@synnaxlabs/client 0.50.0 → 0.53.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 (264) hide show
  1. package/.turbo/turbo-build.log +7 -7
  2. package/dist/client.cjs +58 -34
  3. package/dist/client.js +5368 -4546
  4. package/dist/eslint.config.d.ts +2 -2
  5. package/dist/eslint.config.d.ts.map +1 -1
  6. package/dist/src/access/policy/client.d.ts +90 -90
  7. package/dist/src/access/policy/payload.d.ts +17 -17
  8. package/dist/src/access/role/payload.d.ts +2 -2
  9. package/dist/src/arc/payload.d.ts +2 -2
  10. package/dist/src/channel/client.d.ts +4 -5
  11. package/dist/src/channel/client.d.ts.map +1 -1
  12. package/dist/src/channel/payload.d.ts +9 -11
  13. package/dist/src/channel/payload.d.ts.map +1 -1
  14. package/dist/src/channel/retriever.d.ts.map +1 -1
  15. package/dist/src/client.d.ts +10 -0
  16. package/dist/src/client.d.ts.map +1 -1
  17. package/dist/src/device/client.d.ts +14 -7
  18. package/dist/src/device/client.d.ts.map +1 -1
  19. package/dist/src/device/payload.d.ts +65 -32
  20. package/dist/src/device/payload.d.ts.map +1 -1
  21. package/dist/src/device/payload.spec.d.ts +2 -0
  22. package/dist/src/device/payload.spec.d.ts.map +1 -0
  23. package/dist/src/framer/adapter.d.ts.map +1 -1
  24. package/dist/src/framer/client.d.ts +2 -2
  25. package/dist/src/framer/frame.d.ts +5 -5
  26. package/dist/src/framer/frame.d.ts.map +1 -1
  27. package/dist/src/framer/streamer.d.ts +6 -6
  28. package/dist/src/framer/writer.d.ts +9 -9
  29. package/dist/src/group/access.spec.d.ts.map +1 -0
  30. package/dist/src/{ontology/group → group}/client.d.ts +3 -3
  31. package/dist/src/group/client.d.ts.map +1 -0
  32. package/dist/src/group/external.d.ts.map +1 -0
  33. package/dist/src/group/group.spec.d.ts.map +1 -0
  34. package/dist/src/group/index.d.ts.map +1 -0
  35. package/dist/src/{ontology/group → group}/payload.d.ts +1 -1
  36. package/dist/src/group/payload.d.ts.map +1 -0
  37. package/dist/src/index.d.ts +5 -5
  38. package/dist/src/index.d.ts.map +1 -1
  39. package/dist/src/label/client.d.ts +27 -13
  40. package/dist/src/label/client.d.ts.map +1 -1
  41. package/dist/src/label/payload.d.ts +15 -1
  42. package/dist/src/label/payload.d.ts.map +1 -1
  43. package/dist/src/lineplot/access.spec.d.ts.map +1 -0
  44. package/dist/src/{workspace/lineplot → lineplot}/client.d.ts +6 -6
  45. package/dist/src/lineplot/client.d.ts.map +1 -0
  46. package/dist/src/lineplot/external.d.ts.map +1 -0
  47. package/dist/src/lineplot/index.d.ts.map +1 -0
  48. package/dist/src/lineplot/lineplot.spec.d.ts.map +1 -0
  49. package/dist/src/lineplot/payload.d.ts.map +1 -0
  50. package/dist/src/log/access.spec.d.ts.map +1 -0
  51. package/dist/src/{workspace/log → log}/client.d.ts +6 -6
  52. package/dist/src/log/client.d.ts.map +1 -0
  53. package/dist/src/log/external.d.ts.map +1 -0
  54. package/dist/src/log/index.d.ts.map +1 -0
  55. package/dist/src/log/log.spec.d.ts.map +1 -0
  56. package/dist/src/log/payload.d.ts.map +1 -0
  57. package/dist/src/ontology/client.d.ts +6 -10
  58. package/dist/src/ontology/client.d.ts.map +1 -1
  59. package/dist/src/ontology/payload.d.ts +22 -22
  60. package/dist/src/ontology/writer.d.ts +15 -15
  61. package/dist/src/rack/client.d.ts +3 -3
  62. package/dist/src/rack/client.d.ts.map +1 -1
  63. package/dist/src/rack/payload.d.ts +44 -16
  64. package/dist/src/rack/payload.d.ts.map +1 -1
  65. package/dist/src/ranger/alias/client.d.ts +17 -0
  66. package/dist/src/ranger/alias/client.d.ts.map +1 -0
  67. package/dist/src/ranger/alias/external.d.ts +2 -0
  68. package/dist/src/ranger/alias/external.d.ts.map +1 -0
  69. package/dist/src/ranger/alias/index.d.ts +2 -0
  70. package/dist/src/ranger/alias/index.d.ts.map +1 -0
  71. package/dist/src/ranger/{alias.d.ts → alias/payload.d.ts} +14 -20
  72. package/dist/src/ranger/alias/payload.d.ts.map +1 -0
  73. package/dist/src/ranger/client.d.ts +10 -10
  74. package/dist/src/ranger/client.d.ts.map +1 -1
  75. package/dist/src/ranger/external.d.ts +20 -0
  76. package/dist/src/ranger/external.d.ts.map +1 -1
  77. package/dist/src/ranger/kv/client.d.ts +14 -0
  78. package/dist/src/ranger/kv/client.d.ts.map +1 -0
  79. package/dist/src/ranger/kv/external.d.ts +2 -0
  80. package/dist/src/ranger/kv/external.d.ts.map +1 -0
  81. package/dist/src/ranger/kv/index.d.ts +2 -0
  82. package/dist/src/ranger/kv/index.d.ts.map +1 -0
  83. package/dist/src/ranger/kv/payload.d.ts +26 -0
  84. package/dist/src/ranger/kv/payload.d.ts.map +1 -0
  85. package/dist/src/ranger/payload.d.ts +45 -3
  86. package/dist/src/ranger/payload.d.ts.map +1 -1
  87. package/dist/src/ranger/writer.d.ts +18 -4
  88. package/dist/src/ranger/writer.d.ts.map +1 -1
  89. package/dist/src/schematic/access.spec.d.ts.map +1 -0
  90. package/dist/src/{workspace/schematic → schematic}/client.d.ts +6 -6
  91. package/dist/src/schematic/client.d.ts.map +1 -0
  92. package/dist/src/schematic/external.d.ts.map +1 -0
  93. package/dist/src/schematic/index.d.ts.map +1 -0
  94. package/dist/src/schematic/payload.d.ts.map +1 -0
  95. package/dist/src/schematic/schematic.spec.d.ts.map +1 -0
  96. package/dist/src/schematic/symbol/access.spec.d.ts.map +1 -0
  97. package/dist/src/{workspace/schematic → schematic}/symbol/client.d.ts +2 -2
  98. package/dist/src/schematic/symbol/client.d.ts.map +1 -0
  99. package/dist/src/schematic/symbol/client.spec.d.ts.map +1 -0
  100. package/dist/src/schematic/symbol/external.d.ts.map +1 -0
  101. package/dist/src/schematic/symbol/index.d.ts.map +1 -0
  102. package/dist/src/schematic/symbol/payload.d.ts.map +1 -0
  103. package/dist/src/status/payload.d.ts +43 -7
  104. package/dist/src/status/payload.d.ts.map +1 -1
  105. package/dist/src/table/access.spec.d.ts.map +1 -0
  106. package/dist/src/{workspace/table → table}/client.d.ts +6 -6
  107. package/dist/src/table/client.d.ts.map +1 -0
  108. package/dist/src/table/external.d.ts.map +1 -0
  109. package/dist/src/table/index.d.ts.map +1 -0
  110. package/dist/src/table/payload.d.ts.map +1 -0
  111. package/dist/src/table/table.spec.d.ts.map +1 -0
  112. package/dist/src/task/client.d.ts +19 -21
  113. package/dist/src/task/client.d.ts.map +1 -1
  114. package/dist/src/task/payload.d.ts +32 -27
  115. package/dist/src/task/payload.d.ts.map +1 -1
  116. package/dist/src/user/client.d.ts +2 -2
  117. package/dist/src/view/client.d.ts +2 -2
  118. package/dist/src/workspace/client.d.ts +2 -10
  119. package/dist/src/workspace/client.d.ts.map +1 -1
  120. package/eslint.config.ts +2 -3
  121. package/package.json +10 -9
  122. package/src/arc/lsp.spec.ts +155 -283
  123. package/src/channel/client.ts +3 -5
  124. package/src/channel/payload.spec.ts +0 -57
  125. package/src/channel/payload.ts +7 -14
  126. package/src/channel/retriever.ts +2 -3
  127. package/src/client.ts +16 -1
  128. package/src/device/client.ts +89 -43
  129. package/src/device/payload.spec.ts +118 -0
  130. package/src/device/payload.ts +55 -30
  131. package/src/errors.spec.ts +1 -1
  132. package/src/framer/adapter.ts +5 -7
  133. package/src/framer/frame.ts +8 -8
  134. package/src/{ontology/group → group}/access.spec.ts +7 -7
  135. package/src/{ontology/group → group}/client.ts +1 -1
  136. package/src/group/external.ts +11 -0
  137. package/src/{ontology/group → group}/group.spec.ts +9 -9
  138. package/src/{workspace/log → group}/index.ts +1 -1
  139. package/src/index.ts +5 -5
  140. package/src/label/access.spec.ts +1 -1
  141. package/src/label/client.ts +1 -1
  142. package/src/label/label.spec.ts +4 -4
  143. package/src/{workspace/lineplot → lineplot}/access.spec.ts +14 -14
  144. package/src/{workspace/lineplot → lineplot}/client.ts +13 -13
  145. package/src/lineplot/external.ts +11 -0
  146. package/src/{ontology/group → lineplot}/index.ts +1 -1
  147. package/src/{workspace/lineplot → lineplot}/lineplot.spec.ts +12 -12
  148. package/src/{workspace/log → log}/access.spec.ts +16 -18
  149. package/src/{workspace/log → log}/client.ts +13 -13
  150. package/src/{workspace/schematic/index.ts → log/external.ts} +2 -1
  151. package/src/{workspace/table → log}/index.ts +1 -1
  152. package/src/{workspace/log → log}/log.spec.ts +10 -10
  153. package/src/ontology/client.ts +1 -7
  154. package/src/ontology/ontology.spec.ts +12 -12
  155. package/src/rack/client.ts +10 -21
  156. package/src/ranger/{alias.ts → alias/client.ts} +6 -37
  157. package/src/{workspace/lineplot → ranger/alias}/external.ts +10 -2
  158. package/src/{workspace/lineplot → ranger/alias}/index.ts +1 -1
  159. package/src/ranger/alias/payload.ts +50 -0
  160. package/src/ranger/client.ts +26 -19
  161. package/src/ranger/external.ts +22 -0
  162. package/src/ranger/{kv.ts → kv/client.ts} +5 -19
  163. package/src/{workspace/schematic → ranger/kv}/external.ts +7 -3
  164. package/src/ranger/kv/index.ts +10 -0
  165. package/src/ranger/kv/payload.ts +32 -0
  166. package/src/ranger/payload.ts +2 -2
  167. package/src/ranger/ranger.spec.ts +1 -1
  168. package/src/{workspace/schematic → schematic}/access.spec.ts +14 -14
  169. package/src/{workspace/schematic → schematic}/client.ts +14 -14
  170. package/src/{workspace/log → schematic}/external.ts +3 -2
  171. package/src/schematic/index.ts +10 -0
  172. package/src/{workspace/schematic → schematic}/schematic.spec.ts +17 -17
  173. package/src/{workspace/schematic → schematic}/symbol/access.spec.ts +19 -19
  174. package/src/{workspace/schematic → schematic}/symbol/client.spec.ts +16 -16
  175. package/src/{workspace/schematic → schematic}/symbol/client.ts +8 -8
  176. package/src/{ontology/group → schematic/symbol}/external.ts +2 -2
  177. package/src/schematic/symbol/index.ts +10 -0
  178. package/src/status/payload.ts +1 -1
  179. package/src/status/status.spec.ts +2 -2
  180. package/src/{workspace/table → table}/access.spec.ts +14 -14
  181. package/src/{workspace/table → table}/client.ts +15 -12
  182. package/src/table/external.ts +11 -0
  183. package/src/table/index.ts +10 -0
  184. package/src/{workspace/table → table}/table.spec.ts +12 -12
  185. package/src/task/client.ts +56 -148
  186. package/src/task/payload.ts +34 -58
  187. package/src/workspace/client.ts +0 -12
  188. package/dist/src/ontology/group/access.spec.d.ts.map +0 -1
  189. package/dist/src/ontology/group/client.d.ts.map +0 -1
  190. package/dist/src/ontology/group/external.d.ts.map +0 -1
  191. package/dist/src/ontology/group/group.spec.d.ts.map +0 -1
  192. package/dist/src/ontology/group/index.d.ts.map +0 -1
  193. package/dist/src/ontology/group/payload.d.ts.map +0 -1
  194. package/dist/src/ranger/alias.d.ts.map +0 -1
  195. package/dist/src/ranger/kv.d.ts +0 -48
  196. package/dist/src/ranger/kv.d.ts.map +0 -1
  197. package/dist/src/workspace/lineplot/access.spec.d.ts.map +0 -1
  198. package/dist/src/workspace/lineplot/client.d.ts.map +0 -1
  199. package/dist/src/workspace/lineplot/external.d.ts.map +0 -1
  200. package/dist/src/workspace/lineplot/index.d.ts.map +0 -1
  201. package/dist/src/workspace/lineplot/lineplot.spec.d.ts.map +0 -1
  202. package/dist/src/workspace/lineplot/payload.d.ts.map +0 -1
  203. package/dist/src/workspace/log/access.spec.d.ts.map +0 -1
  204. package/dist/src/workspace/log/client.d.ts.map +0 -1
  205. package/dist/src/workspace/log/external.d.ts.map +0 -1
  206. package/dist/src/workspace/log/index.d.ts.map +0 -1
  207. package/dist/src/workspace/log/log.spec.d.ts.map +0 -1
  208. package/dist/src/workspace/log/payload.d.ts.map +0 -1
  209. package/dist/src/workspace/schematic/access.spec.d.ts.map +0 -1
  210. package/dist/src/workspace/schematic/client.d.ts.map +0 -1
  211. package/dist/src/workspace/schematic/external.d.ts.map +0 -1
  212. package/dist/src/workspace/schematic/index.d.ts.map +0 -1
  213. package/dist/src/workspace/schematic/payload.d.ts.map +0 -1
  214. package/dist/src/workspace/schematic/schematic.spec.d.ts.map +0 -1
  215. package/dist/src/workspace/schematic/symbol/access.spec.d.ts.map +0 -1
  216. package/dist/src/workspace/schematic/symbol/client.d.ts.map +0 -1
  217. package/dist/src/workspace/schematic/symbol/client.spec.d.ts.map +0 -1
  218. package/dist/src/workspace/schematic/symbol/external.d.ts.map +0 -1
  219. package/dist/src/workspace/schematic/symbol/index.d.ts.map +0 -1
  220. package/dist/src/workspace/schematic/symbol/payload.d.ts.map +0 -1
  221. package/dist/src/workspace/table/access.spec.d.ts.map +0 -1
  222. package/dist/src/workspace/table/client.d.ts.map +0 -1
  223. package/dist/src/workspace/table/external.d.ts.map +0 -1
  224. package/dist/src/workspace/table/index.d.ts.map +0 -1
  225. package/dist/src/workspace/table/payload.d.ts.map +0 -1
  226. package/dist/src/workspace/table/table.spec.d.ts.map +0 -1
  227. package/src/workspace/schematic/symbol/external.ts +0 -11
  228. package/src/workspace/schematic/symbol/index.ts +0 -10
  229. package/src/workspace/table/external.ts +0 -11
  230. /package/dist/src/{ontology/group → group}/access.spec.d.ts +0 -0
  231. /package/dist/src/{ontology/group → group}/external.d.ts +0 -0
  232. /package/dist/src/{ontology/group → group}/group.spec.d.ts +0 -0
  233. /package/dist/src/{ontology/group → group}/index.d.ts +0 -0
  234. /package/dist/src/{workspace/lineplot → lineplot}/access.spec.d.ts +0 -0
  235. /package/dist/src/{workspace/lineplot → lineplot}/external.d.ts +0 -0
  236. /package/dist/src/{workspace/lineplot → lineplot}/index.d.ts +0 -0
  237. /package/dist/src/{workspace/lineplot → lineplot}/lineplot.spec.d.ts +0 -0
  238. /package/dist/src/{workspace/lineplot → lineplot}/payload.d.ts +0 -0
  239. /package/dist/src/{workspace/log → log}/access.spec.d.ts +0 -0
  240. /package/dist/src/{workspace/log → log}/external.d.ts +0 -0
  241. /package/dist/src/{workspace/log → log}/index.d.ts +0 -0
  242. /package/dist/src/{workspace/log → log}/log.spec.d.ts +0 -0
  243. /package/dist/src/{workspace/log → log}/payload.d.ts +0 -0
  244. /package/dist/src/{workspace/schematic → schematic}/access.spec.d.ts +0 -0
  245. /package/dist/src/{workspace/schematic → schematic}/external.d.ts +0 -0
  246. /package/dist/src/{workspace/schematic → schematic}/index.d.ts +0 -0
  247. /package/dist/src/{workspace/schematic → schematic}/payload.d.ts +0 -0
  248. /package/dist/src/{workspace/schematic → schematic}/schematic.spec.d.ts +0 -0
  249. /package/dist/src/{workspace/schematic → schematic}/symbol/access.spec.d.ts +0 -0
  250. /package/dist/src/{workspace/schematic → schematic}/symbol/client.spec.d.ts +0 -0
  251. /package/dist/src/{workspace/schematic → schematic}/symbol/external.d.ts +0 -0
  252. /package/dist/src/{workspace/schematic → schematic}/symbol/index.d.ts +0 -0
  253. /package/dist/src/{workspace/schematic → schematic}/symbol/payload.d.ts +0 -0
  254. /package/dist/src/{workspace/table → table}/access.spec.d.ts +0 -0
  255. /package/dist/src/{workspace/table → table}/external.d.ts +0 -0
  256. /package/dist/src/{workspace/table → table}/index.d.ts +0 -0
  257. /package/dist/src/{workspace/table → table}/payload.d.ts +0 -0
  258. /package/dist/src/{workspace/table → table}/table.spec.d.ts +0 -0
  259. /package/src/{ontology/group → group}/payload.ts +0 -0
  260. /package/src/{workspace/lineplot → lineplot}/payload.ts +0 -0
  261. /package/src/{workspace/log → log}/payload.ts +0 -0
  262. /package/src/{workspace/schematic → schematic}/payload.ts +0 -0
  263. /package/src/{workspace/schematic → schematic}/symbol/payload.ts +0 -0
  264. /package/src/{workspace/table → table}/payload.ts +0 -0
package/dist/client.cjs CHANGED
@@ -1,65 +1,89 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("zod"),uh=t=>{const e=t.replace(/_[a-z]/g,n=>n[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Oa=t=>{const e=(n,r=Sr)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!ar(n))return n;r=dh(r);const s={},a=n;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),r):(Object.keys(a).forEach(o=>{let c=a[o];const l=t(o);r.recursive&&(ar(c)?gi(c)||(c=e(c,r)):r.recursiveInArray&&mi(c)&&(c=[...c].map(u=>{let h=u;return ar(u)?gi(h)||(h=e(u,r)):mi(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},Ea=Oa(uh),lh=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),hh=Oa(lh),fh=[Number,String,Uint8Array],Sr={recursive:!0,recursiveInArray:!0},dh=(t=Sr)=>(t.recursive==null?t=Sr:t.recursiveInArray??=!1,t),mi=t=>t!=null&&Array.isArray(t),ar=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),gi=t=>fh.some(e=>t instanceof e);let yh=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e))}decode(e,n){return this.decodeString(this.decoder.decode(e),n)}decodeString(e,n){const r=JSON.parse(e),s=Ea(r);return n!=null?n.parse(s):s}encodeString(e){const n=hh(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}};const kr=new yh,ue=t=>t!=null&&typeof t=="object"&&"value"in t;class $t{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const ph=t=>t!=null&&typeof t=="object"&&"toString"in t,mh=(t,e=!1)=>{const n=ph(t)?"stringer":typeof t;let r;switch(n){case"string":r=(s,a)=>s.localeCompare(a);break;case"stringer":r=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":r=(s,a)=>Number(s)-Number(a);break;case"bigint":r=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":r=(s,a)=>Number(s)-Number(a);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return e?gh(r):r},gh=t=>(e,n)=>t(n,e);let Na=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const Sa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wh=`0123456789${Sa}`,bh=11,vh=Na(Sa,1),zh=Na(wh,bh-1),Th=()=>`${vh()}${zh()}`,Oh=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,Eh=2**12-1,Ar=2n**63n-1n,Nh=2**63-1,jn=t=>(e,n)=>{if(typeof e=="bigint"){if(Sh(n))return t(e,BigInt(n));const r=t(Number(e),Number(n));return typeof r=="number"?BigInt(Math.round(r)):r}return t(Number(e),Number(n))},Qt=jn((t,e)=>t-e),nt=jn((t,e)=>t+e),Sh=t=>typeof t=="bigint"?!0:Number.isInteger(t),Oe=jn((t,e)=>t*e),Mn=jn((t,e)=>t/e),ka=i.z.tuple([i.z.number(),i.z.number()]),Aa=i.z.object({width:i.z.number(),height:i.z.number()}),kh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),Ah=["start","center","end"],qt=i.z.object({x:i.z.number(),y:i.z.number()}),$h=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),Ih=["x","y"],$a=i.z.enum(Ih),Ia=["top","right","bottom","left"];i.z.enum(Ia);const Zh=["left","right"],Za=i.z.enum(Zh),xh=["top","bottom"],xa=i.z.enum(xh),Ca=["center"],wi=i.z.enum(Ca),Ch=[...Ia,...Ca],_a=i.z.enum(Ch);i.z.enum(Ah);const _h=["first","last"];i.z.enum(_h);i.z.object({lower:i.z.number(),upper:i.z.number()});i.z.enum([...$a.options,..._a.options]);i.z.union([$a,_a,i.z.instanceof(String)]);const rt=(t,e,n)=>{const r={};if(typeof e=="object"&&(n=e,e=void 0),n={makeValid:!0,...n},typeof t=="number"||typeof t=="bigint")e!=null?(r.lower=t,r.upper=e):(r.lower=typeof t=="bigint"?0n:0,r.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[r.lower,r.upper]=t}else r.lower=t.lower,r.upper=t.upper;return n?.makeValid?Rh(r):r},Rh=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,bi=(t,e)=>{const n=rt(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e};i.z.object({x:Za.or(wi),y:xa.or(wi)});const Ra=i.z.object({x:Za,y:xa}),jh=Object.freeze({x:"left",y:"top"}),Mh=(t,e)=>t.x===e.x&&t.y===e.y,vi=i.z.union([i.z.number(),qt,ka,Aa,kh,$h]),Uh=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},zi=Object.freeze({x:0,y:0}),pn=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:pn,left:pn,width:pn,height:pn});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:qt,two:qt,root:Ra});const os=(t,e,n=0,r=0,s)=>{const a={one:{...zi},two:{...zi},root:s??jh};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:t,y:e},a.two={x:a.one.x+n,y:a.one.y+r},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(a.one={x:t.left,y:t.top},a.two={x:t.right,y:t.bottom},a):(a.one=t,e==null?a.two={x:a.one.x+n,y:a.one.y+r}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+n}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},or=t=>{const e=os(t);return{lower:e.one.x,upper:e.two.x}},cr=t=>{const e=os(t);return{lower:e.one.y,upper:e.two.y}},Dh=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,Lh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([Aa,Lh,qt,ka]);const Ph=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:vi,scale:vi});i.z.object({offset:i.z.number(),scale:i.z.number()});const Bh=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],qh=t=>(e,n,r,s)=>[e,s?r/t:r*t],Fh=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:a}=e,{lower:o,upper:c}=t,l=a-s,u=c-o;if(n==="dimension")return[t,r*(u/l)];const h=(r-s)*(u/l)+o;return[t,h]},Yh=t=>(e,n,r)=>[t,r],Gh=()=>(t,e,n)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,n];const{lower:r,upper:s}=t;return[t,s-(n-r)]},Hh=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=Ph(r,s,a),[e,r]};class qe{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new qe().translate(e)}static magnify(e){return new qe().magnify(e)}static scale(e,n){return new qe().scale(e,n)}translate(e){const n=this.new(),r=Bh(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=qh(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=rt(e,n),s=this.new(),a=Fh(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=rt(e,n),s=this.new(),a=Hh(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=rt(e,n),s=this.new(),a=Yh(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Gh();e.type="invert";const n=this.new();return n.ops.push(e),n}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new qe;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],a)=>a(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&n.push([s,a])}),n.forEach(([r,s])=>{const a=e.ops.slice(r,s);a.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new qe}class ze{x;y;currRoot;constructor(e=new qe,n=new qe,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new ze().translate(e,n)}static translateX(e){return new ze().translateX(e)}static translateY(e){return new ze().translateY(e)}static clamp(e){return new ze().clamp(e)}static magnify(e){return new ze().magnify(e)}static scale(e){return new ze().scale(e)}static reBound(e){return new ze().reBound(e)}translate(e,n){const r=Uh(e,n),s=this.copy();return s.x=this.x.translate(r.x),s.y=this.y.translate(r.y),s}translateX(e){const n=this.copy();return n.x=this.x.translate(e),n}translateY(e){const n=this.copy();return n.y=this.y.translate(e),n}magnify(e){const n=this.copy();return n.x=this.x.magnify(e.x),n.y=this.y.magnify(e.y),n}scale(e){const n=this.copy();if(Dh(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!Mh(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(or(e)),n.y=n.y.scale(cr(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(or(e)),n.y=this.y.reBound(cr(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(or(e)),n.y=this.y.clamp(cr(e)),n}copy(){const e=new ze;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return os(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new ze}const Vh=qt.extend({root:Ra,units:i.object({x:i.enum(["px","decimal"]),y:i.enum(["px","decimal"])})});Vh.partial({root:!0,units:!0});const Wh=i.z.enum(["static","dynamic"]),Ti=365,mn=30,Kh=i.z.union([i.z.tuple([i.z.int()]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12)]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12),i.z.int().min(1).max(31)])]),ja=(t,e)=>{const n=new b(e);if(![v.DAY,v.HOUR,v.MINUTE,v.SECOND,v.MILLISECOND,v.MICROSECOND,v.NANOSECOND].some(s=>s.equals(n)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=t.valueOf()%n.valueOf();return t instanceof b?new b(r):new v(r)};class b extends $t{constructor(e,n="UTC"){if(e==null)super(b.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*b.MILLISECOND.valueOf());else if(typeof e=="string")super(b.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(b.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=b.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===Nh?e=Ar:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=b.MAX:e=b.MIN)),ue(e)&&(e=e.value),super(BigInt(e.valueOf())+r)}}static parseDate([e=1970,n=1,r=1]){const s=new Date(e,n-1,r,0,0,0,0);return new b(BigInt(s.getTime())*b.MILLISECOND.valueOf()).truncate(b.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let l=b.hours(parseInt(r??"00")).add(b.minutes(parseInt(s??"00"))).add(b.seconds(parseInt(o??"00"))).add(b.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(b.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return b.parseTimeString(e,n);if(e.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let s=e,a=0;if(e.includes(".")){const u=e.split(".");s=u[0];const h=u[1]||"0";a=parseInt(h.padEnd(3,"0").slice(0,3))}const o=n==="local"?new Date(s.replace("T"," ")):new Date(`${s}Z`),c=BigInt(o.getTime())*b.MILLISECOND.valueOf(),l=BigInt(a)*b.MILLISECOND.valueOf();return c+l}const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new b(BigInt(r.getTime())*b.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(b.utcOffset).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new v(BigInt(new Date().getTimezoneOffset())*b.MINUTE.valueOf())}static since(e){return new b().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new b(e).valueOf()}span(e){return this.range(e).span}range(e){return new Mt(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new b(e).valueOf()}afterEq(e){return this.valueOf()>=new b(e).valueOf()}before(e){return this.valueOf()<new b(e).valueOf()}beforeEq(e){return this.valueOf()<=new b(e).valueOf()}add(e){return new b(nt(this.valueOf(),new v(e).valueOf()))}sub(e){return new b(Qt(this.valueOf(),new v(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(v.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(v.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(v.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(v.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(b.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(b.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new b(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new b(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new b(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new b(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new b(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new b(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new b(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new b(n)}toString(e="ISO",n="UTC"){switch(e){case"ISODate":return this.toISOString(n).slice(0,10);case"ISOTime":return this.toISOString(n).slice(11,23);case"time":return this.timeString(!1,n);case"preciseTime":return this.timeString(!0,n);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,n)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,n)}`;default:return this.toISOString(n)}}remainder(e){return ja(this,e)}get isToday(){return this.truncate(v.DAY).equals(b.now().truncate(v.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(v.days(30))?"shortDate":e.greaterThanOrEqual(v.DAY)?"dateTime":e.greaterThanOrEqual(v.HOUR)?"time":e.greaterThanOrEqual(v.SECOND)?"preciseTime":"ISOTime"}static now(){return new b(new Date)}static max(...e){let n=b.MIN;for(const r of e){const s=new b(r);s.after(n)&&(n=s)}return n}static min(...e){let n=b.MAX;for(const r of e){const s=new b(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new b(e,n)}static NANOSECOND=b.nanoseconds(1);static microseconds(e,n="UTC"){return b.nanoseconds(e*1e3,n)}static MICROSECOND=b.microseconds(1);static milliseconds(e,n="UTC"){return b.microseconds(e*1e3,n)}static MILLISECOND=b.milliseconds(1);static seconds(e,n="UTC"){return b.milliseconds(e*1e3,n)}static SECOND=b.seconds(1);static minutes(e,n="UTC"){return b.seconds(e*60,n)}static MINUTE=b.minutes(1);static hours(e,n="UTC"){return b.minutes(e*60,n)}static HOUR=b.hours(1);static days(e,n="UTC"){return b.hours(e*24,n)}static DAY=b.days(1);static MAX=new b(Ar);static MIN=new b(0);static ZERO=new b(0);static z=i.z.union([i.z.instanceof(b),i.z.object({value:i.z.bigint()}).transform(e=>new b(e.value)),i.z.string().transform(e=>new b(BigInt(e))),i.z.number().transform(e=>new b(e)),i.z.bigint().transform(e=>new b(e)),i.z.date().transform(e=>new b(e)),i.z.custom(e=>e instanceof v).transform(e=>new b(e)),Kh.transform(e=>new b(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}}class v extends $t{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),ue(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof v?e:e instanceof ur?e.period:e instanceof b?new v(e):(ue(e)&&(e=e.value),["number","bigint"].includes(typeof e)?v.seconds(e):new v(e))}static fromMilliseconds(e){return e instanceof v?e:e instanceof ur?e.period:e instanceof b?new v(e):(ue(e)&&(e=e.value),["number","bigint"].includes(typeof e)?v.milliseconds(e):new v(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new v(e).valueOf()}greaterThan(e){return this.valueOf()>new v(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new v(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new v(e).valueOf()}remainder(e){return ja(this,e)}truncate(e){return new v(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(v.DAY),r=this.truncate(v.HOUR),s=this.truncate(v.MINUTE),a=this.truncate(v.SECOND),o=this.truncate(v.MILLISECOND),c=this.truncate(v.MICROSECOND),l=this.truncate(v.NANOSECOND),u=n,h=r.sub(n),d=s.sub(r),f=a.sub(s),O=o.sub(a),S=c.sub(o),Z=l.sub(c);let T="";return u.isZero||(T+=`${u.days}d `),h.isZero||(T+=`${h.hours}h `),d.isZero||(T+=`${d.minutes}m `),f.isZero||(T+=`${f.seconds}s `),O.isZero||(T+=`${O.milliseconds}ms `),S.isZero||(T+=`${S.microseconds}µs `),Z.isZero||(T+=`${Z.nanoseconds}ns`),T.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new v(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(v.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/Ti),u=Math.floor(s/mn),h=Math.floor(s/7),d=Math.floor(s),f=Math.floor(a),O=Math.floor(o),S=Math.floor(c),Z=r?"-":"";if(l>=1){let T=`${l}y`;if(l<2){const E=Math.floor(s%Ti/mn);E>0&&(T+=` ${E}mo`)}return Z+T}if(h>=1&&s<mn&&s%7===0){let T=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?T+=` ${E}d`:A>0&&A<24&&(T+=` ${A}h`)),Z+T}if(u>=1){let T=`${u}mo`;if(u<3){const E=Math.floor(s%mn);E>0&&(T+=` ${E}d`)}return Z+T}if(h>=1){let T=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?T+=` ${E}d`:A>0&&A<24&&(T+=` ${A}h`)),Z+T}if(d>=1){let T=`${d}d`;const E=Math.floor(a-d*24);return d<2&&E>0&&(T+=` ${E}h`),Z+T}if(f>=1){let T=`${f}h`;if(f<3){const E=Math.floor(o-f*60);E>0&&(T+=` ${E}m`)}return Z+T}if(O>=1){let T=`${O}m`;if(O<5){const E=Math.floor(c-O*60);E>0&&(T+=` ${E}s`)}return Z+T}return`${Z}${S}s`}mult(e){return new v(Oe(this.valueOf(),e))}div(e){return new v(Mn(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(v.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(v.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(v.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(v.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(v.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new v(e).valueOf()}add(e){return new v(this.valueOf()+new v(e).valueOf())}sub(e){return new v(this.valueOf()-new v(e).valueOf())}static nanoseconds(e=1){return new v(e)}static NANOSECOND=v.nanoseconds(1);static microseconds(e=1){return v.nanoseconds(Oe(e,1e3))}static MICROSECOND=v.microseconds(1);static milliseconds(e=1){return v.microseconds(Oe(e,1e3))}static MILLISECOND=v.milliseconds(1);static seconds(e=1){return v.milliseconds(Oe(e,1e3))}static SECOND=v.seconds(1);static minutes(e=1){return v.seconds(Oe(e,60))}static MINUTE=v.minutes(1);static hours(e){return v.minutes(Oe(e,60))}static HOUR=v.hours(1);static days(e){return v.hours(Oe(e,24))}static DAY=v.days(1);static MAX=new v(Ar);static MIN=new v(0);static ZERO=new v(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new v(e.value)),i.z.string().transform(e=>new v(BigInt(e))),i.z.number().transform(e=>new v(e)),i.z.bigint().transform(e=>new v(e)),i.z.instanceof(v),i.z.instanceof(b).transform(e=>new v(e)),i.z.custom(e=>e instanceof ur).transform(e=>new v(e))])}let ur=class ce extends $t{constructor(e){ue(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new ce(e).valueOf()}get period(){return v.seconds(1/this.valueOf())}sampleCount(e){return new v(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new ee(n).valueOf()}span(e){return v.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new ee(n).valueOf())}add(e){return new ce(nt(this.valueOf(),new ce(e).valueOf()))}sub(e){return new ce(Qt(this.valueOf(),new ce(e).valueOf()))}mult(e){return new ce(Oe(this.valueOf(),e))}div(e){return new ce(Mn(this.valueOf(),e))}static hz(e){return new ce(e)}static khz(e){return ce.hz(e*1e3)}static z=i.z.union([i.z.number().transform(e=>new ce(e)),i.z.instanceof(ce)])},ee=class ne extends $t{constructor(e){ue(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new I(e*this.valueOf())}add(e){return new ne(nt(this.valueOf(),new ne(e).valueOf()))}sub(e){return new ne(Qt(this.valueOf(),new ne(e).valueOf()))}mult(e){return new ne(Oe(this.valueOf(),e))}div(e){return new ne(Mn(this.valueOf(),e))}static UNKNOWN=new ne(0);static BIT128=new ne(16);static BIT64=new ne(8);static BIT32=new ne(4);static BIT16=new ne(2);static BIT8=new ne(1);static z=i.z.union([i.z.number().transform(e=>new ne(e)),i.z.instanceof(ne)])},Mt=class pe{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new b(e.start),this.end=new b(e.end)):(this.start=new b(e),this.end=new b(n))}get span(){return new v(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new pe(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=v.ZERO){if(n.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return r<0&&(r=-r),s<0&&(s=-s),r<=n.valueOf()&&s<=n.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,n=v.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const s=b.max(r.start,e.start),a=b.min(r.end,e.end);return a.before(s)?!1:new v(a.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof pe?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new pe(this.start,this.end);return e.start.after(this.start)&&(n.start=e.start),e.start.after(this.end)&&(n.end=e.start),e.end.before(this.end)&&(n.end=e.end),e.end.before(this.start)&&(n.start=e.end),n}static max(...e){return new pe(b.min(...e.map(n=>n.start)),b.max(...e.map(n=>n.end)))}static MAX=new pe(b.MIN,b.MAX);static ZERO=new pe(b.ZERO,b.ZERO);static z=i.z.union([i.z.object({start:b.z,end:b.z}).transform(e=>new pe(e.start,e.end)),i.z.instanceof(pe)]);static sort(e,n){return b.sort(e.start,n.start)||b.sort(e.end,n.end)}static merge(...e){return pe.max(...e.map(n=>new pe(n).makeValid()))}};class p extends $t{constructor(e){if(ue(e)&&(e=e.value),e instanceof p||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=p.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(n==null)throw new Error(`unable to find data type for ${e.toString()}`);super(n.valueOf())}}get Array(){const e=p.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(n=>this.equals(n))}toString(e=!1){return e?p.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(p.JSON)||this.equals(p.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(p.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=p.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(p.UINT8)||this.equals(p.UINT16)||this.equals(p.UINT32)||this.equals(p.UINT64)}get isSignedInteger(){return this.equals(p.INT8)||this.equals(p.INT16)||this.equals(p.INT32)||this.equals(p.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(p.INT32)&&e.equals(p.FLOAT64)||this.equals(p.INT8)&&e.equals(p.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return p.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new p("unknown");static FLOAT64=new p("float64");static FLOAT32=new p("float32");static INT64=new p("int64");static INT32=new p("int32");static INT16=new p("int16");static INT8=new p("int8");static UINT64=new p("uint64");static UINT32=new p("uint32");static UINT16=new p("uint16");static UINT8=new p("uint8");static BOOLEAN=new p("boolean");static TIMESTAMP=new p("timestamp");static UUID=new p("uuid");static STRING=new p("string");static JSON=new p("json");static ARRAY_CONSTRUCTORS=new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]]);static DENSITIES=new Map([[p.UINT8.toString(),ee.BIT8],[p.UINT16.toString(),ee.BIT16],[p.UINT32.toString(),ee.BIT32],[p.UINT64.toString(),ee.BIT64],[p.FLOAT32.toString(),ee.BIT32],[p.FLOAT64.toString(),ee.BIT64],[p.INT8.toString(),ee.BIT8],[p.INT16.toString(),ee.BIT16],[p.INT32.toString(),ee.BIT32],[p.INT64.toString(),ee.BIT64],[p.TIMESTAMP.toString(),ee.BIT64],[p.STRING.toString(),ee.UNKNOWN],[p.JSON.toString(),ee.UNKNOWN],[p.UUID.toString(),ee.BIT128]]);static ALL=[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON];static SHORT_STRINGS=new Map([[p.UINT8.toString(),"u8"],[p.UINT16.toString(),"u16"],[p.UINT32.toString(),"u32"],[p.UINT64.toString(),"u64"],[p.INT8.toString(),"i8"],[p.INT16.toString(),"i16"],[p.INT32.toString(),"i32"],[p.INT64.toString(),"i64"],[p.FLOAT32.toString(),"f32"],[p.FLOAT64.toString(),"f64"],[p.BOOLEAN.toString(),"bool"],[p.TIMESTAMP.toString(),"ts"],[p.UUID.toString(),"uuid"],[p.STRING.toString(),"str"],[p.JSON.toString(),"json"]]);static BIG_INT_TYPES=[p.INT64,p.UINT64,p.TIMESTAMP];static z=i.z.union([i.z.string().transform(e=>new p(e)),i.z.instanceof(p)])}class I extends $t{constructor(e){ue(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return ue(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return ue(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return ue(e)&&(e=e.value),new I(nt(this.valueOf(),e.valueOf()))}sub(e){return ue(e)&&(e=e.value),new I(Qt(this.valueOf(),e.valueOf()))}mult(e){return new I(Oe(this.valueOf(),e))}div(e){return new I(Mn(this.valueOf(),e))}truncate(e){return new I(Math.trunc(this.valueOf()/new I(e).valueOf())*new I(e).valueOf())}remainder(e){return I.bytes(this.valueOf()%new I(e).valueOf())}get gigabytes(){return this.valueOf()/I.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/I.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/I.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/I.TERABYTE.valueOf()}toString(){const e=this.truncate(I.TERABYTE),n=this.truncate(I.GIGABYTE),r=this.truncate(I.MEGABYTE),s=this.truncate(I.KILOBYTE),a=this.truncate(I.BYTE),o=e,c=n.sub(e),l=r.sub(n),u=s.sub(r),h=a.sub(s);let d="";return o.isZero||(d+=`${o.terabytes}TB `),c.isZero||(d+=`${c.gigabytes}GB `),l.isZero||(d+=`${l.megabytes}MB `),u.isZero||(d+=`${u.kilobytes}KB `),(!h.isZero||d==="")&&(d+=`${h.valueOf()}B`),d.trim()}static bytes(e=1){return new I(e)}static BYTE=new I(1);static kilobytes(e=1){return I.bytes(new I(e).valueOf()*1e3)}static KILOBYTE=I.kilobytes(1);static megabytes(e=1){return I.kilobytes(new I(e).valueOf()*1e3)}static MEGABYTE=I.megabytes(1);static gigabytes(e=1){return I.megabytes(new I(e).valueOf()*1e3)}static GIGABYTE=I.gigabytes(1);static terabytes(e){return I.gigabytes(new I(e).valueOf()*1e3)}static TERABYTE=I.terabytes(1);static ZERO=new I(0);static z=i.z.union([i.z.number().transform(e=>new I(e)),i.z.instanceof(I)]);get isZero(){return this.valueOf()===0}}i.z.object({start:i.z.number(),end:i.z.number()});i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const Ma=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof b||t instanceof v||t instanceof Date},Jh=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Qt(n,r),Xh=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Qh(t){return typeof t=="string"&&Xh.test(t)}const J=[];for(let t=0;t<256;++t)J.push((t+256).toString(16).slice(1));function ef(t,e=0){return(J[t[e+0]]+J[t[e+1]]+J[t[e+2]]+J[t[e+3]]+"-"+J[t[e+4]]+J[t[e+5]]+"-"+J[t[e+6]]+J[t[e+7]]+"-"+J[t[e+8]]+J[t[e+9]]+"-"+J[t[e+10]]+J[t[e+11]]+J[t[e+12]]+J[t[e+13]]+J[t[e+14]]+J[t[e+15]]).toLowerCase()}function tf(t,e=0){const n=ef(t,e);if(!Qh(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Ua=(t,e)=>tf(t,e),Ue=-1,nf=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),rf=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),$r=10,sf=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Da="sy_x_telem_series";let La=class Be{key;discriminator=Da;dataType;sampleOffset;gl;_data;timeRange=Mt.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Ue;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=i.z.object({timeRange:Mt.z.optional(),dataType:p.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([nf,rf,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:Wh.default("static").optional()});static z=Be.crudeZ.transform(e=>new Be(e));constructor(e){af(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:l=Th(),data:u}=e;if(of(u)){const f=u;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=Ma(u),d=Array.isArray(u);if(n!=null)this.dataType=new p(n);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(d||h){let f=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=u[0]}if(typeof f=="string")this.dataType=p.STRING;else if(typeof f=="number")this.dataType=p.FLOAT64;else if(typeof f=="bigint")this.dataType=p.INT64;else if(typeof f=="boolean")this.dataType=p.BOOLEAN;else if(f instanceof b||f instanceof Date||f instanceof b)this.dataType=p.TIMESTAMP;else if(typeof f=="object")this.dataType=p.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new p(u)}if(!d&&!h)this._data=u;else if(d&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[u]:u;const O=f[0];(O instanceof b||O instanceof Date||O instanceof v)&&(f=f.map(S=>new b(S).valueOf())),this.dataType.equals(p.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("zod"),Ph=t=>{const e=t.replace(/_[a-z]/g,n=>n[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},La=t=>{const e=(n,r=Dr)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!vr(n))return n;r=qh(r);const s={},a=n;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),r):(Object.keys(a).forEach(o=>{let c=a[o];const u=t(o);r.recursive&&(vr(c)?Ii(c)||(c=e(c,r)):r.recursiveInArray&&Ai(c)&&(c=[...c].map(l=>{let h=l;return vr(l)?Ii(h)||(h=e(l,r)):Ai(l)&&(h=e({key:l},r).key),h}))),s[u]=c}),s)};return e},Da=La(Ph),Lh=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),Dh=La(Lh),Bh=[Number,String,Uint8Array],Dr={recursive:!0,recursiveInArray:!0},qh=(t=Dr)=>(t.recursive==null?t=Dr:t.recursiveInArray??=!1,t),Ai=t=>t!=null&&Array.isArray(t),vr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Ii=t=>Bh.some(e=>t instanceof e);class Fh{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e))}decode(e,n){return this.decodeString(this.decoder.decode(e),n)}decodeString(e,n){const r=JSON.parse(e),s=Da(r);return n!=null?n.parse(s):s}encodeString(e){const n=Dh(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}}const Br=new Fh,de=t=>t!=null&&typeof t=="object"&&"value"in t;class It{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const Yh=t=>t!=null&&typeof t=="object"&&"toString"in t,Hh=(t,e=!1)=>{const n=Yh(t)?"stringer":typeof t;let r;switch(n){case"string":r=(s,a)=>s.localeCompare(a);break;case"stringer":r=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":r=(s,a)=>Number(s)-Number(a);break;case"bigint":r=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":r=(s,a)=>Number(s)-Number(a);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return e?Vh(r):r},Vh=t=>(e,n)=>t(n,e);let Ba=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const qa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Gh=`0123456789${qa}`,Wh=11,Jh=Ba(qa,1),Kh=Ba(Gh,Wh-1),Xh=()=>`${Jh()}${Kh()}`,Qh=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,ef=2**12-1,qr=2n**63n-1n,tf=2**63-1,Vn=t=>(e,n)=>{if(typeof e=="bigint"){if(nf(n))return t(e,BigInt(n));const r=t(Number(e),Number(n));return typeof r=="number"?BigInt(Math.round(r)):r}return t(Number(e),Number(n))},an=Vn((t,e)=>t-e),at=Vn((t,e)=>t+e),nf=t=>typeof t=="bigint"?!0:Number.isInteger(t),Ne=Vn((t,e)=>t*e),Gn=Vn((t,e)=>t/e),Fa=i.z.tuple([i.z.number(),i.z.number()]),Ya=i.z.object({width:i.z.number(),height:i.z.number()}),rf=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),sf=["start","center","end"],Gt=i.z.object({x:i.z.number(),y:i.z.number()}),af=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),of=["x","y"],Ha=i.z.enum(of),Va=["top","right","bottom","left"];i.z.enum(Va);const cf=["left","right"],Ga=i.z.enum(cf),uf=["top","bottom"],Wa=i.z.enum(uf),Ja=["center"],Zi=i.z.enum(Ja),lf=[...Va,...Ja],Ka=i.z.enum(lf);i.z.enum(sf);const hf=["first","last"];i.z.enum(hf);i.z.object({lower:i.z.number(),upper:i.z.number()});i.z.enum([...Ha.options,...Ka.options]);i.z.union([Ha,Ka,i.z.instanceof(String)]);const ot=(t,e,n)=>{const r={};if(typeof e=="object"&&(n=e,e=void 0),n={makeValid:!0,...n},typeof t=="number"||typeof t=="bigint")e!=null?(r.lower=t,r.upper=e):(r.lower=typeof t=="bigint"?0n:0,r.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[r.lower,r.upper]=t}else r.lower=t.lower,r.upper=t.upper;return n?.makeValid?ff(r):r},ff=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,xi=(t,e)=>{const n=ot(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e};i.z.object({x:Ga.or(Zi),y:Wa.or(Zi)});const Xa=i.z.object({x:Ga,y:Wa}),df=Object.freeze({x:"left",y:"top"}),pf=(t,e)=>t.x===e.x&&t.y===e.y,Ci=i.z.union([i.z.number(),Gt,Fa,Ya,rf,af]),yf=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},_i=Object.freeze({x:0,y:0}),On=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:On,left:On,width:On,height:On});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:Gt,two:Gt,root:Xa});const vs=(t,e,n=0,r=0,s)=>{const a={one:{..._i},two:{..._i},root:s??df};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:t,y:e},a.two={x:a.one.x+n,y:a.one.y+r},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(a.one={x:t.left,y:t.top},a.two={x:t.right,y:t.bottom},a):(a.one=t,e==null?a.two={x:a.one.x+n,y:a.one.y+r}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+n}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},zr=t=>{const e=vs(t);return{lower:e.one.x,upper:e.two.x}},Tr=t=>{const e=vs(t);return{lower:e.one.y,upper:e.two.y}},mf=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,gf=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([Ya,gf,Gt,Fa]);const wf=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:Ci,scale:Ci});i.z.object({offset:i.z.number(),scale:i.z.number()});const bf=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],vf=t=>(e,n,r,s)=>[e,s?r/t:r*t],zf=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:a}=e,{lower:o,upper:c}=t,u=a-s,l=c-o;if(n==="dimension")return[t,r*(l/u)];const h=(r-s)*(l/u)+o;return[t,h]},Tf=t=>(e,n,r)=>[t,r],Of=()=>(t,e,n)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,n];const{lower:r,upper:s}=t;return[t,s-(n-r)]},Sf=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=wf(r,s,a),[e,r]};class Ve{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Ve().translate(e)}static magnify(e){return new Ve().magnify(e)}static scale(e,n){return new Ve().scale(e,n)}translate(e){const n=this.new(),r=bf(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=vf(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=ot(e,n),s=this.new(),a=zf(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=ot(e,n),s=this.new(),a=Sf(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=ot(e,n),s=this.new(),a=Tf(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Of();e.type="invert";const n=this.new();return n.ops.push(e),n}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Ve;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],a)=>a(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&n.push([s,a])}),n.forEach(([r,s])=>{const a=e.ops.slice(r,s);a.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Ve}class Se{x;y;currRoot;constructor(e=new Ve,n=new Ve,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new Se().translate(e,n)}static translateX(e){return new Se().translateX(e)}static translateY(e){return new Se().translateY(e)}static clamp(e){return new Se().clamp(e)}static magnify(e){return new Se().magnify(e)}static scale(e){return new Se().scale(e)}static reBound(e){return new Se().reBound(e)}translate(e,n){const r=yf(e,n),s=this.copy();return s.x=this.x.translate(r.x),s.y=this.y.translate(r.y),s}translateX(e){const n=this.copy();return n.x=this.x.translate(e),n}translateY(e){const n=this.copy();return n.y=this.y.translate(e),n}magnify(e){const n=this.copy();return n.x=this.x.magnify(e.x),n.y=this.y.magnify(e.y),n}scale(e){const n=this.copy();if(mf(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!pf(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(zr(e)),n.y=n.y.scale(Tr(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(zr(e)),n.y=this.y.reBound(Tr(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(zr(e)),n.y=this.y.clamp(Tr(e)),n}copy(){const e=new Se;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return vs(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new Se}const Ef=Gt.extend({root:Xa,units:i.object({x:i.enum(["px","decimal"]),y:i.enum(["px","decimal"])})});Ef.partial({root:!0,units:!0});const Nf=i.z.enum(["static","dynamic"]),Mi=365,Sn=30,$f=i.z.union([i.z.tuple([i.z.int()]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12)]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12),i.z.int().min(1).max(31)])]),Qa=(t,e)=>{const n=new v(e);if(![z.DAY,z.HOUR,z.MINUTE,z.SECOND,z.MILLISECOND,z.MICROSECOND,z.NANOSECOND].some(s=>s.equals(n)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=t.valueOf()%n.valueOf();return t instanceof v?new v(r):new z(r)};class v extends It{constructor(e,n="UTC"){if(e==null)super(v.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*v.MILLISECOND.valueOf());else if(typeof e=="string")super(v.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(v.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=v.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===tf?e=qr:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=v.MAX:e=v.MIN)),de(e)&&(e=e.value),super(BigInt(e.valueOf())+r)}}static parseDate([e=1970,n=1,r=1]){const s=new Date(e,n-1,r,0,0,0,0);return new v(BigInt(s.getTime())*v.MILLISECOND.valueOf()).truncate(v.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let u=v.hours(parseInt(r??"00")).add(v.minutes(parseInt(s??"00"))).add(v.seconds(parseInt(o??"00"))).add(v.milliseconds(parseInt(c??"00")));return n==="local"&&(u=u.add(v.utcOffset)),u.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return v.parseTimeString(e,n);if(e.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let s=e,a=0;if(e.includes(".")){const l=e.split(".");s=l[0];const h=l[1]||"0";a=parseInt(h.padEnd(3,"0").slice(0,3))}const o=n==="local"?new Date(s.replace("T"," ")):new Date(`${s}Z`),c=BigInt(o.getTime())*v.MILLISECOND.valueOf(),u=BigInt(a)*v.MILLISECOND.valueOf();return c+u}const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new v(BigInt(r.getTime())*v.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){if(e==="UTC")return this.date().toISOString();const n=this.date(),r=new z(BigInt(n.getTimezoneOffset())*v.MINUTE.valueOf());return this.sub(r).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new z(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 re(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}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(at(this.valueOf(),new z(e).valueOf()))}sub(e){return new v(an(this.valueOf(),new z(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(v.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}get localYear(){return this.date().getFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new v(n)}setLocalYear(e){const n=this.date();return n.setFullYear(e),new v(n)}get month(){return this.date().getUTCMonth()}get localMonth(){return this.date().getMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new v(n)}setLocalMonth(e){const n=this.date();return n.setMonth(e),new v(n)}get day(){return this.date().getUTCDate()}get localDay(){return this.date().getDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new v(n)}setLocalDay(e){const n=this.date();return n.setDate(e),new v(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new v(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new v(n)}get minute(){return this.date().getUTCMinutes()}get localMinute(){return this.date().getMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new v(n)}setLocalMinute(e){const n=this.date();return n.setMinutes(e),new v(n)}get second(){return this.date().getUTCSeconds()}get localSecond(){return this.date().getSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new v(n)}setLocalSecond(e){const n=this.date();return n.setSeconds(e),new v(n)}get millisecond(){return this.date().getUTCMilliseconds()}get localMillisecond(){return this.date().getMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new v(n)}setLocalMillisecond(e){const n=this.date();return n.setMilliseconds(e),new v(n)}toString(e="ISO",n="UTC"){switch(e){case"ISODate":return this.toISOString(n).slice(0,10);case"ISOTime":return this.toISOString(n).slice(11,23);case"time":return this.timeString(!1,n);case"preciseTime":return this.timeString(!0,n);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,n)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,n)}`;default:return this.toISOString(n)}}remainder(e){return Qa(this,e)}get isToday(){return this.truncate(z.DAY).equals(v.now().truncate(z.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(z.days(30))?"shortDate":e.greaterThanOrEqual(z.DAY)?"dateTime":e.greaterThanOrEqual(z.HOUR)?"time":e.greaterThanOrEqual(z.SECOND)?"preciseTime":"ISOTime"}static now(){return new v(new Date)}static max(...e){let n=v.MIN;for(const r of e){const s=new v(r);s.after(n)&&(n=s)}return n}static min(...e){let n=v.MAX;for(const r of e){const s=new v(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new v(e,n)}static NANOSECOND=v.nanoseconds(1);static microseconds(e,n="UTC"){return v.nanoseconds(e*1e3,n)}static MICROSECOND=v.microseconds(1);static milliseconds(e,n="UTC"){return v.microseconds(e*1e3,n)}static MILLISECOND=v.milliseconds(1);static seconds(e,n="UTC"){return v.milliseconds(e*1e3,n)}static SECOND=v.seconds(1);static minutes(e,n="UTC"){return v.seconds(e*60,n)}static MINUTE=v.minutes(1);static hours(e,n="UTC"){return v.minutes(e*60,n)}static HOUR=v.hours(1);static days(e,n="UTC"){return v.hours(e*24,n)}static DAY=v.days(1);static MAX=new v(qr);static MIN=new v(0);static ZERO=new v(0);static z=i.z.union([i.z.instanceof(v),i.z.object({value:i.z.bigint()}).transform(e=>new v(e.value)),i.z.string().transform(e=>new v(BigInt(e))),i.z.number().transform(e=>new v(e)),i.z.bigint().transform(e=>new v(e)),i.z.date().transform(e=>new v(e)),i.z.custom(e=>e instanceof z).transform(e=>new v(e)),$f.transform(e=>new v(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}}class z extends It{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),de(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof z?e:e instanceof Or?e.period:e instanceof v?new z(e):(de(e)&&(e=e.value),["number","bigint"].includes(typeof e)?z.seconds(e):new z(e))}static fromMilliseconds(e){return e instanceof z?e:e instanceof Or?e.period:e instanceof v?new z(e):(de(e)&&(e=e.value),["number","bigint"].includes(typeof e)?z.milliseconds(e):new z(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new z(e).valueOf()}greaterThan(e){return this.valueOf()>new z(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new z(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new z(e).valueOf()}remainder(e){return Qa(this,e)}truncate(e){return new z(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(z.DAY),r=this.truncate(z.HOUR),s=this.truncate(z.MINUTE),a=this.truncate(z.SECOND),o=this.truncate(z.MILLISECOND),c=this.truncate(z.MICROSECOND),u=this.truncate(z.NANOSECOND),l=n,h=r.sub(n),d=s.sub(r),f=a.sub(s),b=o.sub(a),N=c.sub(o),k=u.sub(c);let O="";return l.isZero||(O+=`${l.days}d `),h.isZero||(O+=`${h.hours}h `),d.isZero||(O+=`${d.minutes}m `),f.isZero||(O+=`${f.seconds}s `),b.isZero||(O+=`${b.milliseconds}ms `),N.isZero||(O+=`${N.microseconds}µs `),k.isZero||(O+=`${k.nanoseconds}ns`),O.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new z(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(z.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,u=Math.floor(s/Mi),l=Math.floor(s/Sn),h=Math.floor(s/7),d=Math.floor(s),f=Math.floor(a),b=Math.floor(o),N=Math.floor(c),k=r?"-":"";if(u>=1){let O=`${u}y`;if(u<2){const S=Math.floor(s%Mi/Sn);S>0&&(O+=` ${S}mo`)}return k+O}if(h>=1&&s<Sn&&s%7===0){let O=`${h}w`;const S=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(S>0?O+=` ${S}d`:A>0&&A<24&&(O+=` ${A}h`)),k+O}if(l>=1){let O=`${l}mo`;if(l<3){const S=Math.floor(s%Sn);S>0&&(O+=` ${S}d`)}return k+O}if(h>=1){let O=`${h}w`;const S=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(S>0?O+=` ${S}d`:A>0&&A<24&&(O+=` ${A}h`)),k+O}if(d>=1){let O=`${d}d`;const S=Math.floor(a-d*24);return d<2&&S>0&&(O+=` ${S}h`),k+O}if(f>=1){let O=`${f}h`;if(f<3){const S=Math.floor(o-f*60);S>0&&(O+=` ${S}m`)}return k+O}if(b>=1){let O=`${b}m`;if(b<5){const S=Math.floor(c-b*60);S>0&&(O+=` ${S}s`)}return k+O}return`${k}${N}s`}mult(e){return new z(Ne(this.valueOf(),e))}div(e){return new z(Gn(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(z.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(z.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new z(e).valueOf()}add(e){return new z(this.valueOf()+new z(e).valueOf())}sub(e){return new z(this.valueOf()-new z(e).valueOf())}static nanoseconds(e=1){return new z(e)}static NANOSECOND=z.nanoseconds(1);static microseconds(e=1){return z.nanoseconds(Ne(e,1e3))}static MICROSECOND=z.microseconds(1);static milliseconds(e=1){return z.microseconds(Ne(e,1e3))}static MILLISECOND=z.milliseconds(1);static seconds(e=1){return z.milliseconds(Ne(e,1e3))}static SECOND=z.seconds(1);static minutes(e=1){return z.seconds(Ne(e,60))}static MINUTE=z.minutes(1);static hours(e){return z.minutes(Ne(e,60))}static HOUR=z.hours(1);static days(e){return z.hours(Ne(e,24))}static DAY=z.days(1);static MAX=new z(qr);static MIN=new z(0);static ZERO=new z(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new z(e.value)),i.z.string().transform(e=>new z(BigInt(e))),i.z.number().transform(e=>new z(e)),i.z.bigint().transform(e=>new z(e)),i.z.instanceof(z),i.z.instanceof(v).transform(e=>new z(e)),i.z.custom(e=>e instanceof Or).transform(e=>new z(e))])}let Or=class fe extends It{constructor(e){de(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new fe(e).valueOf()}get period(){return z.seconds(1/this.valueOf())}sampleCount(e){return new z(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new R(n).valueOf()}span(e){return z.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new R(n).valueOf())}add(e){return new fe(at(this.valueOf(),new fe(e).valueOf()))}sub(e){return new fe(an(this.valueOf(),new fe(e).valueOf()))}mult(e){return new fe(Ne(this.valueOf(),e))}div(e){return new fe(Gn(this.valueOf(),e))}static hz(e){return new fe(e)}static khz(e){return fe.hz(e*1e3)}static z=i.z.union([i.z.number().transform(e=>new fe(e)),i.z.instanceof(fe)])};class R extends It{constructor(e){de(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new Z(e*this.valueOf())}add(e){return new R(at(this.valueOf(),new R(e).valueOf()))}sub(e){return new R(an(this.valueOf(),new R(e).valueOf()))}mult(e){return new R(Ne(this.valueOf(),e))}div(e){return new R(Gn(this.valueOf(),e))}static UNKNOWN=new R(0);static BIT128=new R(16);static BIT64=new R(8);static BIT32=new R(4);static BIT16=new R(2);static BIT8=new R(1);static z=i.z.union([i.z.number().transform(e=>new R(e)),i.z.instanceof(R)])}class re{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new v(e.start),this.end=new v(e.end)):(this.start=new v(e),this.end=new v(n))}get span(){return new z(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new re(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=z.ZERO){if(n.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return r<0&&(r=-r),s<0&&(s=-s),r<=n.valueOf()&&s<=n.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,n=z.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const s=v.max(r.start,e.start),a=v.min(r.end,e.end);return a.before(s)?!1:new z(a.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof re?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new re(this.start,this.end);return e.start.after(this.start)&&(n.start=e.start),e.start.after(this.end)&&(n.end=e.start),e.end.before(this.end)&&(n.end=e.end),e.end.before(this.start)&&(n.start=e.end),n}static max(...e){return new re(v.min(...e.map(n=>n.start)),v.max(...e.map(n=>n.end)))}static MAX=new re(v.MIN,v.MAX);static ZERO=new re(v.ZERO,v.ZERO);static z=i.z.union([i.z.object({start:v.z,end:v.z}).transform(e=>new re(e.start,e.end)),i.z.instanceof(re)]);static sort(e,n){return v.sort(e.start,n.start)||v.sort(e.end,n.end)}static merge(...e){return re.max(...e.map(n=>new re(n).makeValid()))}}class y extends It{constructor(e){if(de(e)&&(e=e.value),e instanceof y||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=y.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(n==null)throw new Error(`unable to find data type for ${e.toString()}`);super(n.valueOf())}}get Array(){const e=y.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(n=>this.equals(n))}toString(e=!1){return e?y.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(y.JSON)||this.equals(y.STRING)||this.equals(y.BYTES)}get isNumeric(){return!this.isVariable&&!this.equals(y.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=y.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(y.UINT8)||this.equals(y.UINT16)||this.equals(y.UINT32)||this.equals(y.UINT64)}get isSignedInteger(){return this.equals(y.INT8)||this.equals(y.INT16)||this.equals(y.INT32)||this.equals(y.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(y.INT32)&&e.equals(y.FLOAT64)||this.equals(y.INT8)&&e.equals(y.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return y.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new y("unknown");static FLOAT64=new y("float64");static FLOAT32=new y("float32");static INT64=new y("int64");static INT32=new y("int32");static INT16=new y("int16");static INT8=new y("int8");static UINT64=new y("uint64");static UINT32=new y("uint32");static UINT16=new y("uint16");static UINT8=new y("uint8");static TIMESTAMP=new y("timestamp");static UUID=new y("uuid");static STRING=new y("string");static JSON=new y("json");static BYTES=new y("bytes");static ARRAY_CONSTRUCTORS=new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array],[y.BYTES.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]]);static DENSITIES=new Map([[y.UINT8.toString(),R.BIT8],[y.UINT16.toString(),R.BIT16],[y.UINT32.toString(),R.BIT32],[y.UINT64.toString(),R.BIT64],[y.FLOAT32.toString(),R.BIT32],[y.FLOAT64.toString(),R.BIT64],[y.INT8.toString(),R.BIT8],[y.INT16.toString(),R.BIT16],[y.INT32.toString(),R.BIT32],[y.INT64.toString(),R.BIT64],[y.TIMESTAMP.toString(),R.BIT64],[y.STRING.toString(),R.UNKNOWN],[y.JSON.toString(),R.UNKNOWN],[y.UUID.toString(),R.BIT128],[y.BYTES.toString(),R.UNKNOWN]]);static ALL=[y.UNKNOWN,y.UINT8,y.UINT16,y.UINT32,y.UINT64,y.INT8,y.INT16,y.INT32,y.INT64,y.FLOAT32,y.FLOAT64,y.TIMESTAMP,y.UUID,y.STRING,y.JSON,y.BYTES];static SHORT_STRINGS=new Map([[y.UINT8.toString(),"u8"],[y.UINT16.toString(),"u16"],[y.UINT32.toString(),"u32"],[y.UINT64.toString(),"u64"],[y.INT8.toString(),"i8"],[y.INT16.toString(),"i16"],[y.INT32.toString(),"i32"],[y.INT64.toString(),"i64"],[y.FLOAT32.toString(),"f32"],[y.FLOAT64.toString(),"f64"],[y.TIMESTAMP.toString(),"ts"],[y.UUID.toString(),"uuid"],[y.STRING.toString(),"str"],[y.JSON.toString(),"json"],[y.BYTES.toString(),"bytes"]]);static BIG_INT_TYPES=[y.INT64,y.UINT64,y.TIMESTAMP];static z=i.z.union([i.z.string().transform(e=>new y(e)),i.z.instanceof(y)])}class Z extends It{constructor(e){de(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return de(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return de(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return de(e)&&(e=e.value),new Z(at(this.valueOf(),e.valueOf()))}sub(e){return de(e)&&(e=e.value),new Z(an(this.valueOf(),e.valueOf()))}mult(e){return new Z(Ne(this.valueOf(),e))}div(e){return new Z(Gn(this.valueOf(),e))}truncate(e){return new Z(Math.trunc(this.valueOf()/new Z(e).valueOf())*new Z(e).valueOf())}remainder(e){return Z.bytes(this.valueOf()%new Z(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),n=this.truncate(Z.GIGABYTE),r=this.truncate(Z.MEGABYTE),s=this.truncate(Z.KILOBYTE),a=this.truncate(Z.BYTE),o=e,c=n.sub(e),u=r.sub(n),l=s.sub(r),h=a.sub(s);let d="";return o.isZero||(d+=`${o.terabytes}TB `),c.isZero||(d+=`${c.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),l.isZero||(d+=`${l.kilobytes}KB `),(!h.isZero||d==="")&&(d+=`${h.valueOf()}B`),d.trim()}static bytes(e=1){return new Z(e)}static BYTE=new Z(1);static kilobytes(e=1){return Z.bytes(new Z(e).valueOf()*1e3)}static KILOBYTE=Z.kilobytes(1);static megabytes(e=1){return Z.kilobytes(new Z(e).valueOf()*1e3)}static MEGABYTE=Z.megabytes(1);static gigabytes(e=1){return Z.megabytes(new Z(e).valueOf()*1e3)}static GIGABYTE=Z.gigabytes(1);static terabytes(e){return Z.gigabytes(new Z(e).valueOf()*1e3)}static TERABYTE=Z.terabytes(1);static ZERO=new Z(0);static z=i.z.union([i.z.number().transform(e=>new Z(e)),i.z.instanceof(Z)]);get isZero(){return this.valueOf()===0}}i.z.object({start:i.z.number(),end:i.z.number()});i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const eo=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof v||t instanceof z||t instanceof Date},kf=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):an(n,r),Af=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function If(t){return typeof t=="string"&&Af.test(t)}const Q=[];for(let t=0;t<256;++t)Q.push((t+256).toString(16).slice(1));function Zf(t,e=0){return(Q[t[e+0]]+Q[t[e+1]]+Q[t[e+2]]+Q[t[e+3]]+"-"+Q[t[e+4]]+Q[t[e+5]]+"-"+Q[t[e+6]]+Q[t[e+7]]+"-"+Q[t[e+8]]+Q[t[e+9]]+"-"+Q[t[e+10]]+Q[t[e+11]]+Q[t[e+12]]+Q[t[e+13]]+Q[t[e+14]]+Q[t[e+15]]).toLowerCase()}function xf(t,e=0){const n=Zf(t,e);if(!If(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const to=(t,e)=>xf(t,e),Be=-1,Cf=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),_f=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Fr=10,Mf=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},no="sy_x_telem_series";let ro=class He{key;discriminator=no;dataType;sampleOffset;gl;_data;timeRange=re.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Be;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=i.z.object({timeRange:re.z.optional(),dataType:y.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Cf,_f,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:Nf.default("static").optional()});static z=He.crudeZ.transform(e=>new He(e));constructor(e){Rf(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:u=Xh(),data:l}=e;if(jf(l)){const f=l;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=eo(l),d=Array.isArray(l);if(n!=null)this.dataType=new y(n);else{if(l instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(d||h){let f=l;if(!h){if(l.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=l[0]}if(typeof f=="string")this.dataType=y.STRING;else if(typeof f=="number")this.dataType=y.FLOAT64;else if(typeof f=="bigint")this.dataType=y.INT64;else if(typeof f=="boolean")this.dataType=y.UINT8;else if(f instanceof v||f instanceof Date||f instanceof v)this.dataType=y.TIMESTAMP;else if(typeof f=="object")this.dataType=y.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new y(l)}if(!d&&!h)this._data=l;else if(d&&l.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[l]:l;const b=f[0];(b instanceof v||b instanceof Date||b instanceof z)&&(f=f.map(N=>new v(N).valueOf())),this.dataType.equals(y.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
2
2
  `)}
3
- `).buffer):this.dataType.equals(p.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(S=>kr.encodeString(S)).join(`
3
+ `).buffer):this.dataType.equals(y.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(N=>Br.encodeString(N)).join(`
4
4
  `)}
5
- `).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(f.map(S=>BigInt(Math.round(S)))).buffer:!this.dataType.usesBigInt&&typeof O=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=l,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??Mt.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:n,...r}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const s=new new p(n).Array(e),a=new Be({data:s.buffer,dataType:n,...r});return a.writePos=0,a}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===Ue)return 0;const n=this.byteCapacity.valueOf()-this.writePos,r=e.subBytes(0,n);return this.writeToUnderlyingData(r),this.writePos+=r.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=r.length,this.calculateCachedLength()),r.length}writeFixed(e){if(this.writePos===Ue)return 0;const n=this.capacity-this.writePos,r=e.sub(0,n);return this.writeToUnderlyingData(r),this.cachedLength=void 0,this.maybeRecomputeMinMax(r),this.writePos+=r.length,r.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Ue?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
6
- `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(p.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(kr.decodeString(n)))}get byteCapacity(){return new I(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ue?this.byteCapacity:this.dataType.isVariable?new I(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ue?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const n=[0];return this.data.forEach((r,s)=>{r===$r&&(e++,n.push(s+1))}),this._cachedIndexes=n,this.cachedLength=e,e}convert(e,n=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let s=0;s<this.length;s++)r[s]=Jh(this.dataType,e,this.data[s],n);return new Be({data:r.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(p.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}else{const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),nt(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(p.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}else{const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),nt(this.cachedMin,this.sampleOffset))}get bounds(){return rt(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const n=e.cachedMin??e.calcRawMin();n<this.cachedMin&&(this.cachedMin=n)}if(this.cachedMax!=null){const n=e.cachedMax??e.calcRawMax();n>this.cachedMax&&(this.cachedMax=n)}}atAlignment(e,n){const r=Number((e-this.alignment)/this.alignmentMultiple);if(r<0||r>=this.length){if(n===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,n)}at(e,n=!1){if(this.dataType.isVariable)return this.atVariable(e,n??!1);if(this.dataType.equals(p.UUID))return this.atUUID(e,n);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(n===!0)throw new Error(`[series] - no value at index ${e}`);return}return nt(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=Ua(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(r==null){if(n)throw new Error(`[series] - no value at index ${e}`);return}return r}atVariable(e,n){let r=0,s=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===$r){if(e===0){s=o;break}r=o+1,e--}if(s===0&&(s=this.data.length),r>=s||e>0){if(n)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(r,s);return this.dataType.equals(p.STRING)?new TextDecoder().decode(a):Ea(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=mh(e);for(;n<=r;){const a=Math.floor((n+r)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?n=a+1:r=a-1}return n}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(p.FLOAT32)&&!this.dataType.equals(p.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:n,bufferUsage:r,prevBuffer:s}=this.gl;if(n==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Ue){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Ue}as(e){return sf(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Ei(this.alignmentBounds.lower),upper:Ei(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return rt(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new cf(this);return this.dataType.equals(p.JSON)?new cs(e):e}return this.dataType.equals(p.UUID)?new uf(this):new lf(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new Oi(this,e,n??this.length)}subAlignmentIterator(e,n){const r=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),s=Math.ceil(Number(n-this.alignment)/Number(this.alignmentMultiple));return new Oi(this,r,s)}subBytes(e,n){if(e>=0&&(n==null||n>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,n);return new Be({data:r,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,n,r){if(n<=0&&(r==null||r>=this.length))return this;let s;return e?s=this.data.subarray(n,r):s=this.data.slice(n,r),new Be({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new Be({data:this.buffer,dataType:this.dataType,timeRange:Mt.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(n=>n.toString());else{for(let n=0;n<5;n++)e+=`${this.at(n)?.toString()}`,e+=",";e+="...,";for(let n=-5;n<0;n++)e+=this.at(n)?.toString(),n<-1&&(e+=",")}return e+="])",e}};const af=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof La?!0:Ma(t),of=Oh(Da,La);let Oi=class{series;end;index;constructor(e,n,r){this.series=e;const s=rt(0,e.length+1);this.end=bi(s,r),this.index=bi(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}};class cf{series;index;decoder;constructor(e){if(!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,n=this.series.data;for(;this.index<n.length&&n[this.index]!==$r;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}}class cs{wrapped;static schema=i.z.record(i.z.string(),i.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:kr.decodeString(e.value,cs.schema)}}}let uf=class{series;index;data;density;constructor(e){if(!e.dataType.equals(p.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=p.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Ua(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}};class lf{series;index;constructor(e){this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}const Ei=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},hf=async t=>await new Promise(e=>setTimeout(e,v.fromMilliseconds(t).milliseconds));let ff=class{config;retries;interval;constructor(e){this.config={baseInterval:new v(e?.baseInterval??v.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??hf},this.retries=0,this.interval=new v(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:n,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(n),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}};const df=i.z.object({baseInterval:v.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),yf=Object.freeze(Object.defineProperty({__proto__:null,Breaker:ff,breakerConfigZ:df},Symbol.toStringTag,{value:"Module"})),pf=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Pa=i.z.string().regex(pf),zt=i.z.number().min(0).max(255),Ba=i.z.number().min(0).max(1),qa=i.z.tuple([zt,zt,zt,Ba]),mf=i.z.tuple([zt,zt,zt]),gf=i.z.object({rgba255:qa}),wf=i.z.number().min(0).max(360),bf=i.z.number().min(0).max(100),vf=i.z.number().min(0).max(100),zf=i.z.tuple([wf,bf,vf,Ba]),us=i.z.union([Pa,mf,qa,zf,gf]),Tf=us.transform(t=>ls(t)),ls=(t,e=1)=>{if(t=us.parse(t),typeof t=="string")return Of(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return t.rgba255},Of=(t,e=1)=>(t=Pa.parse(t),t=Ef(t),[gn(t,0),gn(t,2),gn(t,4),t.length===8?gn(t,6)/255:e]),gn=(t,e)=>parseInt(t.slice(e,e+2),16),Ef=t=>t.startsWith("#")?t.slice(1):t;ls("#000000");ls("#ffffff");const Nf=i.z.object({key:i.z.string(),color:us,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(Nf);const Sf=i.z.object({key:i.z.string(),name:i.z.string(),color:Tf});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(Sf)});i.z.int().min(0).max(255);i.z.object({name:i.z.string(),key:i.z.string()});const kf=t=>Object.getOwnPropertySymbols(globalThis).includes(t),Af=(t,e)=>{const n=Symbol.for(t);if(!kf(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},Fa="sy_x_error",$f=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),en=t=>class Ut extends Error{static discriminator=Fa;discriminator=Ut.discriminator;static TYPE=t;type=Ut.TYPE;static matches=$f(t);matches=Ut.matches;constructor(n,r){super(n,r),this.name=Ut.TYPE}static sub(n){return en(`${t}.${n}`)}},Ya=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Fa)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},wt="unknown",Ir="nil";class If{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Ir,data:""};if(Ya(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:wt,data:e.message};if(typeof e=="string")return{type:wt,data:e};try{return{type:wt,data:JSON.stringify(e)}}catch{return{type:wt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Ir)return null;if(e.type===wt)return new Zr(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new Zr(e.data)}}const hs=Af("synnax-error-registry",()=>new If),Zf=({encode:t,decode:e})=>hs().register({encode:t,decode:e}),xf=t=>hs().encode(t),Cf=t=>t==null?null:hs().decode(t);let Zr=class extends en("unknown"){};const _f=i.z.object({type:i.z.string(),data:i.z.string()});let Rf=class extends en("canceled"){},jf=class extends en("not_implemented"){};const Ye=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Rf,NONE:Ir,NotImplemented:jf,UNKNOWN:wt,Unknown:Zr,createTyped:en,decode:Cf,encode:xf,isTyped:Ya,payloadZ:_f,register:Zf},Symbol.toStringTag,{value:"Module"})),Mf=i.object({jsonrpc:i.literal("2.0"),method:i.string(),params:i.any().optional(),id:i.union([i.string(),i.number(),i.null()]).optional()}),Ga=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()])}),Uf=Ga.extend({result:i.json()}),Df=Ga.extend({error:i.object({code:i.number().int(),message:i.string().optional(),data:i.json().optional()})}),Lf=i.union([Uf,Df]);i.union([Mf,Lf]);i.z.object({key:i.z.string(),value:i.z.string()});const Pf=i.uuid();i.object({key:Pf,name:i.string().min(1),color:i.string()});i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/);const Bf=["standard","scientific","engineering"];i.z.enum(Bf);const qf=i.z.union([i.z.string(),i.z.number()]);i.z.record(qf,i.z.unknown());const Ff=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Ff();const Yf=["macOS","Windows","Linux"],Gf=["macos","windows","linux"],Hf={macos:"macOS",windows:"Windows",linux:"Linux"};i.z.enum(Yf).or(i.z.enum(Gf).transform(t=>Hf[t]));i.z.enum(["success","info","warning","error","loading","disabled"]);i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)});const Vf=(...t)=>t.map(Ha).join(""),Ha=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Wf=t=>t.endsWith("/")?t.slice(0,-1):t,Kf=(t,e="")=>t===null?"":`?${Object.entries(t).filter(([,n])=>n==null?!1:Array.isArray(n)?n.length>0:!0).map(([n,r])=>`${e}${n}=${r}`).join("&")}`;let Jf=class Nn{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=Ha(s)}replace(e){return new Nn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Nn({...this,pathPrefix:Vf(this.path,e)})}toString(){return Wf(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new Nn({host:"unknown",port:0})};i.z.int().min(0).max(Eh);class tn extends Ye.createTyped("freighter"){}let we=class extends tn.sub("eof"){constructor(){super("EOF")}},Nt=class extends tn.sub("stream_closed"){constructor(){super("StreamClosed")}},Ge=class extends tn.sub("unreachable"){url;constructor(e={}){const{message:n="Unreachable",url:r=Jf.UNKNOWN}=e;super(n),this.url=r}};const Xf=t=>{if(!t.type.startsWith(tn.TYPE))return null;if(we.matches(t))return{type:we.TYPE,data:"EOF"};if(Nt.matches(t))return{type:Nt.TYPE,data:"StreamClosed"};if(Ge.matches(t))return{type:Ge.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},Qf=t=>{if(!t.type.startsWith(tn.TYPE))return null;switch(t.type){case we.TYPE:return new we;case Nt.TYPE:return new Nt;case Ge.TYPE:return new Ge;default:throw new Ye.Unknown(`Unknown error type: ${t.data}`)}};Ye.register({encode:Xf,decode:Qf});let Va=class{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,n){let r=0;const s=async a=>{if(r===this.middleware.length)return await n(a);const o=this.middleware[r];return r++,await o(a,s)};return await s(e)}};const Wa="Content-Type",ed=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),td=t=>{const e=t?.cause?.code??t?.code??t?.errno;if(typeof e=="string"&&ed.has(e))return!0;if(t.name==="TypeError"){const n=String(t.message||"").toLowerCase();if(/load failed|failed to fetch|networkerror|network error/.test(n))return!0}return t?.name==="AbortError"||t?.code,!1},nd=400;let rd=class extends Va{endpoint;encoder;constructor(e,n,r=!1){return super(),this.endpoint=e.replace({protocol:r?"https":"http"}),this.encoder=n,new Proxy(this,{get:(s,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(s,a,o)})}get headers(){return{[Wa]:this.encoder.contentType}}async send(e,n,r,s){n=r?.parse(n);let a=null;const o=this.endpoint.child(e),c={};c.method="POST",c.body=this.encoder.encode(n??{});const[,l]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async u=>{const h={...u,params:{}};c.headers={...this.headers,...u.params};let d;try{d=await fetch(u.target,c)}catch(O){if(!(O instanceof Error))throw O;return[h,td(O)?new Ge({url:o}):O]}const f=await d.arrayBuffer();if(d?.ok)return s!=null&&(a=this.encoder.decode(f,s)),[h,null];try{if(d.status!==nd)return[h,new Error(d.statusText)];const O=this.encoder.decode(f,Ye.payloadZ),S=Ye.decode(O);return[h,S]}catch(O){return[h,new Error(`[freighter] - failed to decode error: ${d.statusText}: ${O.message}`)]}});if(l!=null)return[null,l];if(a==null)throw new Error("Response must be defined");return[a,null]}};const sd=(t,e)=>{class n{wrapped;constructor(s){this.wrapped=s}use(...s){this.wrapped.use(...s)}async send(s,a,o,c){const l=new yf.Breaker(e);do{const[u,h]=await this.wrapped.send(s,a,o,c);if(h==null)return[u,null];if(!Ge.matches(h))return[null,h];if(console.warn(`[freighter] ${l.retryMessage}`,h),!await l.wait())return[u,h]}while(!0)}}return new n(t)},z=async(t,e,n,r,s)=>{const[a,o]=await t.send(e,n,r,s);if(o!=null)throw o;return a},id=i.z.object({type:i.z.enum(["data","close","open"]),payload:i.z.unknown(),error:i.z.optional(Ye.payloadZ)});let ad=class{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,n,r,s){this.codec=n,this.reqSchema=r,this.resSchema=s,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return Ye.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new we;if(this.sendClosed)throw new Nt;return this.ws.send(this.codec.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");if(this.serverClosed=Ye.decode(e.error),this.serverClosed==null)throw new Error("Message error must be defined");return[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.codec.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((n,r)=>this.receiveCallbacksQueue.push({resolve:n,reject:r}))}addMessage(e){const n=this.receiveCallbacksQueue.shift();n!=null?n.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=this.onMessage.bind(this),this.ws.onclose=this.onClose.bind(this)}onMessage(e){this.addMessage(this.codec.decode(e.data,id))}onClose(e){this.addMessage({type:"close",error:{type:e.code===cd?we.TYPE:Nt.TYPE,data:""}})}};const od="freighterctx",cd=1e3;let ud=class xr extends Va{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,n,r=!1){super(),this.secure=r,this.baseUrl=e.replace({protocol:r?"wss":"ws"}),this.encoder=n}withCodec(e){const n=new xr(this.baseUrl,e,this.secure);return n.use(...this.middleware),n}async stream(e,n,r){let s;const[,a]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async o=>{const c=new WebSocket(this.buildURL(e,o)),l={...o,params:{}};c.binaryType=xr.MESSAGE_TYPE;const u=await this.wrapSocket(c,n,r);return u instanceof Error?[l,u]:(s=u,[l,null])});if(a!=null)throw a;return s}buildURL(e,n){const r=Kf({[Wa]:this.encoder.contentType,...n.params},od);return this.baseUrl.child(e).toString()+r}async wrapSocket(e,n,r){return await new Promise(s=>{e.onopen=()=>{const a=new ad(e,this.encoder,n,r);a.receiveOpenAck().then(o=>{o!=null?s(o):s(a)}).catch(o=>s(o))},e.onerror=a=>{const o=a;s(new Error(o.message))}})}};const Ka=t=>i.union([i.union([i.null(),i.undefined()]).transform(()=>[]),t.array()]),ld=t=>Array.isArray(t)?t:t==null?[]:[t],Ja=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>Ja(s,a),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s==e),r=[...t];return n===-1?r.push(e):r[n]=e,r},hd=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n)):t.filter(n=>n!=e)}),Xa=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>Xa(s,a),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s.key===e.key),r=[...t];return n===-1?r.push(e):r[n]=e,r},fd=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n.key)):t.filter(n=>n.key!==e)}),N=Object.freeze(Object.defineProperty({__proto__:null,nullableZ:Ka,remove:hd,removeKeyed:fd,toArray:ld,upsert:Ja,upsertKeyed:Xa},Symbol.toStringTag,{value:"Module"})),dd=t=>{const e=t.replace(/_[a-z]/g,n=>n[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Un=t=>{const e=(n,r=Cr)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!lr(n))return n;r=md(r);const s={},a=n;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),r):(Object.keys(a).forEach(o=>{let c=a[o];const l=t(o);r.recursive&&(lr(c)?Si(c)||(c=e(c,r)):r.recursiveInArray&&Ni(c)&&(c=[...c].map(u=>{let h=u;return lr(u)?Si(h)||(h=e(u,r)):Ni(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},fs=Un(dd),yd=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),Qa=Un(yd),eo=t=>t.length===0?t:t[0].toUpperCase()+t.slice(1),pd=[Number,String,Uint8Array],Cr={recursive:!0,recursiveInArray:!0},md=(t=Cr)=>(t.recursive==null?t=Cr:t.recursiveInArray??=!1,t),Ni=t=>t!=null&&Array.isArray(t),lr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Si=t=>pd.some(e=>t instanceof e),gd=t=>t.replace(/[\s_]+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}-${r.toLowerCase()}`).toLowerCase(),wd=Un(gd),bd=t=>{if(t.length===0)return t;let e=t.replace(/[_-]/g," ");return e=e.replace(/([a-z0-9])([A-Z])/g,(n,r,s)=>`${r} ${s}`),e=e.replace(/([A-Z]+)([A-Z][a-z])/g,(n,r,s)=>`${r} ${s}`),e=e.replace(/\s+/g," ").trim(),e=e.replace(/\b\w/g,n=>n.toUpperCase()),e},vd=Un(bd),zd=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:Qa,capitalize:eo,snakeToCamel:fs,toKebab:wd,toProperNoun:vd},Symbol.toStringTag,{value:"Module"})),Td=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);class to{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e))}decode(e,n){return this.decodeString(this.decoder.decode(e),n)}decodeString(e,n){const r=JSON.parse(e),s=fs(r);return n!=null?n.parse(s):s}encodeString(e){const n=Qa(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}}class no{contentType="text/csv";encode(e){const n=this.encodeString(e);return new TextEncoder().encode(n)}decode(e,n){const r=new TextDecoder().decode(e);return this.decodeString(r,n)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Td(e[0]))throw new Error("Payload must be an array of objects");const n=Object.keys(e[0]),r=[n.join(",")];return e.forEach(s=>{const a=n.map(o=>JSON.stringify(s[o]??""));r.push(a.join(","))}),r.join(`
5
+ `).buffer):this.dataType.usesBigInt&&typeof b=="number"?this._data=new this.dataType.Array(f.map(N=>BigInt(Math.round(N)))).buffer:!this.dataType.usesBigInt&&typeof b=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=u,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??re.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:n,...r}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const s=new new y(n).Array(e),a=new He({data:s.buffer,dataType:n,...r});return a.writePos=0,a}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===Be)return 0;const n=this.byteCapacity.valueOf()-this.writePos,r=e.subBytes(0,n);return this.writeToUnderlyingData(r),this.writePos+=r.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=r.length,this.calculateCachedLength()),r.length}writeFixed(e){if(this.writePos===Be)return 0;const n=this.capacity-this.writePos,r=e.sub(0,n);return this.writeToUnderlyingData(r),this.cachedLength=void 0,this.maybeRecomputeMinMax(r),this.writePos+=r.length,r.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Be?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
6
+ `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(y.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(Br.decodeString(n)))}get byteCapacity(){return new Z(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Be?this.byteCapacity:this.dataType.isVariable?new Z(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Be?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const n=[0];return this.data.forEach((r,s)=>{r===Fr&&(e++,n.push(s+1))}),this._cachedIndexes=n,this.cachedLength=e,e}convert(e,n=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let s=0;s<this.length;s++)r[s]=kf(this.dataType,e,this.data[s],n);return new He({data:r.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(y.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}else{const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),at(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(y.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}else{const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),at(this.cachedMin,this.sampleOffset))}get bounds(){return ot(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const n=e.cachedMin??e.calcRawMin();n<this.cachedMin&&(this.cachedMin=n)}if(this.cachedMax!=null){const n=e.cachedMax??e.calcRawMax();n>this.cachedMax&&(this.cachedMax=n)}}atAlignment(e,n){const r=Number((e-this.alignment)/this.alignmentMultiple);if(r<0||r>=this.length){if(n===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,n)}at(e,n=!1){if(this.dataType.isVariable)return this.atVariable(e,n??!1);if(this.dataType.equals(y.UUID))return this.atUUID(e,n);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(n===!0)throw new Error(`[series] - no value at index ${e}`);return}return at(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=to(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(r==null){if(n)throw new Error(`[series] - no value at index ${e}`);return}return r}atVariable(e,n){let r=0,s=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===Fr){if(e===0){s=o;break}r=o+1,e--}if(s===0&&(s=this.data.length),r>=s||e>0){if(n)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(r,s);return this.dataType.equals(y.STRING)?new TextDecoder().decode(a):Da(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=Hh(e);for(;n<=r;){const a=Math.floor((n+r)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?n=a+1:r=a-1}return n}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(y.FLOAT32)&&!this.dataType.equals(y.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:n,bufferUsage:r,prevBuffer:s}=this.gl;if(n==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Be){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Be}as(e){return Mf(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:ji(this.alignmentBounds.lower),upper:ji(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return ot(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Uf(this);return this.dataType.equals(y.JSON)?new Pf(e):e}return this.dataType.equals(y.UUID)?new Lf(this):new Df(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new Ri(this,e,n??this.length)}subAlignmentIterator(e,n){const r=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),s=Math.ceil(Number(n-this.alignment)/Number(this.alignmentMultiple));return new Ri(this,r,s)}subBytes(e,n){if(e>=0&&(n==null||n>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,n);return new He({data:r,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,n,r){if(n<=0&&(r==null||r>=this.length))return this;let s;return e?s=this.data.subarray(n,r):s=this.data.slice(n,r),new He({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new He({data:this.buffer,dataType:this.dataType,timeRange:re.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(n=>n.toString());else{for(let n=0;n<5;n++)e+=`${this.at(n)?.toString()}`,e+=",";e+="...,";for(let n=-5;n<0;n++)e+=this.at(n)?.toString(),n<-1&&(e+=",")}return e+="])",e}};const Rf=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof ro?!0:eo(t),jf=Qh(no,ro);let Ri=class{series;end;index;constructor(e,n,r){this.series=e;const s=ot(0,e.length+1);this.end=xi(s,r),this.index=xi(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},Uf=class{series;index;decoder;constructor(e){if(!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,n=this.series.data;for(;this.index<n.length&&n[this.index]!==Fr;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}},Pf=class so{wrapped;static schema=i.z.record(i.z.string(),i.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Br.decodeString(e.value,so.schema)}}};class Lf{series;index;data;density;constructor(e){if(!e.dataType.equals(y.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=y.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=to(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}class Df{series;index;constructor(e){this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}const ji=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},Bf=async t=>await new Promise(e=>setTimeout(e,z.fromMilliseconds(t).milliseconds));let qf=class{config;retries;interval;constructor(e){this.config={baseInterval:new z(e?.baseInterval??z.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Bf},this.retries=0,this.interval=new z(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:n,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(n),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}};const Ff=i.z.object({baseInterval:z.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),Yf=Object.freeze(Object.defineProperty({__proto__:null,Breaker:qf,breakerConfigZ:Ff},Symbol.toStringTag,{value:"Module"})),Hf=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,io=i.z.string().regex(Hf),Me=i.z.number().min(0).max(255),zs=i.z.number().min(0).max(1),ao=i.z.tuple([Me,Me,Me,zs]),Vf=i.z.tuple([Me,Me,Me]),Gf=i.z.object({rgba255:ao}),Wf=i.z.object({r:Me,g:Me,b:Me,a:zs}),Jf=i.z.number().min(0).max(360),Kf=i.z.number().min(0).max(100),Xf=i.z.number().min(0).max(100),Qf=i.z.tuple([Jf,Kf,Xf,zs]),Ts=i.z.union([io,Vf,ao,Qf,Gf,Wf]),oo=Ts.transform(t=>Os(t)),Os=(t,e=1)=>{if(t=Ts.parse(t),typeof t=="string")return ed(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return"a"in t&&"r"in t?[t.r,t.g,t.b,t.a]:t.rgba255},ed=(t,e=1)=>(t=io.parse(t),t=td(t),[En(t,0),En(t,2),En(t,4),t.length===8?En(t,6)/255:e]),En=(t,e)=>parseInt(t.slice(e,e+2),16),td=t=>t.startsWith("#")?t.slice(1):t;Os("#000000");Os("#ffffff");const nd=i.z.object({key:i.z.string(),color:Ts,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(nd);const rd=i.z.object({key:i.z.string(),name:i.z.string(),color:oo});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(rd)});i.z.int().min(0).max(255);i.z.object({name:i.z.string(),key:i.z.string()});const sd=t=>Object.getOwnPropertySymbols(globalThis).includes(t),id=(t,e)=>{const n=Symbol.for(t);if(!sd(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},co="sy_x_error",ad=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),on=t=>class Ut extends Error{static discriminator=co;discriminator=Ut.discriminator;static TYPE=t;type=Ut.TYPE;static matches=ad(t);matches=Ut.matches;constructor(n,r){super(n,r),this.name=Ut.TYPE}static sub(n){return on(`${t}.${n}`)}},uo=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==co)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},zt="unknown",Yr="nil";let od=class{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Yr,data:""};if(uo(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:zt,data:e.message};if(typeof e=="string")return{type:zt,data:e};try{return{type:zt,data:JSON.stringify(e)}}catch{return{type:zt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Yr)return null;if(e.type===zt)return new Hr(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new Hr(e.data)}};const Ss=id("synnax-error-registry",()=>new od),cd=({encode:t,decode:e})=>Ss().register({encode:t,decode:e}),ud=t=>Ss().encode(t),ld=t=>t==null?null:Ss().decode(t);let Hr=class extends on("unknown"){};const hd=i.z.object({type:i.z.string(),data:i.z.string()});class fd extends on("canceled"){}let dd=class extends on("not_implemented"){};const We=Object.freeze(Object.defineProperty({__proto__:null,Canceled:fd,NONE:Yr,NotImplemented:dd,UNKNOWN:zt,Unknown:Hr,createTyped:on,decode:ld,encode:ud,isTyped:uo,payloadZ:hd,register:cd},Symbol.toStringTag,{value:"Module"}));i.z.string().regex(/^(?:$|(?:\/(?:[^~/]|~0|~1)*)+)$/,"must be a valid JSON pointer (RFC 6901)");i.z.union([i.z.string(),i.z.number(),i.z.boolean(),i.z.null()]);i.z.enum(["string","number","boolean","null"]);i.z.object({key:i.z.string(),value:i.z.string()});const pd=i.uuid();i.object({key:pd,name:i.string().min(1),color:oo});i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/);const yd=["standard","scientific","engineering"];i.z.enum(yd);const md=i.z.union([i.z.string(),i.z.number()]);i.z.record(md,i.z.unknown());const gd=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";gd();const wd=["macOS","Windows","Linux"],bd=["macos","windows","linux"],vd={macos:"macOS",windows:"Windows",linux:"Linux"};i.z.enum(wd).or(i.z.enum(bd).transform(t=>vd[t]));i.z.enum(["success","info","warning","error","loading","disabled"]);i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)});const zd=(...t)=>t.map(lo).join(""),lo=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Td=t=>t.endsWith("/")?t.slice(0,-1):t,Od=(t,e="")=>t===null?"":`?${Object.entries(t).filter(([,n])=>n==null?!1:Array.isArray(n)?n.length>0:!0).map(([n,r])=>`${e}${n}=${r}`).join("&")}`;let Sd=class Cn{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=lo(s)}replace(e){return new Cn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Cn({...this,pathPrefix:zd(this.path,e)})}toString(){return Td(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new Cn({host:"unknown",port:0})};i.z.int().min(0).max(ef);let cn=class extends We.createTyped("freighter"){},ze=class extends cn.sub("eof"){constructor(){super("EOF")}},Nt=class extends cn.sub("stream_closed"){constructor(){super("StreamClosed")}},Je=class extends cn.sub("unreachable"){url;constructor(e={}){const{message:n="Unreachable",url:r=Sd.UNKNOWN}=e;super(n),this.url=r}};const Ed=t=>{if(!t.type.startsWith(cn.TYPE))return null;if(ze.matches(t))return{type:ze.TYPE,data:"EOF"};if(Nt.matches(t))return{type:Nt.TYPE,data:"StreamClosed"};if(Je.matches(t))return{type:Je.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},Nd=t=>{if(!t.type.startsWith(cn.TYPE))return null;switch(t.type){case ze.TYPE:return new ze;case Nt.TYPE:return new Nt;case Je.TYPE:return new Je;default:throw new We.Unknown(`Unknown error type: ${t.data}`)}};We.register({encode:Ed,decode:Nd});let ho=class{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,n){let r=0;const s=async a=>{if(r===this.middleware.length)return await n(a);const o=this.middleware[r];return r++,await o(a,s)};return await s(e)}};const fo="Content-Type",$d=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),kd=t=>{const e=t?.cause?.code??t?.code??t?.errno;if(typeof e=="string"&&$d.has(e))return!0;if(t.name==="TypeError"){const n=String(t.message||"").toLowerCase();if(/load failed|failed to fetch|networkerror|network error/.test(n))return!0}return t?.name==="AbortError"||t?.code,!1},Ad=400;let Id=class extends ho{endpoint;encoder;constructor(e,n,r=!1){return super(),this.endpoint=e.replace({protocol:r?"https":"http"}),this.encoder=n,new Proxy(this,{get:(s,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(s,a,o)})}get headers(){return{[fo]:this.encoder.contentType}}async send(e,n,r,s){n=r?.parse(n);let a=null;const o=this.endpoint.child(e),c={};c.method="POST",c.body=this.encoder.encode(n??{});const[,u]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async l=>{const h={...l,params:{}};c.headers={...this.headers,...l.params};let d;try{d=await fetch(l.target,c)}catch(b){if(!(b instanceof Error))throw b;return[h,kd(b)?new Je({url:o}):b]}const f=await d.arrayBuffer();if(d?.ok)return s!=null&&(a=this.encoder.decode(f,s)),[h,null];try{if(d.status!==Ad)return[h,new Error(d.statusText)];const b=this.encoder.decode(f,We.payloadZ),N=We.decode(b);return[h,N]}catch(b){return[h,new Error(`[freighter] - failed to decode error: ${d.statusText}: ${b.message}`)]}});if(u!=null)return[null,u];if(a==null)throw new Error("Response must be defined");return[a,null]}};const Zd=(t,e)=>{class n{wrapped;constructor(s){this.wrapped=s}use(...s){this.wrapped.use(...s)}async send(s,a,o,c){const u=new Yf.Breaker(e);do{const[l,h]=await this.wrapped.send(s,a,o,c);if(h==null)return[l,null];if(!Je.matches(h))return[null,h];if(console.warn(`[freighter] ${u.retryMessage}`,h),!await u.wait())return[l,h]}while(!0)}}return new n(t)},T=async(t,e,n,r,s)=>{const[a,o]=await t.send(e,n,r,s);if(o!=null)throw o;return a},xd=i.z.object({type:i.z.enum(["data","close","open"]),payload:i.z.unknown(),error:i.z.optional(We.payloadZ)});let Cd=class{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,n,r,s){this.codec=n,this.reqSchema=r,this.resSchema=s,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return We.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new ze;if(this.sendClosed)throw new Nt;return this.ws.send(this.codec.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");if(this.serverClosed=We.decode(e.error),this.serverClosed==null)throw new Error("Message error must be defined");return[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.codec.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((n,r)=>this.receiveCallbacksQueue.push({resolve:n,reject:r}))}addMessage(e){const n=this.receiveCallbacksQueue.shift();n!=null?n.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=this.onMessage.bind(this),this.ws.onclose=this.onClose.bind(this)}onMessage(e){this.addMessage(this.codec.decode(e.data,xd))}onClose(e){this.addMessage({type:"close",error:{type:e.code===Md?ze.TYPE:Nt.TYPE,data:""}})}};const _d="freighterctx",Md=1e3;let Rd=class Vr extends ho{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,n,r=!1){super(),this.secure=r,this.baseUrl=e.replace({protocol:r?"wss":"ws"}),this.encoder=n}withCodec(e){const n=new Vr(this.baseUrl,e,this.secure);return n.use(...this.middleware),n}async stream(e,n,r){let s;const[,a]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async o=>{const c=new WebSocket(this.buildURL(e,o)),u={...o,params:{}};c.binaryType=Vr.MESSAGE_TYPE;const l=await this.wrapSocket(c,n,r);return l instanceof Error?[u,l]:(s=l,[u,null])});if(a!=null)throw a;return s}buildURL(e,n){const r=Od({[fo]:this.encoder.contentType,...n.params},_d);return this.baseUrl.child(e).toString()+r}async wrapSocket(e,n,r){return await new Promise(s=>{e.onopen=()=>{const a=new Cd(e,this.encoder,n,r);a.receiveOpenAck().then(o=>{o!=null?s(o):s(a)}).catch(o=>s(o))},e.onerror=a=>{const o=a;s(new Error(o.message))}})}};const po=t=>i.union([i.union([i.null(),i.undefined()]).transform(()=>[]),t.array()]),jd=t=>Array.isArray(t)?t:t==null?[]:[t],yo=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>yo(s,a),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s==e),r=[...t];return n===-1?r.push(e):r[n]=e,r},Ud=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n)):t.filter(n=>n!=e)}),mo=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>mo(s,a),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s.key===e.key),r=[...t];return n===-1?r.push(e):r[n]=e,r},Pd=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n.key)):t.filter(n=>n.key!==e)}),E=Object.freeze(Object.defineProperty({__proto__:null,nullableZ:po,remove:Ud,removeKeyed:Pd,toArray:jd,upsert:yo,upsertKeyed:mo},Symbol.toStringTag,{value:"Module"})),Ld=t=>{const e=t.replace(/_[a-z]/g,n=>n[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Wn=t=>{const e=(n,r=Gr)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!Sr(n))return n;r=qd(r);const s={},a=n;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),r):(Object.keys(a).forEach(o=>{let c=a[o];const u=t(o);r.recursive&&(Sr(c)?Pi(c)||(c=e(c,r)):r.recursiveInArray&&Ui(c)&&(c=[...c].map(l=>{let h=l;return Sr(l)?Pi(h)||(h=e(l,r)):Ui(l)&&(h=e({key:l},r).key),h}))),s[u]=c}),s)};return e},Es=Wn(Ld),Dd=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),go=Wn(Dd),wo=t=>t.length===0?t:t[0].toUpperCase()+t.slice(1),Bd=[Number,String,Uint8Array],Gr={recursive:!0,recursiveInArray:!0},qd=(t=Gr)=>(t.recursive==null?t=Gr:t.recursiveInArray??=!1,t),Ui=t=>t!=null&&Array.isArray(t),Sr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Pi=t=>Bd.some(e=>t instanceof e),Fd=t=>t.replace(/[\s_]+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}-${r.toLowerCase()}`).toLowerCase(),Yd=Wn(Fd),Hd=t=>{if(t.length===0)return t;let e=t.replace(/[_-]/g," ");return e=e.replace(/([a-z0-9])([A-Z])/g,(n,r,s)=>`${r} ${s}`),e=e.replace(/([A-Z]+)([A-Z][a-z])/g,(n,r,s)=>`${r} ${s}`),e=e.replace(/\s+/g," ").trim(),e=e.replace(/\b\w/g,n=>n.toUpperCase()),e},Vd=Wn(Hd),Gd=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:go,capitalize:wo,snakeToCamel:Es,toKebab:Yd,toProperNoun:Vd},Symbol.toStringTag,{value:"Module"})),bo=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);class vo{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e))}decode(e,n){return this.decodeString(this.decoder.decode(e),n)}decodeString(e,n){const r=JSON.parse(e),s=Es(r);return n!=null?n.parse(s):s}encodeString(e){const n=go(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}}class zo{contentType="text/csv";encode(e){const n=this.encodeString(e);return new TextEncoder().encode(n)}decode(e,n){const r=new TextDecoder().decode(e);return this.decodeString(r,n)}encodeString(e){if(!Array.isArray(e)||e.length===0||!bo(e[0]))throw new Error("Payload must be an array of objects");const n=Object.keys(e[0]),r=[n.join(",")];return e.forEach(s=>{const a=n.map(o=>JSON.stringify(s[o]??""));r.push(a.join(","))}),r.join(`
7
7
  `)}decodeString(e,n){const[r,...s]=e.trim().split(`
8
- `).map(c=>c.trim());if(r.length===0)return n!=null?n.parse({}):{};const a=r.split(",").map(c=>c.trim()),o={};return a.forEach(c=>{o[c]=[]}),s.forEach(c=>{const l=c.split(",").map(u=>u.trim());a.forEach((u,h)=>{const d=this.parseValue(l[h]);d!=null&&o[u].push(d)})}),n!=null?n.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const n=Number(e);return isNaN(n)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:n}}class ro{contentType="text/plain";encode(e){if(typeof e!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(e)}decode(e,n){const r=new TextDecoder().decode(e);return n!=null?n.parse(r):r}}const Ft=new to,Od=new no,Ed=new ro,Nd=[Ft],ut=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:no,CSV_CODEC:Od,ENCODERS:Nd,JSONCodec:to,JSON_CODEC:Ft,TEXT_CODEC:Ed,TextCodec:ro},Symbol.toStringTag,{value:"Module"})),ie=t=>t!=null&&typeof t=="object"&&"value"in t;class lt{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const ds=t=>t!=null&&typeof t=="object"&&"toString"in t,so=t=>{if(ds(t))return t?.toString().length===0;switch(typeof t){case"string":return t.length===0;case"number":return t===0;case"bigint":return t===0n;case"boolean":return!t;case"undefined":return!0;case"object":return t==null;default:return!1}},Sd=t=>!so(t),kd=Object.freeze(Object.defineProperty({__proto__:null,ValueExtension:lt,isCrudeValueExtension:ie,isNonZero:Sd,isStringer:ds,isZero:so},Symbol.toStringTag,{value:"Module"})),_r=t=>[...new Set(t)],Ad=(t,e,n=!0)=>{const r=new Map;return t.forEach(s=>{const a=e(s);if(r.has(a)){if(n)return;r.delete(a)}r.set(a,s)}),Array.from(r.values())},ki=Object.freeze(Object.defineProperty({__proto__:null,by:Ad,unique:_r},Symbol.toStringTag,{value:"Module"})),nn=(t,e=!1)=>{const n=ds(t)?"stringer":typeof t;let r;switch(n){case"string":r=(s,a)=>s.localeCompare(a);break;case"stringer":r=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":r=(s,a)=>Number(s)-Number(a);break;case"bigint":r=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":r=(s,a)=>Number(s)-Number(a);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return e?ao(r):r},$d=(t,e,n)=>{const r=nn(e[t],n);return(s,a)=>r(s[t],a[t])},Id=(t,e)=>t.length!==e.length?t.length-e.length:t.every((n,r)=>n===e[r])?0:-1,io=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const n=nn(t[0]),r=[...t].sort(n),s=[...e].sort(n);return r.every((a,o)=>a===s[o])?0:-1},Zd=(t,e)=>{const n=_r(t),r=_r(e);return io(n,r)},xd=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,ao=t=>(e,n)=>t(n,e),ht=0,Ze=-1,xe=1,oo=t=>t<ht,co=t=>t>ht,Cd=t=>t>=ht,uo=t=>t===ht,_d=(t,e)=>{const n=/([a-zA-Z]+)|(\d+)/g,r=t.replace(/[\s_.-]+/g,"").match(n),s=e.replace(/[\s_.-]+/g,"").match(n);if(!r||!s)return 0;for(let a=0;a<Math.min(r.length,s.length);a++){const o=r[a],c=s[a];if(isNaN(Number(o))&&isNaN(Number(c))){const l=o.localeCompare(c);if(l!==0)return l}else if(!isNaN(Number(o))&&!isNaN(Number(c))){const l=Number(o)-Number(c);if(l!==0)return l}else return isNaN(Number(o))?-1:1}return r.length-s.length},lo=(t,e,n)=>{let r=0,s=t.length;const a=n??nn(e);for(;r<s;){const o=Math.floor((r+s)/2),c=a(t[o],e);if(c===0)return o;c<0?r=o+1:s=o}return r},Rd=(t,e,n)=>{const r=lo(t,e,n);t.splice(r,0,e)},Ai=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:ht,GREATER_THAN:xe,LESS_THAN:Ze,insert:Rd,isEqualTo:uo,isGreaterThan:co,isGreaterThanEqual:Cd,isLessThan:oo,newF:nn,newFieldF:$d,order:xd,primitiveArrays:Id,reverseF:ao,search:lo,stringsWithNumbers:_d,uniqueUnorderedPrimitiveArrays:Zd,unorderedPrimitiveArrays:io},Symbol.toStringTag,{value:"Module"}));let ho=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const fo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",jd=`0123456789${fo}`,yo=11,Md=ho(fo,1),Ud=ho(jd,yo-1),ys=()=>`${Md()}${Ud()}`,po=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:yo,create:ys},Symbol.toStringTag,{value:"Module"})),Dd=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,Ld=2**8-1,mo=2**12-1,Pd=2**16-1,Bd=2**32-1,qd=2n**64n-1n,Fd=2**64-1,Yd=-128,Gd=2**7-1,Hd=-32768,Vd=2**15-1,Wd=-2147483648,Kd=2**31-1,Jd=-(2n**63n),kn=2n**63n-1n,Xd=-9223372036854776e3,go=2**63-1,It=t=>(e,n)=>{if(typeof e=="bigint"){if(An(n))return t(e,BigInt(n));const r=t(Number(e),Number(n));return typeof r=="number"?BigInt(Math.round(r)):r}return t(Number(e),Number(n))},Ce=It((t,e)=>t-e),_e=It((t,e)=>t+e),Qd=(t,e,n=1e-4)=>Math.abs(t-e)<n,Rr=(t,e)=>{const n=typeof t=="bigint",r=typeof e=="bigint";return n&&r?t===e:n&&An(e)?t===BigInt(e):r&&An(t)?e===BigInt(t):t===e},ey=t=>{const e=10**Math.floor(Math.log10(t));return Math.round(t/e)*e},wo=It((t,e)=>t<=e?t:e),An=t=>typeof t=="bigint"?!0:Number.isInteger(t),ty=It((t,e)=>t>=e?t:e),bo=t=>typeof t=="bigint"?t<0n?-t:t:t<0?-t:t,me=It((t,e)=>t*e),rn=It((t,e)=>t/e),vo=i.z.tuple([i.z.number(),i.z.number()]),zo=i.z.object({width:i.z.number(),height:i.z.number()}),ny=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),ry=["start","center","end"],St=i.z.object({x:i.z.number(),y:i.z.number()}),To=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),ps=["x","y"],Oo=i.z.enum(ps),ms=["top","right","bottom","left"],sy=i.z.enum(ms),Eo=["left","right"],gs=i.z.enum(Eo),ws=["top","bottom"],bs=i.z.enum(ws),vs=["center"],jr=i.z.enum(vs),iy=[...ms,...vs],zs=i.z.enum(iy);i.z.enum(ry);const ay=["first","last"];i.z.enum(ay);i.z.object({lower:i.z.number(),upper:i.z.number()});i.z.enum([...Oo.options,...zs.options]);const oy=i.z.union([Oo,zs,i.z.instanceof(String)]),W=(t,e,n)=>{const r={};if(typeof e=="object"&&(n=e,e=void 0),n={makeValid:!0,...n},typeof t=="number"||typeof t=="bigint")e!=null?(r.lower=t,r.upper=e):(r.lower=typeof t=="bigint"?0n:0,r.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[r.lower,r.upper]=t}else r.lower=t.lower,r.upper=t.upper;return n?.makeValid?cy(r):r},cy=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,$i=(t,e)=>{const n=W(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e},wn=(t,e)=>{const n=W(t);if(typeof e=="number"||typeof e=="bigint")return e>=n.lower&&e<n.upper;const r=W(e);return r.lower>=n.lower&&r.upper<=n.upper},No=t=>{const e=W(t);return e.upper-e.lower},uy=t=>({lower:Math.min(...t.map(e=>W(e).lower)),upper:Math.max(...t.map(e=>W(e).upper))}),ly=(t,e,n)=>{const r=t.map(c=>W(c)),s=n>0?1:n<0?-1:0;if(s===0)return e;let a=n,o=e;for(;Rr(a,0)===!1;){const c=r.findIndex(l=>s>0?o>=l.lower&&o<l.upper:o>l.lower&&o<=l.upper);if(c!==-1){const l=r[c];let u;if(s>0?u=Ce(l.upper,o):u=Ce(o,l.lower),u>0){const h=wo(bo(a),u);if(o=_e(o,s>0?h:-h),a=Ce(a,s>0?h:-h),Rr(a,0))return o;continue}}if(s>0){const l=r.filter(u=>u.lower>o);if(l.length>0)o=l[0].lower;else return o}else{const l=r.filter(u=>u.upper<o);if(l.length>0)o=l[l.length-1].upper;else return o}}return o},hy=(t,e,n)=>{const r=t.map(o=>W(o));if(e===n)return typeof e=="bigint"?0n:0;const s=e<n?W([e,n]):W([n,e]);let a=typeof e=="bigint"?0n:0;for(const o of r){const c=o.lower>s.lower?o.lower:s.lower,l=o.upper<s.upper?o.upper:s.upper;if(c<l){const u=l-c;a=a+u}}return a},Mr=2,Ur=3,So=2,fy=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=No(e);if(n==0)return t;let r;n>=1e3?r=Mr:n>=1?r=Ur:r=Math.ceil(-Math.log10(n))+So;const s=10**r;return Math.round(t*s)/s},dy=5,yy=1e-10,py=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=Math.abs(t);if(n===0)return 0;let r=!1,s=0;if(e!=null){s=No(e);const c=s/n;r=s>0&&c>yy}if(r){let c;s>=1e3?c=Mr:s>=1?c=Ur:c=Math.ceil(-Math.log10(s))+So;const l=10**c;return Math.round(t*l)/l}if(n>=1e3){const c=10**Mr;return Math.round(t*c)/c}if(n>=1){const c=10**Ur;return Math.round(t*c)/c}const a=Math.floor(Math.log10(n)),o=10**(dy-a-1);return Math.round(t*o)/o},Dr=Object.freeze(Object.defineProperty({__proto__:null,MAX_INT16:Vd,MAX_INT32:Kd,MAX_INT64:kn,MAX_INT64_NUMBER:go,MAX_INT8:Gd,MAX_UINT12:mo,MAX_UINT16:Pd,MAX_UINT32:Bd,MAX_UINT64:qd,MAX_UINT64_NUMBER:Fd,MAX_UINT8:Ld,MIN_INT16:Hd,MIN_INT32:Wd,MIN_INT64:Jd,MIN_INT64_NUMBER:Xd,MIN_INT8:Yd,abs:bo,add:_e,closeTo:Qd,div:rn,equal:Rr,isInteger:An,max:ty,min:wo,mult:me,roundBySpan:fy,roundToNearestMagnitude:ey,smartRound:py,sub:Ce},Symbol.toStringTag,{value:"Module"})),my=t=>ps.includes(t)?t:ws.includes(t)?"y":"x",gy=gs,wy=bs,by=jr,vy={top:"bottom",right:"left",bottom:"top",left:"right",center:"center"},zy={top:{clockwise:"left",counterclockwise:"right"},right:{clockwise:"top",counterclockwise:"bottom"},bottom:{clockwise:"right",counterclockwise:"left"},left:{clockwise:"bottom",counterclockwise:"top"}},Ty=oy,it=t=>t instanceof String||!ps.includes(t)?t:t==="x"?"left":"top",Oy=t=>vy[it(t)],Ey=(t,e)=>zy[t][e],Yt=t=>{const e=it(t);return e==="top"||e==="bottom"?"y":"x"},Ny=i.z.object({x:gs.or(jr),y:bs.or(jr)}),Ts=i.z.object({x:gs,y:bs}),Os=Object.freeze({x:"left",y:"top"}),ko=Object.freeze({x:"right",y:"top"}),Ao=Object.freeze({x:"left",y:"bottom"}),$o=Object.freeze({x:"right",y:"bottom"}),Es=Object.freeze({x:"center",y:"center"}),Io=Object.freeze({x:"center",y:"top"}),Zo=Object.freeze({x:"center",y:"bottom"}),xo=Object.freeze({x:"right",y:"center"}),Co=Object.freeze({x:"left",y:"center"}),Sy=Object.freeze([Co,xo,Io,Zo,Os,ko,Ao,$o,Es]),_o=(t,e)=>t.x===e.x&&t.y===e.y,ky=(t,e)=>{if(typeof e=="object"){let n=!0;return"x"in e&&(t.x===e.x||(n=!1)),"y"in e&&(t.y===e.y||(n=!1)),n}return t.x===e||t.y===e},Ay=t=>[t.x,t.y],Sn=t=>Yt(it(t))==="x",$y=t=>Yt(it(t))==="y",Iy=t=>`${t.x}${eo(t.y)}`,Zy=(t,e)=>{let n,r;if(typeof t=="object"&&"x"in t?(n=t.x,r=t.y):(n=it(t),r=it(e??t)),Yt(n)===Yt(r)&&n!=="center"&&r!=="center")throw new Error(`[XYLocation] - encountered two locations with the same direction: ${n.toString()} - ${r.toString()}`);const s={...Es};return n==="center"?Sn(r)?[s.x,s.y]=[r,n]:[s.x,s.y]=[n,r]:r==="center"?Sn(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n]:Sn(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n],s},xy=Object.freeze(Object.defineProperty({__proto__:null,BOTTOM_CENTER:Zo,BOTTOM_LEFT:Ao,BOTTOM_RIGHT:$o,CENTER:Es,CENTER_LEFT:Co,CENTER_LOCATIONS:vs,CENTER_RIGHT:xo,OUTER_LOCATIONS:ms,TOP_CENTER:Io,TOP_LEFT:Os,TOP_RIGHT:ko,XY_LOCATIONS:Sy,X_LOCATIONS:Eo,Y_LOCATIONS:ws,center:by,construct:it,constructXY:Zy,corner:Ts,crude:Ty,direction:Yt,isX:Sn,isY:$y,location:zs,outer:sy,rotate:Ey,swap:Oy,x:gy,xy:Ny,xyCouple:Ay,xyEquals:_o,xyMatches:ky,xyToString:Iy,y:wy},Symbol.toStringTag,{value:"Module"})),Lr=i.z.union([i.z.number(),St,vo,zo,ny,To]),R=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},at=Object.freeze({x:0,y:0}),Cy=Object.freeze({x:1,y:1}),_y=Object.freeze({x:1/0,y:1/0}),Ry=Object.freeze({x:NaN,y:NaN}),Ro=(t,e,n=0)=>{const r=R(t),s=R(e);return n===0?r.x===s.x&&r.y===s.y:Math.abs(r.x-s.x)<=n&&Math.abs(r.y-s.y)<=n},jy=t=>Ro(t,at),Ns=(t,e,n)=>{const r=R(t),s=R(e,n);return{x:r.x*s.x,y:r.y*s.y}},jo=(t,e)=>{const n=R(t);return{x:n.x+e,y:n.y}},Mo=(t,e)=>{const n=R(t);return{x:n.x,y:n.y+e}},Uo=(t,e,n,...r)=>{if(typeof e=="string"){if(typeof n!="number")throw new Error("The value must be a number.");return e==="x"?jo(t,n):Mo(t,n)}if(typeof e=="object"&&"x"in e&&typeof e.x=="string"){const s=R(n),a=R(t);return e.x==="left"?s.x=-s.x:e.x==="center"&&(s.x=0),e.y==="top"?s.y=-s.y:e.y==="center"&&(s.y=0),{x:a.x+s.x,y:a.y+s.y}}return[t,e,n??at,...r].reduce((s,a)=>{const o=R(a);return{x:s.x+o.x,y:s.y+o.y}},at)},My=(t,e,n)=>{const r=R(t);return my(e)==="x"?{x:n,y:r.y}:{x:r.x,y:n}},Uy=(t,e)=>{const n=R(t),r=R(e);return Math.sqrt((n.x-r.x)**2+(n.y-r.y)**2)},Dy=(t,e)=>{const n=R(t),r=R(e);return{x:r.x-n.x,y:r.y-n.y}},Ly=t=>{const e=R(t);return Number.isNaN(e.x)||Number.isNaN(e.y)},Py=t=>{const e=R(t);return Number.isFinite(e.x)&&Number.isFinite(e.y)},By=t=>{const e=R(t);return[e.x,e.y]},qy=t=>{const e=R(t);return{left:e.x,top:e.y}},Fy=(t,e=0)=>{const n=R(t);return{x:Number(n.x.toFixed(e)),y:Number(n.y.toFixed(e))}},Dt=(t,e)=>{const n=R(t),r=R(e);return{x:n.x-r.x,y:n.y-r.y}},Lt=t=>{const e=R(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:-e.y/n,y:e.x/n}},Do=t=>{const e=R(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:e.x/n,y:e.y/n}},Lo=(...t)=>{const e=t.reduce((n,r)=>Uo(n,r),at);return Ns(e,1/t.length)},Yy=(t,e)=>{const n=[];for(let r=0;r<t.length;r++){const s=t[r];let a,o,c,l;if(r===0){const u=t[r+1],h=Dt(u,s);o=Lt(h),c=o,l=e}else if(r===t.length-1){const u=t[r-1],h=Dt(s,u);a=Lt(h),c=a,l=e}else{const u=t[r-1],h=t[r+1],d=Dt(s,u),f=Dt(h,s);a=Lt(d),o=Lt(f);const O=Math.acos((d.x*f.x+d.y*f.y)/(Math.hypot(d.x,d.y)*Math.hypot(f.x,f.y))),S=Math.sin(O/2);S===0?l=e:l=e/S,c=Do(Lo(a,o))}n.push(Ns(c,l))}return n},Gy=t=>{const e=R(t);return{x:e.y,y:e.x}},Hy=t=>{const e=R(t);return{x:Math.round(e.x),y:Math.round(e.y)}},Vy=t=>{const e=R(t);return{x:1/e.x,y:1/e.y}},Wy=(t,e,n)=>{const r=R(t),s=R(e),a=n==="clockwise"?Math.PI/2:-Math.PI/2,o=r.x-s.x,c=r.y-s.y,l=o*Math.cos(a)-c*Math.sin(a),u=o*Math.sin(a)+c*Math.cos(a);return{x:l+s.x,y:u+s.y}},Ss=Object.freeze(Object.defineProperty({__proto__:null,INFINITY:_y,NAN:Ry,ONE:Cy,ZERO:at,average:Lo,calculateMiters:Yy,clientXY:To,construct:R,couple:By,crudeZ:Lr,css:qy,distance:Uy,equals:Ro,isFinite:Py,isNan:Ly,isZero:jy,normal:Lt,normalize:Do,reciprocal:Vy,rotate:Wy,round:Hy,scale:Ns,set:My,sub:Dt,swap:Gy,translate:Uo,translateX:jo,translateY:Mo,translation:Dy,truncate:Fy,xy:St},Symbol.toStringTag,{value:"Module"})),bn=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:bn,left:bn,width:bn,height:bn});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:St,two:St,root:Ts});const ks=(t,e,n=0,r=0,s)=>{const a={one:{...at},two:{...at},root:s??Os};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:t,y:e},a.two={x:a.one.x+n,y:a.one.y+r},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(a.one={x:t.left,y:t.top},a.two={x:t.right,y:t.bottom},a):(a.one=t,e==null?a.two={x:a.one.x+n,y:a.one.y+r}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+n}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},hr=t=>{const e=ks(t);return{lower:e.one.x,upper:e.two.x}},fr=t=>{const e=ks(t);return{lower:e.one.y,upper:e.two.y}},Ky=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,Jy=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([zo,Jy,St,vo]);const Xy=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:Lr,scale:Lr});i.z.object({offset:i.z.number(),scale:i.z.number()});const Qy=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],ep=t=>(e,n,r,s)=>[e,s?r/t:r*t],tp=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:a}=e,{lower:o,upper:c}=t,l=a-s,u=c-o;if(n==="dimension")return[t,r*(u/l)];const h=(r-s)*(u/l)+o;return[t,h]},np=t=>(e,n,r)=>[t,r],rp=()=>(t,e,n)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,n];const{lower:r,upper:s}=t;return[t,s-(n-r)]},sp=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=Xy(r,s,a),[e,r]};class Fe{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Fe().translate(e)}static magnify(e){return new Fe().magnify(e)}static scale(e,n){return new Fe().scale(e,n)}translate(e){const n=this.new(),r=Qy(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=ep(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=W(e,n),s=this.new(),a=tp(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=W(e,n),s=this.new(),a=sp(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=W(e,n),s=this.new(),a=np(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=rp();e.type="invert";const n=this.new();return n.ops.push(e),n}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Fe;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],a)=>a(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&n.push([s,a])}),n.forEach(([r,s])=>{const a=e.ops.slice(r,s);a.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Fe}class Te{x;y;currRoot;constructor(e=new Fe,n=new Fe,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new Te().translate(e,n)}static translateX(e){return new Te().translateX(e)}static translateY(e){return new Te().translateY(e)}static clamp(e){return new Te().clamp(e)}static magnify(e){return new Te().magnify(e)}static scale(e){return new Te().scale(e)}static reBound(e){return new Te().reBound(e)}translate(e,n){const r=R(e,n),s=this.copy();return s.x=this.x.translate(r.x),s.y=this.y.translate(r.y),s}translateX(e){const n=this.copy();return n.x=this.x.translate(e),n}translateY(e){const n=this.copy();return n.y=this.y.translate(e),n}magnify(e){const n=this.copy();return n.x=this.x.magnify(e.x),n.y=this.y.magnify(e.y),n}scale(e){const n=this.copy();if(Ky(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!_o(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(hr(e)),n.y=n.y.scale(fr(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(hr(e)),n.y=this.y.reBound(fr(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(hr(e)),n.y=this.y.clamp(fr(e)),n}copy(){const e=new Te;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return ks(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new Te}const ip=St.extend({root:Ts,units:i.object({x:i.enum(["px","decimal"]),y:i.enum(["px","decimal"])})});ip.partial({root:!0,units:!0});const ap=i.z.enum(["static","dynamic"]),Ii=365,vn=30,op=i.z.union([i.z.tuple([i.z.int()]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12)]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12),i.z.int().min(1).max(31)])]),Po=(t,e)=>{const n=new w(e);if(![m.DAY,m.HOUR,m.MINUTE,m.SECOND,m.MILLISECOND,m.MICROSECOND,m.NANOSECOND].some(s=>s.equals(n)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=t.valueOf()%n.valueOf();return t instanceof w?new w(r):new m(r)};class w extends lt{constructor(e,n="UTC"){if(e==null)super(w.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*w.MILLISECOND.valueOf());else if(typeof e=="string")super(w.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(w.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=w.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===go?e=kn:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=w.MAX:e=w.MIN)),ie(e)&&(e=e.value),super(BigInt(e.valueOf())+r)}}static parseDate([e=1970,n=1,r=1]){const s=new Date(e,n-1,r,0,0,0,0);return new w(BigInt(s.getTime())*w.MILLISECOND.valueOf()).truncate(w.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let l=w.hours(parseInt(r??"00")).add(w.minutes(parseInt(s??"00"))).add(w.seconds(parseInt(o??"00"))).add(w.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(w.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return w.parseTimeString(e,n);if(e.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let s=e,a=0;if(e.includes(".")){const u=e.split(".");s=u[0];const h=u[1]||"0";a=parseInt(h.padEnd(3,"0").slice(0,3))}const o=n==="local"?new Date(s.replace("T"," ")):new Date(`${s}Z`),c=BigInt(o.getTime())*w.MILLISECOND.valueOf(),l=BigInt(a)*w.MILLISECOND.valueOf();return c+l}const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new w(BigInt(r.getTime())*w.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(w.utcOffset).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new m(BigInt(new Date().getTimezoneOffset())*w.MINUTE.valueOf())}static since(e){return new w().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new w(e).valueOf()}span(e){return this.range(e).span}range(e){return new x(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new w(e).valueOf()}afterEq(e){return this.valueOf()>=new w(e).valueOf()}before(e){return this.valueOf()<new w(e).valueOf()}beforeEq(e){return this.valueOf()<=new w(e).valueOf()}add(e){return new w(_e(this.valueOf(),new m(e).valueOf()))}sub(e){return new w(Ce(this.valueOf(),new m(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(m.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(m.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(m.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(m.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(w.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(w.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new w(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new w(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new w(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new w(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new w(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new w(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new w(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new w(n)}toString(e="ISO",n="UTC"){switch(e){case"ISODate":return this.toISOString(n).slice(0,10);case"ISOTime":return this.toISOString(n).slice(11,23);case"time":return this.timeString(!1,n);case"preciseTime":return this.timeString(!0,n);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,n)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,n)}`;default:return this.toISOString(n)}}remainder(e){return Po(this,e)}get isToday(){return this.truncate(m.DAY).equals(w.now().truncate(m.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(m.days(30))?"shortDate":e.greaterThanOrEqual(m.DAY)?"dateTime":e.greaterThanOrEqual(m.HOUR)?"time":e.greaterThanOrEqual(m.SECOND)?"preciseTime":"ISOTime"}static now(){return new w(new Date)}static max(...e){let n=w.MIN;for(const r of e){const s=new w(r);s.after(n)&&(n=s)}return n}static min(...e){let n=w.MAX;for(const r of e){const s=new w(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new w(e,n)}static NANOSECOND=w.nanoseconds(1);static microseconds(e,n="UTC"){return w.nanoseconds(e*1e3,n)}static MICROSECOND=w.microseconds(1);static milliseconds(e,n="UTC"){return w.microseconds(e*1e3,n)}static MILLISECOND=w.milliseconds(1);static seconds(e,n="UTC"){return w.milliseconds(e*1e3,n)}static SECOND=w.seconds(1);static minutes(e,n="UTC"){return w.seconds(e*60,n)}static MINUTE=w.minutes(1);static hours(e,n="UTC"){return w.minutes(e*60,n)}static HOUR=w.hours(1);static days(e,n="UTC"){return w.hours(e*24,n)}static DAY=w.days(1);static MAX=new w(kn);static MIN=new w(0);static ZERO=new w(0);static z=i.z.union([i.z.instanceof(w),i.z.object({value:i.z.bigint()}).transform(e=>new w(e.value)),i.z.string().transform(e=>new w(BigInt(e))),i.z.number().transform(e=>new w(e)),i.z.bigint().transform(e=>new w(e)),i.z.date().transform(e=>new w(e)),i.z.custom(e=>e instanceof m).transform(e=>new w(e)),op.transform(e=>new w(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}}class m extends lt{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),ie(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof m?e:e instanceof G?e.period:e instanceof w?new m(e):(ie(e)&&(e=e.value),["number","bigint"].includes(typeof e)?m.seconds(e):new m(e))}static fromMilliseconds(e){return e instanceof m?e:e instanceof G?e.period:e instanceof w?new m(e):(ie(e)&&(e=e.value),["number","bigint"].includes(typeof e)?m.milliseconds(e):new m(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new m(e).valueOf()}greaterThan(e){return this.valueOf()>new m(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new m(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new m(e).valueOf()}remainder(e){return Po(this,e)}truncate(e){return new m(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(m.DAY),r=this.truncate(m.HOUR),s=this.truncate(m.MINUTE),a=this.truncate(m.SECOND),o=this.truncate(m.MILLISECOND),c=this.truncate(m.MICROSECOND),l=this.truncate(m.NANOSECOND),u=n,h=r.sub(n),d=s.sub(r),f=a.sub(s),O=o.sub(a),S=c.sub(o),Z=l.sub(c);let T="";return u.isZero||(T+=`${u.days}d `),h.isZero||(T+=`${h.hours}h `),d.isZero||(T+=`${d.minutes}m `),f.isZero||(T+=`${f.seconds}s `),O.isZero||(T+=`${O.milliseconds}ms `),S.isZero||(T+=`${S.microseconds}µs `),Z.isZero||(T+=`${Z.nanoseconds}ns`),T.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new m(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(m.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/Ii),u=Math.floor(s/vn),h=Math.floor(s/7),d=Math.floor(s),f=Math.floor(a),O=Math.floor(o),S=Math.floor(c),Z=r?"-":"";if(l>=1){let T=`${l}y`;if(l<2){const E=Math.floor(s%Ii/vn);E>0&&(T+=` ${E}mo`)}return Z+T}if(h>=1&&s<vn&&s%7===0){let T=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?T+=` ${E}d`:A>0&&A<24&&(T+=` ${A}h`)),Z+T}if(u>=1){let T=`${u}mo`;if(u<3){const E=Math.floor(s%vn);E>0&&(T+=` ${E}d`)}return Z+T}if(h>=1){let T=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?T+=` ${E}d`:A>0&&A<24&&(T+=` ${A}h`)),Z+T}if(d>=1){let T=`${d}d`;const E=Math.floor(a-d*24);return d<2&&E>0&&(T+=` ${E}h`),Z+T}if(f>=1){let T=`${f}h`;if(f<3){const E=Math.floor(o-f*60);E>0&&(T+=` ${E}m`)}return Z+T}if(O>=1){let T=`${O}m`;if(O<5){const E=Math.floor(c-O*60);E>0&&(T+=` ${E}s`)}return Z+T}return`${Z}${S}s`}mult(e){return new m(me(this.valueOf(),e))}div(e){return new m(rn(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(m.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(m.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(m.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(m.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(m.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(m.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new m(e).valueOf()}add(e){return new m(this.valueOf()+new m(e).valueOf())}sub(e){return new m(this.valueOf()-new m(e).valueOf())}static nanoseconds(e=1){return new m(e)}static NANOSECOND=m.nanoseconds(1);static microseconds(e=1){return m.nanoseconds(me(e,1e3))}static MICROSECOND=m.microseconds(1);static milliseconds(e=1){return m.microseconds(me(e,1e3))}static MILLISECOND=m.milliseconds(1);static seconds(e=1){return m.milliseconds(me(e,1e3))}static SECOND=m.seconds(1);static minutes(e=1){return m.seconds(me(e,60))}static MINUTE=m.minutes(1);static hours(e){return m.minutes(me(e,60))}static HOUR=m.hours(1);static days(e){return m.hours(me(e,24))}static DAY=m.days(1);static MAX=new m(kn);static MIN=new m(0);static ZERO=new m(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new m(e.value)),i.z.string().transform(e=>new m(BigInt(e))),i.z.number().transform(e=>new m(e)),i.z.bigint().transform(e=>new m(e)),i.z.instanceof(m),i.z.instanceof(w).transform(e=>new m(e)),i.z.custom(e=>e instanceof G).transform(e=>new m(e))])}class G extends lt{constructor(e){ie(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new G(e).valueOf()}get period(){return m.seconds(1/this.valueOf())}sampleCount(e){return new m(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new C(n).valueOf()}span(e){return m.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new C(n).valueOf())}add(e){return new G(_e(this.valueOf(),new G(e).valueOf()))}sub(e){return new G(Ce(this.valueOf(),new G(e).valueOf()))}mult(e){return new G(me(this.valueOf(),e))}div(e){return new G(rn(this.valueOf(),e))}static hz(e){return new G(e)}static khz(e){return G.hz(e*1e3)}static z=i.z.union([i.z.number().transform(e=>new G(e)),i.z.instanceof(G)])}class C extends lt{constructor(e){ie(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new $(e*this.valueOf())}add(e){return new C(_e(this.valueOf(),new C(e).valueOf()))}sub(e){return new C(Ce(this.valueOf(),new C(e).valueOf()))}mult(e){return new C(me(this.valueOf(),e))}div(e){return new C(rn(this.valueOf(),e))}static UNKNOWN=new C(0);static BIT128=new C(16);static BIT64=new C(8);static BIT32=new C(4);static BIT16=new C(2);static BIT8=new C(1);static z=i.z.union([i.z.number().transform(e=>new C(e)),i.z.instanceof(C)])}class x{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new w(e.start),this.end=new w(e.end)):(this.start=new w(e),this.end=new w(n))}get span(){return new m(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new x(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=m.ZERO){if(n.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return r<0&&(r=-r),s<0&&(s=-s),r<=n.valueOf()&&s<=n.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,n=m.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const s=w.max(r.start,e.start),a=w.min(r.end,e.end);return a.before(s)?!1:new m(a.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof x?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new x(this.start,this.end);return e.start.after(this.start)&&(n.start=e.start),e.start.after(this.end)&&(n.end=e.start),e.end.before(this.end)&&(n.end=e.end),e.end.before(this.start)&&(n.start=e.end),n}static max(...e){return new x(w.min(...e.map(n=>n.start)),w.max(...e.map(n=>n.end)))}static MAX=new x(w.MIN,w.MAX);static ZERO=new x(w.ZERO,w.ZERO);static z=i.z.union([i.z.object({start:w.z,end:w.z}).transform(e=>new x(e.start,e.end)),i.z.instanceof(x)]);static sort(e,n){return w.sort(e.start,n.start)||w.sort(e.end,n.end)}static merge(...e){return x.max(...e.map(n=>new x(n).makeValid()))}}class y extends lt{constructor(e){if(ie(e)&&(e=e.value),e instanceof y||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=y.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(n==null)throw new Error(`unable to find data type for ${e.toString()}`);super(n.valueOf())}}get Array(){const e=y.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(n=>this.equals(n))}toString(e=!1){return e?y.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(y.JSON)||this.equals(y.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(y.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=y.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(y.UINT8)||this.equals(y.UINT16)||this.equals(y.UINT32)||this.equals(y.UINT64)}get isSignedInteger(){return this.equals(y.INT8)||this.equals(y.INT16)||this.equals(y.INT32)||this.equals(y.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(y.INT32)&&e.equals(y.FLOAT64)||this.equals(y.INT8)&&e.equals(y.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return y.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new y("unknown");static FLOAT64=new y("float64");static FLOAT32=new y("float32");static INT64=new y("int64");static INT32=new y("int32");static INT16=new y("int16");static INT8=new y("int8");static UINT64=new y("uint64");static UINT32=new y("uint32");static UINT16=new y("uint16");static UINT8=new y("uint8");static BOOLEAN=new y("boolean");static TIMESTAMP=new y("timestamp");static UUID=new y("uuid");static STRING=new y("string");static JSON=new y("json");static ARRAY_CONSTRUCTORS=new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]]);static DENSITIES=new Map([[y.UINT8.toString(),C.BIT8],[y.UINT16.toString(),C.BIT16],[y.UINT32.toString(),C.BIT32],[y.UINT64.toString(),C.BIT64],[y.FLOAT32.toString(),C.BIT32],[y.FLOAT64.toString(),C.BIT64],[y.INT8.toString(),C.BIT8],[y.INT16.toString(),C.BIT16],[y.INT32.toString(),C.BIT32],[y.INT64.toString(),C.BIT64],[y.TIMESTAMP.toString(),C.BIT64],[y.STRING.toString(),C.UNKNOWN],[y.JSON.toString(),C.UNKNOWN],[y.UUID.toString(),C.BIT128]]);static ALL=[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON];static SHORT_STRINGS=new Map([[y.UINT8.toString(),"u8"],[y.UINT16.toString(),"u16"],[y.UINT32.toString(),"u32"],[y.UINT64.toString(),"u64"],[y.INT8.toString(),"i8"],[y.INT16.toString(),"i16"],[y.INT32.toString(),"i32"],[y.INT64.toString(),"i64"],[y.FLOAT32.toString(),"f32"],[y.FLOAT64.toString(),"f64"],[y.BOOLEAN.toString(),"bool"],[y.TIMESTAMP.toString(),"ts"],[y.UUID.toString(),"uuid"],[y.STRING.toString(),"str"],[y.JSON.toString(),"json"]]);static BIG_INT_TYPES=[y.INT64,y.UINT64,y.TIMESTAMP];static z=i.z.union([i.z.string().transform(e=>new y(e)),i.z.instanceof(y)])}class $ extends lt{constructor(e){ie(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return ie(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return ie(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return ie(e)&&(e=e.value),new $(_e(this.valueOf(),e.valueOf()))}sub(e){return ie(e)&&(e=e.value),new $(Ce(this.valueOf(),e.valueOf()))}mult(e){return new $(me(this.valueOf(),e))}div(e){return new $(rn(this.valueOf(),e))}truncate(e){return new $(Math.trunc(this.valueOf()/new $(e).valueOf())*new $(e).valueOf())}remainder(e){return $.bytes(this.valueOf()%new $(e).valueOf())}get gigabytes(){return this.valueOf()/$.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/$.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/$.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/$.TERABYTE.valueOf()}toString(){const e=this.truncate($.TERABYTE),n=this.truncate($.GIGABYTE),r=this.truncate($.MEGABYTE),s=this.truncate($.KILOBYTE),a=this.truncate($.BYTE),o=e,c=n.sub(e),l=r.sub(n),u=s.sub(r),h=a.sub(s);let d="";return o.isZero||(d+=`${o.terabytes}TB `),c.isZero||(d+=`${c.gigabytes}GB `),l.isZero||(d+=`${l.megabytes}MB `),u.isZero||(d+=`${u.kilobytes}KB `),(!h.isZero||d==="")&&(d+=`${h.valueOf()}B`),d.trim()}static bytes(e=1){return new $(e)}static BYTE=new $(1);static kilobytes(e=1){return $.bytes(new $(e).valueOf()*1e3)}static KILOBYTE=$.kilobytes(1);static megabytes(e=1){return $.kilobytes(new $(e).valueOf()*1e3)}static MEGABYTE=$.megabytes(1);static gigabytes(e=1){return $.megabytes(new $(e).valueOf()*1e3)}static GIGABYTE=$.gigabytes(1);static terabytes(e){return $.gigabytes(new $(e).valueOf()*1e3)}static TERABYTE=$.terabytes(1);static ZERO=new $(0);static z=i.z.union([i.z.number().transform(e=>new $(e)),i.z.instanceof($)]);get isZero(){return this.valueOf()===0}}i.z.object({start:i.z.number(),end:i.z.number()});i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const Bo=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof w||t instanceof m||t instanceof Date},cp=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Ce(n,r),up=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function lp(t){return typeof t=="string"&&up.test(t)}const X=[];for(let t=0;t<256;++t)X.push((t+256).toString(16).slice(1));function hp(t,e=0){return(X[t[e+0]]+X[t[e+1]]+X[t[e+2]]+X[t[e+3]]+"-"+X[t[e+4]]+X[t[e+5]]+"-"+X[t[e+6]]+X[t[e+7]]+"-"+X[t[e+8]]+X[t[e+9]]+"-"+X[t[e+10]]+X[t[e+11]]+X[t[e+12]]+X[t[e+13]]+X[t[e+14]]+X[t[e+15]]).toLowerCase()}function fp(t,e=0){const n=hp(t,e);if(!lp(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const qo=(t,e)=>fp(t,e),De=-1,Pr={[Symbol.iterator]:()=>Pr,next:()=>({done:!0,value:void 0})},dp=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),yp=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Br=10,Fo=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Yo="sy_x_telem_series";class Q{key;discriminator=Yo;dataType;sampleOffset;gl;_data;timeRange=x.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=De;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=i.z.object({timeRange:x.z.optional(),dataType:y.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([dp,yp,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:ap.default("static").optional()});static z=Q.crudeZ.transform(e=>new Q(e));constructor(e){pp(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:l=ys(),data:u}=e;if(Go(u)){const f=u;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=Bo(u),d=Array.isArray(u);if(n!=null)this.dataType=new y(n);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(d||h){let f=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=u[0]}if(typeof f=="string")this.dataType=y.STRING;else if(typeof f=="number")this.dataType=y.FLOAT64;else if(typeof f=="bigint")this.dataType=y.INT64;else if(typeof f=="boolean")this.dataType=y.BOOLEAN;else if(f instanceof w||f instanceof Date||f instanceof w)this.dataType=y.TIMESTAMP;else if(typeof f=="object")this.dataType=y.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new y(u)}if(!d&&!h)this._data=u;else if(d&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[u]:u;const O=f[0];(O instanceof w||O instanceof Date||O instanceof m)&&(f=f.map(S=>new w(S).valueOf())),this.dataType.equals(y.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
8
+ `).map(c=>c.trim());if(r.length===0)return n!=null?n.parse({}):{};const a=r.split(",").map(c=>c.trim()),o={};return a.forEach(c=>{o[c]=[]}),s.forEach(c=>{const u=c.split(",").map(l=>l.trim());a.forEach((l,h)=>{const d=this.parseValue(u[h]);d!=null&&o[l].push(d)})}),n!=null?n.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const n=Number(e);return isNaN(n)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:n}}class To{contentType="text/plain";encode(e){if(typeof e!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(e)}decode(e,n){const r=new TextDecoder().decode(e);return n!=null?n.parse(r):r}}const Wt=new vo,Wd=new zo,Jd=new To,Kd=[Wt],Jn=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:zo,CSV_CODEC:Wd,ENCODERS:Kd,JSONCodec:vo,JSON_CODEC:Wt,TEXT_CODEC:Jd,TextCodec:To},Symbol.toStringTag,{value:"Module"})),he=t=>t!=null&&typeof t=="object"&&"value"in t;class dt{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const Ns=t=>t!=null&&typeof t=="object"&&"toString"in t,Oo=t=>{if(Ns(t))return t?.toString().length===0;switch(typeof t){case"string":return t.length===0;case"number":return t===0;case"bigint":return t===0n;case"boolean":return!t;case"undefined":return!0;case"object":return t==null;default:return!1}},Xd=t=>!Oo(t),Qd=Object.freeze(Object.defineProperty({__proto__:null,ValueExtension:dt,isCrudeValueExtension:he,isNonZero:Xd,isStringer:Ns,isZero:Oo},Symbol.toStringTag,{value:"Module"})),Wr=t=>[...new Set(t)],ep=(t,e,n=!0)=>{const r=new Map;return t.forEach(s=>{const a=e(s);if(r.has(a)){if(n)return;r.delete(a)}r.set(a,s)}),Array.from(r.values())},Li=Object.freeze(Object.defineProperty({__proto__:null,by:ep,unique:Wr},Symbol.toStringTag,{value:"Module"})),un=(t,e=!1)=>{const n=Ns(t)?"stringer":typeof t;let r;switch(n){case"string":r=(s,a)=>s.localeCompare(a);break;case"stringer":r=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":r=(s,a)=>Number(s)-Number(a);break;case"bigint":r=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":r=(s,a)=>Number(s)-Number(a);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return e?Eo(r):r},tp=(t,e,n)=>{const r=un(e[t],n);return(s,a)=>r(s[t],a[t])},np=(t,e)=>t.length!==e.length?t.length-e.length:t.every((n,r)=>n===e[r])?0:-1,So=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const n=un(t[0]),r=[...t].sort(n),s=[...e].sort(n);return r.every((a,o)=>a===s[o])?0:-1},rp=(t,e)=>{const n=Wr(t),r=Wr(e);return So(n,r)},sp=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,Eo=t=>(e,n)=>t(n,e),pt=0,Ce=-1,_e=1,No=t=>t<pt,$o=t=>t>pt,ip=t=>t>=pt,ko=t=>t===pt,ap=(t,e)=>{const n=/([a-zA-Z]+)|(\d+)/g,r=t.replace(/[\s_.-]+/g,"").match(n),s=e.replace(/[\s_.-]+/g,"").match(n);if(!r||!s)return 0;for(let a=0;a<Math.min(r.length,s.length);a++){const o=r[a],c=s[a];if(isNaN(Number(o))&&isNaN(Number(c))){const u=o.localeCompare(c);if(u!==0)return u}else if(!isNaN(Number(o))&&!isNaN(Number(c))){const u=Number(o)-Number(c);if(u!==0)return u}else return isNaN(Number(o))?-1:1}return r.length-s.length},Ao=(t,e,n)=>{let r=0,s=t.length;const a=n??un(e);for(;r<s;){const o=Math.floor((r+s)/2),c=a(t[o],e);if(c===0)return o;c<0?r=o+1:s=o}return r},op=(t,e,n)=>{const r=Ao(t,e,n);t.splice(r,0,e)},Di=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:pt,GREATER_THAN:_e,LESS_THAN:Ce,insert:op,isEqualTo:ko,isGreaterThan:$o,isGreaterThanEqual:ip,isLessThan:No,newF:un,newFieldF:tp,order:sp,primitiveArrays:np,reverseF:Eo,search:Ao,stringsWithNumbers:ap,uniqueUnorderedPrimitiveArrays:rp,unorderedPrimitiveArrays:So},Symbol.toStringTag,{value:"Module"}));let Io=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const Zo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",cp=`0123456789${Zo}`,xo=11,up=Io(Zo,1),lp=Io(cp,xo-1),$s=()=>`${up()}${lp()}`,Co=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:xo,create:$s},Symbol.toStringTag,{value:"Module"})),hp=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,fp=2**8-1,_o=2**12-1,dp=2**16-1,pp=2**32-1,yp=2n**64n-1n,mp=2**64-1,gp=-128,wp=2**7-1,bp=-32768,vp=2**15-1,zp=-2147483648,Tp=2**31-1,Op=-(2n**63n),Rn=2n**63n-1n,Sp=-9223372036854776e3,Mo=2**63-1,Zt=t=>(e,n)=>{if(typeof e=="bigint"){if(jn(n))return t(e,BigInt(n));const r=t(Number(e),Number(n));return typeof r=="number"?BigInt(Math.round(r)):r}return t(Number(e),Number(n))},Re=Zt((t,e)=>t-e),je=Zt((t,e)=>t+e),Ep=(t,e,n=1e-4)=>Math.abs(t-e)<n,Jr=(t,e)=>{const n=typeof t=="bigint",r=typeof e=="bigint";return n&&r?t===e:n&&jn(e)?t===BigInt(e):r&&jn(t)?e===BigInt(t):t===e},Np=t=>{const e=10**Math.floor(Math.log10(t));return Math.round(t/e)*e},Ro=Zt((t,e)=>t<=e?t:e),jn=t=>typeof t=="bigint"?!0:Number.isInteger(t),$p=Zt((t,e)=>t>=e?t:e),jo=t=>typeof t=="bigint"?t<0n?-t:t:t<0?-t:t,we=Zt((t,e)=>t*e),ln=Zt((t,e)=>t/e),Uo=i.z.tuple([i.z.number(),i.z.number()]),Po=i.z.object({width:i.z.number(),height:i.z.number()}),kp=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),Ap=["start","center","end"],$t=i.z.object({x:i.z.number(),y:i.z.number()}),Lo=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),ks=["x","y"],Do=i.z.enum(ks),As=["top","right","bottom","left"],Ip=i.z.enum(As),Bo=["left","right"],Is=i.z.enum(Bo),Zs=["top","bottom"],xs=i.z.enum(Zs),Cs=["center"],Kr=i.z.enum(Cs),Zp=[...As,...Cs],_s=i.z.enum(Zp);i.z.enum(Ap);const xp=["first","last"];i.z.enum(xp);i.z.object({lower:i.z.number(),upper:i.z.number()});i.z.enum([...Do.options,..._s.options]);const Cp=i.z.union([Do,_s,i.z.instanceof(String)]),K=(t,e,n)=>{const r={};if(typeof e=="object"&&(n=e,e=void 0),n={makeValid:!0,...n},typeof t=="number"||typeof t=="bigint")e!=null?(r.lower=t,r.upper=e):(r.lower=typeof t=="bigint"?0n:0,r.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[r.lower,r.upper]=t}else r.lower=t.lower,r.upper=t.upper;return n?.makeValid?_p(r):r},_p=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,Bi=(t,e)=>{const n=K(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e},Nn=(t,e)=>{const n=K(t);if(typeof e=="number"||typeof e=="bigint")return e>=n.lower&&e<n.upper;const r=K(e);return r.lower>=n.lower&&r.upper<=n.upper},Mp=t=>{const e=K(t);return e.upper-e.lower},Rp=t=>({lower:Math.min(...t.map(e=>K(e).lower)),upper:Math.max(...t.map(e=>K(e).upper))}),jp=(t,e,n)=>{const r=t.map(c=>K(c)),s=n>0?1:n<0?-1:0;if(s===0)return e;let a=n,o=e;for(;Jr(a,0)===!1;){const c=r.findIndex(u=>s>0?o>=u.lower&&o<u.upper:o>u.lower&&o<=u.upper);if(c!==-1){const u=r[c];let l;if(s>0?l=Re(u.upper,o):l=Re(o,u.lower),l>0){const h=Ro(jo(a),l);if(o=je(o,s>0?h:-h),a=Re(a,s>0?h:-h),Jr(a,0))return o;continue}}if(s>0){const u=r.filter(l=>l.lower>o);if(u.length>0)o=u[0].lower;else return o}else{const u=r.filter(l=>l.upper<o);if(u.length>0)o=u[u.length-1].upper;else return o}}return o},Up=(t,e,n)=>{const r=t.map(o=>K(o));if(e===n)return typeof e=="bigint"?0n:0;const s=e<n?K([e,n]):K([n,e]);let a=typeof e=="bigint"?0n:0;for(const o of r){const c=o.lower>s.lower?o.lower:s.lower,u=o.upper<s.upper?o.upper:s.upper;if(c<u){const l=u-c;a=a+l}}return a},qi=2,Fi=3,Pp=2,Lp=5,Dp=1e-10,Bp=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=Math.abs(t);if(n===0)return 0;let r=!1,s=0;if(e!=null){s=Mp(e);const c=s/n;r=s>0&&c>Dp}if(r){let c;s>=1e3?c=qi:s>=1?c=Fi:c=Math.ceil(-Math.log10(s))+Pp;const u=10**c;return Math.round(t*u)/u}if(n>=1e3){const c=10**qi;return Math.round(t*c)/c}if(n>=1){const c=10**Fi;return Math.round(t*c)/c}const a=Math.floor(Math.log10(n)),o=10**(Lp-a-1);return Math.round(t*o)/o},Xr=Object.freeze(Object.defineProperty({__proto__:null,MAX_INT16:vp,MAX_INT32:Tp,MAX_INT64:Rn,MAX_INT64_NUMBER:Mo,MAX_INT8:wp,MAX_UINT12:_o,MAX_UINT16:dp,MAX_UINT32:pp,MAX_UINT64:yp,MAX_UINT64_NUMBER:mp,MAX_UINT8:fp,MIN_INT16:bp,MIN_INT32:zp,MIN_INT64:Op,MIN_INT64_NUMBER:Sp,MIN_INT8:gp,abs:jo,add:je,closeTo:Ep,div:ln,equal:Jr,isInteger:jn,max:$p,min:Ro,mult:we,roundToNearestMagnitude:Np,smartRound:Bp,sub:Re},Symbol.toStringTag,{value:"Module"})),qp=t=>ks.includes(t)?t:Zs.includes(t)?"y":"x",Fp=Is,Yp=xs,Hp=Kr,Vp={top:"bottom",right:"left",bottom:"top",left:"right",center:"center"},Gp={top:{clockwise:"left",counterclockwise:"right"},right:{clockwise:"top",counterclockwise:"bottom"},bottom:{clockwise:"right",counterclockwise:"left"},left:{clockwise:"bottom",counterclockwise:"top"}},Wp=Cp,ut=t=>t instanceof String||!ks.includes(t)?t:t==="x"?"left":"top",Jp=t=>Vp[ut(t)],Kp=(t,e)=>Gp[t][e],Jt=t=>{const e=ut(t);return e==="top"||e==="bottom"?"y":"x"},Xp=i.z.object({x:Is.or(Kr),y:xs.or(Kr)}),Ms=i.z.object({x:Is,y:xs}),Rs=Object.freeze({x:"left",y:"top"}),qo=Object.freeze({x:"right",y:"top"}),Fo=Object.freeze({x:"left",y:"bottom"}),Yo=Object.freeze({x:"right",y:"bottom"}),js=Object.freeze({x:"center",y:"center"}),Ho=Object.freeze({x:"center",y:"top"}),Vo=Object.freeze({x:"center",y:"bottom"}),Go=Object.freeze({x:"right",y:"center"}),Wo=Object.freeze({x:"left",y:"center"}),Qp=Object.freeze([Wo,Go,Ho,Vo,Rs,qo,Fo,Yo,js]),Jo=(t,e)=>t.x===e.x&&t.y===e.y,ey=(t,e)=>{if(typeof e=="object"){let n=!0;return"x"in e&&(t.x===e.x||(n=!1)),"y"in e&&(t.y===e.y||(n=!1)),n}return t.x===e||t.y===e},ty=t=>[t.x,t.y],_n=t=>Jt(ut(t))==="x",ny=t=>Jt(ut(t))==="y",ry=t=>`${t.x}${wo(t.y)}`,sy=(t,e)=>{let n,r;if(typeof t=="object"&&"x"in t?(n=t.x,r=t.y):(n=ut(t),r=ut(e??t)),Jt(n)===Jt(r)&&n!=="center"&&r!=="center")throw new Error(`[XYLocation] - encountered two locations with the same direction: ${n.toString()} - ${r.toString()}`);const s={...js};return n==="center"?_n(r)?[s.x,s.y]=[r,n]:[s.x,s.y]=[n,r]:r==="center"?_n(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n]:_n(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n],s},iy=Object.freeze(Object.defineProperty({__proto__:null,BOTTOM_CENTER:Vo,BOTTOM_LEFT:Fo,BOTTOM_RIGHT:Yo,CENTER:js,CENTER_LEFT:Wo,CENTER_LOCATIONS:Cs,CENTER_RIGHT:Go,OUTER_LOCATIONS:As,TOP_CENTER:Ho,TOP_LEFT:Rs,TOP_RIGHT:qo,XY_LOCATIONS:Qp,X_LOCATIONS:Bo,Y_LOCATIONS:Zs,center:Hp,construct:ut,constructXY:sy,corner:Ms,crude:Wp,direction:Jt,isX:_n,isY:ny,location:_s,outer:Ip,rotate:Kp,swap:Jp,x:Fp,xy:Xp,xyCouple:ty,xyEquals:Jo,xyMatches:ey,xyToString:ry,y:Yp},Symbol.toStringTag,{value:"Module"})),Qr=i.z.union([i.z.number(),$t,Uo,Po,kp,Lo]),j=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},lt=Object.freeze({x:0,y:0}),ay=Object.freeze({x:1,y:1}),oy=Object.freeze({x:1/0,y:1/0}),cy=Object.freeze({x:NaN,y:NaN}),Ko=(t,e,n=0)=>{const r=j(t),s=j(e);return n===0?r.x===s.x&&r.y===s.y:Math.abs(r.x-s.x)<=n&&Math.abs(r.y-s.y)<=n},uy=t=>Ko(t,lt),Us=(t,e,n)=>{const r=j(t),s=j(e,n);return{x:r.x*s.x,y:r.y*s.y}},Xo=(t,e)=>{const n=j(t);return{x:n.x+e,y:n.y}},Qo=(t,e)=>{const n=j(t);return{x:n.x,y:n.y+e}},ec=(t,e,n,...r)=>{if(typeof e=="string"){if(typeof n!="number")throw new Error("The value must be a number.");return e==="x"?Xo(t,n):Qo(t,n)}if(typeof e=="object"&&"x"in e&&typeof e.x=="string"){const s=j(n),a=j(t);return e.x==="left"?s.x=-s.x:e.x==="center"&&(s.x=0),e.y==="top"?s.y=-s.y:e.y==="center"&&(s.y=0),{x:a.x+s.x,y:a.y+s.y}}return[t,e,n??lt,...r].reduce((s,a)=>{const o=j(a);return{x:s.x+o.x,y:s.y+o.y}},lt)},ly=(t,e,n)=>{const r=j(t);return qp(e)==="x"?{x:n,y:r.y}:{x:r.x,y:n}},hy=(t,e)=>{const n=j(t),r=j(e);return Math.sqrt((n.x-r.x)**2+(n.y-r.y)**2)},fy=(t,e)=>{const n=j(t),r=j(e);return{x:r.x-n.x,y:r.y-n.y}},dy=t=>{const e=j(t);return Number.isNaN(e.x)||Number.isNaN(e.y)},py=t=>{const e=j(t);return Number.isFinite(e.x)&&Number.isFinite(e.y)},yy=t=>{const e=j(t);return[e.x,e.y]},my=t=>{const e=j(t);return{left:e.x,top:e.y}},gy=(t,e=0)=>{const n=j(t);return{x:Number(n.x.toFixed(e)),y:Number(n.y.toFixed(e))}},Pt=(t,e)=>{const n=j(t),r=j(e);return{x:n.x-r.x,y:n.y-r.y}},Lt=t=>{const e=j(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:-e.y/n,y:e.x/n}},tc=t=>{const e=j(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:e.x/n,y:e.y/n}},nc=(...t)=>{const e=t.reduce((n,r)=>ec(n,r),lt);return Us(e,1/t.length)},wy=(t,e)=>{const n=[];for(let r=0;r<t.length;r++){const s=t[r];let a,o,c,u;if(r===0){const l=t[r+1],h=Pt(l,s);o=Lt(h),c=o,u=e}else if(r===t.length-1){const l=t[r-1],h=Pt(s,l);a=Lt(h),c=a,u=e}else{const l=t[r-1],h=t[r+1],d=Pt(s,l),f=Pt(h,s);a=Lt(d),o=Lt(f);const b=Math.acos((d.x*f.x+d.y*f.y)/(Math.hypot(d.x,d.y)*Math.hypot(f.x,f.y))),N=Math.sin(b/2);N===0?u=e:u=e/N,c=tc(nc(a,o))}n.push(Us(c,u))}return n},by=t=>{const e=j(t);return{x:e.y,y:e.x}},vy=t=>{const e=j(t);return{x:Math.round(e.x),y:Math.round(e.y)}},zy=t=>{const e=j(t);return{x:1/e.x,y:1/e.y}},Ty=(t,e,n)=>{const r=j(t),s=j(e),a=n==="clockwise"?Math.PI/2:-Math.PI/2,o=r.x-s.x,c=r.y-s.y,u=o*Math.cos(a)-c*Math.sin(a),l=o*Math.sin(a)+c*Math.cos(a);return{x:u+s.x,y:l+s.y}},Ps=Object.freeze(Object.defineProperty({__proto__:null,INFINITY:oy,NAN:cy,ONE:ay,ZERO:lt,average:nc,calculateMiters:wy,clientXY:Lo,construct:j,couple:yy,crudeZ:Qr,css:my,distance:hy,equals:Ko,isFinite:py,isNan:dy,isZero:uy,normal:Lt,normalize:tc,reciprocal:zy,rotate:Ty,round:vy,scale:Us,set:ly,sub:Pt,swap:by,translate:ec,translateX:Xo,translateY:Qo,translation:fy,truncate:gy,xy:$t},Symbol.toStringTag,{value:"Module"})),$n=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:$n,left:$n,width:$n,height:$n});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:$t,two:$t,root:Ms});const Ls=(t,e,n=0,r=0,s)=>{const a={one:{...lt},two:{...lt},root:s??Rs};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:t,y:e},a.two={x:a.one.x+n,y:a.one.y+r},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(a.one={x:t.left,y:t.top},a.two={x:t.right,y:t.bottom},a):(a.one=t,e==null?a.two={x:a.one.x+n,y:a.one.y+r}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+n}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},Er=t=>{const e=Ls(t);return{lower:e.one.x,upper:e.two.x}},Nr=t=>{const e=Ls(t);return{lower:e.one.y,upper:e.two.y}},Oy=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,Sy=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([Po,Sy,$t,Uo]);const Ey=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:Qr,scale:Qr});i.z.object({offset:i.z.number(),scale:i.z.number()});const Ny=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],$y=t=>(e,n,r,s)=>[e,s?r/t:r*t],ky=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:a}=e,{lower:o,upper:c}=t,u=a-s,l=c-o;if(n==="dimension")return[t,r*(l/u)];const h=(r-s)*(l/u)+o;return[t,h]},Ay=t=>(e,n,r)=>[t,r],Iy=()=>(t,e,n)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,n];const{lower:r,upper:s}=t;return[t,s-(n-r)]},Zy=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=Ey(r,s,a),[e,r]};class Ge{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Ge().translate(e)}static magnify(e){return new Ge().magnify(e)}static scale(e,n){return new Ge().scale(e,n)}translate(e){const n=this.new(),r=Ny(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=$y(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=K(e,n),s=this.new(),a=ky(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=K(e,n),s=this.new(),a=Zy(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=K(e,n),s=this.new(),a=Ay(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Iy();e.type="invert";const n=this.new();return n.ops.push(e),n}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Ge;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],a)=>a(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&n.push([s,a])}),n.forEach(([r,s])=>{const a=e.ops.slice(r,s);a.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Ge}class Ee{x;y;currRoot;constructor(e=new Ge,n=new Ge,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new Ee().translate(e,n)}static translateX(e){return new Ee().translateX(e)}static translateY(e){return new Ee().translateY(e)}static clamp(e){return new Ee().clamp(e)}static magnify(e){return new Ee().magnify(e)}static scale(e){return new Ee().scale(e)}static reBound(e){return new Ee().reBound(e)}translate(e,n){const r=j(e,n),s=this.copy();return s.x=this.x.translate(r.x),s.y=this.y.translate(r.y),s}translateX(e){const n=this.copy();return n.x=this.x.translate(e),n}translateY(e){const n=this.copy();return n.y=this.y.translate(e),n}magnify(e){const n=this.copy();return n.x=this.x.magnify(e.x),n.y=this.y.magnify(e.y),n}scale(e){const n=this.copy();if(Oy(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!Jo(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(Er(e)),n.y=n.y.scale(Nr(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(Er(e)),n.y=this.y.reBound(Nr(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(Er(e)),n.y=this.y.clamp(Nr(e)),n}copy(){const e=new Ee;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Ls(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new Ee}const xy=$t.extend({root:Ms,units:i.object({x:i.enum(["px","decimal"]),y:i.enum(["px","decimal"])})});xy.partial({root:!0,units:!0});const Cy=i.z.enum(["static","dynamic"]),Yi=365,kn=30,_y=i.z.union([i.z.tuple([i.z.int()]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12)]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12),i.z.int().min(1).max(31)])]),rc=(t,e)=>{const n=new m(e);if(![w.DAY,w.HOUR,w.MINUTE,w.SECOND,w.MILLISECOND,w.MICROSECOND,w.NANOSECOND].some(s=>s.equals(n)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=t.valueOf()%n.valueOf();return t instanceof m?new m(r):new w(r)};class m extends dt{constructor(e,n="UTC"){if(e==null)super(m.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*m.MILLISECOND.valueOf());else if(typeof e=="string")super(m.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(m.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=m.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===Mo?e=Rn:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=m.MAX:e=m.MIN)),he(e)&&(e=e.value),super(BigInt(e.valueOf())+r)}}static parseDate([e=1970,n=1,r=1]){const s=new Date(e,n-1,r,0,0,0,0);return new m(BigInt(s.getTime())*m.MILLISECOND.valueOf()).truncate(m.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let u=m.hours(parseInt(r??"00")).add(m.minutes(parseInt(s??"00"))).add(m.seconds(parseInt(o??"00"))).add(m.milliseconds(parseInt(c??"00")));return n==="local"&&(u=u.add(m.utcOffset)),u.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return m.parseTimeString(e,n);if(e.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let s=e,a=0;if(e.includes(".")){const l=e.split(".");s=l[0];const h=l[1]||"0";a=parseInt(h.padEnd(3,"0").slice(0,3))}const o=n==="local"?new Date(s.replace("T"," ")):new Date(`${s}Z`),c=BigInt(o.getTime())*m.MILLISECOND.valueOf(),u=BigInt(a)*m.MILLISECOND.valueOf();return c+u}const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new m(BigInt(r.getTime())*m.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){if(e==="UTC")return this.date().toISOString();const n=this.date(),r=new w(BigInt(n.getTimezoneOffset())*m.MINUTE.valueOf());return this.sub(r).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new w(BigInt(new Date().getTimezoneOffset())*m.MINUTE.valueOf())}static since(e){return new m().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new m(e).valueOf()}span(e){return this.range(e).span}range(e){return new x(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new m(e).valueOf()}afterEq(e){return this.valueOf()>=new m(e).valueOf()}before(e){return this.valueOf()<new m(e).valueOf()}beforeEq(e){return this.valueOf()<=new m(e).valueOf()}add(e){return new m(je(this.valueOf(),new w(e).valueOf()))}sub(e){return new m(Re(this.valueOf(),new w(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(w.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(w.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(w.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(w.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(m.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(m.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}get localYear(){return this.date().getFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new m(n)}setLocalYear(e){const n=this.date();return n.setFullYear(e),new m(n)}get month(){return this.date().getUTCMonth()}get localMonth(){return this.date().getMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new m(n)}setLocalMonth(e){const n=this.date();return n.setMonth(e),new m(n)}get day(){return this.date().getUTCDate()}get localDay(){return this.date().getDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new m(n)}setLocalDay(e){const n=this.date();return n.setDate(e),new m(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new m(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new m(n)}get minute(){return this.date().getUTCMinutes()}get localMinute(){return this.date().getMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new m(n)}setLocalMinute(e){const n=this.date();return n.setMinutes(e),new m(n)}get second(){return this.date().getUTCSeconds()}get localSecond(){return this.date().getSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new m(n)}setLocalSecond(e){const n=this.date();return n.setSeconds(e),new m(n)}get millisecond(){return this.date().getUTCMilliseconds()}get localMillisecond(){return this.date().getMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new m(n)}setLocalMillisecond(e){const n=this.date();return n.setMilliseconds(e),new m(n)}toString(e="ISO",n="UTC"){switch(e){case"ISODate":return this.toISOString(n).slice(0,10);case"ISOTime":return this.toISOString(n).slice(11,23);case"time":return this.timeString(!1,n);case"preciseTime":return this.timeString(!0,n);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,n)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,n)}`;default:return this.toISOString(n)}}remainder(e){return rc(this,e)}get isToday(){return this.truncate(w.DAY).equals(m.now().truncate(w.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(w.days(30))?"shortDate":e.greaterThanOrEqual(w.DAY)?"dateTime":e.greaterThanOrEqual(w.HOUR)?"time":e.greaterThanOrEqual(w.SECOND)?"preciseTime":"ISOTime"}static now(){return new m(new Date)}static max(...e){let n=m.MIN;for(const r of e){const s=new m(r);s.after(n)&&(n=s)}return n}static min(...e){let n=m.MAX;for(const r of e){const s=new m(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new m(e,n)}static NANOSECOND=m.nanoseconds(1);static microseconds(e,n="UTC"){return m.nanoseconds(e*1e3,n)}static MICROSECOND=m.microseconds(1);static milliseconds(e,n="UTC"){return m.microseconds(e*1e3,n)}static MILLISECOND=m.milliseconds(1);static seconds(e,n="UTC"){return m.milliseconds(e*1e3,n)}static SECOND=m.seconds(1);static minutes(e,n="UTC"){return m.seconds(e*60,n)}static MINUTE=m.minutes(1);static hours(e,n="UTC"){return m.minutes(e*60,n)}static HOUR=m.hours(1);static days(e,n="UTC"){return m.hours(e*24,n)}static DAY=m.days(1);static MAX=new m(Rn);static MIN=new m(0);static ZERO=new m(0);static z=i.z.union([i.z.instanceof(m),i.z.object({value:i.z.bigint()}).transform(e=>new m(e.value)),i.z.string().transform(e=>new m(BigInt(e))),i.z.number().transform(e=>new m(e)),i.z.bigint().transform(e=>new m(e)),i.z.date().transform(e=>new m(e)),i.z.custom(e=>e instanceof w).transform(e=>new m(e)),_y.transform(e=>new m(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}}class w extends dt{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),he(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof w?e:e instanceof G?e.period:e instanceof m?new w(e):(he(e)&&(e=e.value),["number","bigint"].includes(typeof e)?w.seconds(e):new w(e))}static fromMilliseconds(e){return e instanceof w?e:e instanceof G?e.period:e instanceof m?new w(e):(he(e)&&(e=e.value),["number","bigint"].includes(typeof e)?w.milliseconds(e):new w(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new w(e).valueOf()}greaterThan(e){return this.valueOf()>new w(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new w(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new w(e).valueOf()}remainder(e){return rc(this,e)}truncate(e){return new w(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(w.DAY),r=this.truncate(w.HOUR),s=this.truncate(w.MINUTE),a=this.truncate(w.SECOND),o=this.truncate(w.MILLISECOND),c=this.truncate(w.MICROSECOND),u=this.truncate(w.NANOSECOND),l=n,h=r.sub(n),d=s.sub(r),f=a.sub(s),b=o.sub(a),N=c.sub(o),k=u.sub(c);let O="";return l.isZero||(O+=`${l.days}d `),h.isZero||(O+=`${h.hours}h `),d.isZero||(O+=`${d.minutes}m `),f.isZero||(O+=`${f.seconds}s `),b.isZero||(O+=`${b.milliseconds}ms `),N.isZero||(O+=`${N.microseconds}µs `),k.isZero||(O+=`${k.nanoseconds}ns`),O.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new w(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(w.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,u=Math.floor(s/Yi),l=Math.floor(s/kn),h=Math.floor(s/7),d=Math.floor(s),f=Math.floor(a),b=Math.floor(o),N=Math.floor(c),k=r?"-":"";if(u>=1){let O=`${u}y`;if(u<2){const S=Math.floor(s%Yi/kn);S>0&&(O+=` ${S}mo`)}return k+O}if(h>=1&&s<kn&&s%7===0){let O=`${h}w`;const S=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(S>0?O+=` ${S}d`:A>0&&A<24&&(O+=` ${A}h`)),k+O}if(l>=1){let O=`${l}mo`;if(l<3){const S=Math.floor(s%kn);S>0&&(O+=` ${S}d`)}return k+O}if(h>=1){let O=`${h}w`;const S=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(S>0?O+=` ${S}d`:A>0&&A<24&&(O+=` ${A}h`)),k+O}if(d>=1){let O=`${d}d`;const S=Math.floor(a-d*24);return d<2&&S>0&&(O+=` ${S}h`),k+O}if(f>=1){let O=`${f}h`;if(f<3){const S=Math.floor(o-f*60);S>0&&(O+=` ${S}m`)}return k+O}if(b>=1){let O=`${b}m`;if(b<5){const S=Math.floor(c-b*60);S>0&&(O+=` ${S}s`)}return k+O}return`${k}${N}s`}mult(e){return new w(we(this.valueOf(),e))}div(e){return new w(ln(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(w.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(w.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(w.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(w.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(w.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(w.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new w(e).valueOf()}add(e){return new w(this.valueOf()+new w(e).valueOf())}sub(e){return new w(this.valueOf()-new w(e).valueOf())}static nanoseconds(e=1){return new w(e)}static NANOSECOND=w.nanoseconds(1);static microseconds(e=1){return w.nanoseconds(we(e,1e3))}static MICROSECOND=w.microseconds(1);static milliseconds(e=1){return w.microseconds(we(e,1e3))}static MILLISECOND=w.milliseconds(1);static seconds(e=1){return w.milliseconds(we(e,1e3))}static SECOND=w.seconds(1);static minutes(e=1){return w.seconds(we(e,60))}static MINUTE=w.minutes(1);static hours(e){return w.minutes(we(e,60))}static HOUR=w.hours(1);static days(e){return w.hours(we(e,24))}static DAY=w.days(1);static MAX=new w(Rn);static MIN=new w(0);static ZERO=new w(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new w(e.value)),i.z.string().transform(e=>new w(BigInt(e))),i.z.number().transform(e=>new w(e)),i.z.bigint().transform(e=>new w(e)),i.z.instanceof(w),i.z.instanceof(m).transform(e=>new w(e)),i.z.custom(e=>e instanceof G).transform(e=>new w(e))])}class G extends dt{constructor(e){he(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new G(e).valueOf()}get period(){return w.seconds(1/this.valueOf())}sampleCount(e){return new w(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new M(n).valueOf()}span(e){return w.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new M(n).valueOf())}add(e){return new G(je(this.valueOf(),new G(e).valueOf()))}sub(e){return new G(Re(this.valueOf(),new G(e).valueOf()))}mult(e){return new G(we(this.valueOf(),e))}div(e){return new G(ln(this.valueOf(),e))}static hz(e){return new G(e)}static khz(e){return G.hz(e*1e3)}static z=i.z.union([i.z.number().transform(e=>new G(e)),i.z.instanceof(G)])}class M extends dt{constructor(e){he(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new I(e*this.valueOf())}add(e){return new M(je(this.valueOf(),new M(e).valueOf()))}sub(e){return new M(Re(this.valueOf(),new M(e).valueOf()))}mult(e){return new M(we(this.valueOf(),e))}div(e){return new M(ln(this.valueOf(),e))}static UNKNOWN=new M(0);static BIT128=new M(16);static BIT64=new M(8);static BIT32=new M(4);static BIT16=new M(2);static BIT8=new M(1);static z=i.z.union([i.z.number().transform(e=>new M(e)),i.z.instanceof(M)])}class x{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new m(e.start),this.end=new m(e.end)):(this.start=new m(e),this.end=new m(n))}get span(){return new w(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new x(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=w.ZERO){if(n.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return r<0&&(r=-r),s<0&&(s=-s),r<=n.valueOf()&&s<=n.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,n=w.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const s=m.max(r.start,e.start),a=m.min(r.end,e.end);return a.before(s)?!1:new w(a.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof x?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new x(this.start,this.end);return e.start.after(this.start)&&(n.start=e.start),e.start.after(this.end)&&(n.end=e.start),e.end.before(this.end)&&(n.end=e.end),e.end.before(this.start)&&(n.start=e.end),n}static max(...e){return new x(m.min(...e.map(n=>n.start)),m.max(...e.map(n=>n.end)))}static MAX=new x(m.MIN,m.MAX);static ZERO=new x(m.ZERO,m.ZERO);static z=i.z.union([i.z.object({start:m.z,end:m.z}).transform(e=>new x(e.start,e.end)),i.z.instanceof(x)]);static sort(e,n){return m.sort(e.start,n.start)||m.sort(e.end,n.end)}static merge(...e){return x.max(...e.map(n=>new x(n).makeValid()))}}class p extends dt{constructor(e){if(he(e)&&(e=e.value),e instanceof p||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=p.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(n==null)throw new Error(`unable to find data type for ${e.toString()}`);super(n.valueOf())}}get Array(){const e=p.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(n=>this.equals(n))}toString(e=!1){return e?p.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(p.JSON)||this.equals(p.STRING)||this.equals(p.BYTES)}get isNumeric(){return!this.isVariable&&!this.equals(p.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=p.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(p.UINT8)||this.equals(p.UINT16)||this.equals(p.UINT32)||this.equals(p.UINT64)}get isSignedInteger(){return this.equals(p.INT8)||this.equals(p.INT16)||this.equals(p.INT32)||this.equals(p.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(p.INT32)&&e.equals(p.FLOAT64)||this.equals(p.INT8)&&e.equals(p.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return p.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new p("unknown");static FLOAT64=new p("float64");static FLOAT32=new p("float32");static INT64=new p("int64");static INT32=new p("int32");static INT16=new p("int16");static INT8=new p("int8");static UINT64=new p("uint64");static UINT32=new p("uint32");static UINT16=new p("uint16");static UINT8=new p("uint8");static TIMESTAMP=new p("timestamp");static UUID=new p("uuid");static STRING=new p("string");static JSON=new p("json");static BYTES=new p("bytes");static ARRAY_CONSTRUCTORS=new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array],[p.BYTES.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]]);static DENSITIES=new Map([[p.UINT8.toString(),M.BIT8],[p.UINT16.toString(),M.BIT16],[p.UINT32.toString(),M.BIT32],[p.UINT64.toString(),M.BIT64],[p.FLOAT32.toString(),M.BIT32],[p.FLOAT64.toString(),M.BIT64],[p.INT8.toString(),M.BIT8],[p.INT16.toString(),M.BIT16],[p.INT32.toString(),M.BIT32],[p.INT64.toString(),M.BIT64],[p.TIMESTAMP.toString(),M.BIT64],[p.STRING.toString(),M.UNKNOWN],[p.JSON.toString(),M.UNKNOWN],[p.UUID.toString(),M.BIT128],[p.BYTES.toString(),M.UNKNOWN]]);static ALL=[p.UNKNOWN,p.UINT8,p.UINT16,p.UINT32,p.UINT64,p.INT8,p.INT16,p.INT32,p.INT64,p.FLOAT32,p.FLOAT64,p.TIMESTAMP,p.UUID,p.STRING,p.JSON,p.BYTES];static SHORT_STRINGS=new Map([[p.UINT8.toString(),"u8"],[p.UINT16.toString(),"u16"],[p.UINT32.toString(),"u32"],[p.UINT64.toString(),"u64"],[p.INT8.toString(),"i8"],[p.INT16.toString(),"i16"],[p.INT32.toString(),"i32"],[p.INT64.toString(),"i64"],[p.FLOAT32.toString(),"f32"],[p.FLOAT64.toString(),"f64"],[p.TIMESTAMP.toString(),"ts"],[p.UUID.toString(),"uuid"],[p.STRING.toString(),"str"],[p.JSON.toString(),"json"],[p.BYTES.toString(),"bytes"]]);static BIG_INT_TYPES=[p.INT64,p.UINT64,p.TIMESTAMP];static z=i.z.union([i.z.string().transform(e=>new p(e)),i.z.instanceof(p)])}class I extends dt{constructor(e){he(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return he(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return he(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return he(e)&&(e=e.value),new I(je(this.valueOf(),e.valueOf()))}sub(e){return he(e)&&(e=e.value),new I(Re(this.valueOf(),e.valueOf()))}mult(e){return new I(we(this.valueOf(),e))}div(e){return new I(ln(this.valueOf(),e))}truncate(e){return new I(Math.trunc(this.valueOf()/new I(e).valueOf())*new I(e).valueOf())}remainder(e){return I.bytes(this.valueOf()%new I(e).valueOf())}get gigabytes(){return this.valueOf()/I.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/I.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/I.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/I.TERABYTE.valueOf()}toString(){const e=this.truncate(I.TERABYTE),n=this.truncate(I.GIGABYTE),r=this.truncate(I.MEGABYTE),s=this.truncate(I.KILOBYTE),a=this.truncate(I.BYTE),o=e,c=n.sub(e),u=r.sub(n),l=s.sub(r),h=a.sub(s);let d="";return o.isZero||(d+=`${o.terabytes}TB `),c.isZero||(d+=`${c.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),l.isZero||(d+=`${l.kilobytes}KB `),(!h.isZero||d==="")&&(d+=`${h.valueOf()}B`),d.trim()}static bytes(e=1){return new I(e)}static BYTE=new I(1);static kilobytes(e=1){return I.bytes(new I(e).valueOf()*1e3)}static KILOBYTE=I.kilobytes(1);static megabytes(e=1){return I.kilobytes(new I(e).valueOf()*1e3)}static MEGABYTE=I.megabytes(1);static gigabytes(e=1){return I.megabytes(new I(e).valueOf()*1e3)}static GIGABYTE=I.gigabytes(1);static terabytes(e){return I.gigabytes(new I(e).valueOf()*1e3)}static TERABYTE=I.terabytes(1);static ZERO=new I(0);static z=i.z.union([i.z.number().transform(e=>new I(e)),i.z.instanceof(I)]);get isZero(){return this.valueOf()===0}}i.z.object({start:i.z.number(),end:i.z.number()});i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const sc=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof m||t instanceof w||t instanceof Date},My=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Re(n,r),Ry=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function jy(t){return typeof t=="string"&&Ry.test(t)}const ee=[];for(let t=0;t<256;++t)ee.push((t+256).toString(16).slice(1));function Uy(t,e=0){return(ee[t[e+0]]+ee[t[e+1]]+ee[t[e+2]]+ee[t[e+3]]+"-"+ee[t[e+4]]+ee[t[e+5]]+"-"+ee[t[e+6]]+ee[t[e+7]]+"-"+ee[t[e+8]]+ee[t[e+9]]+"-"+ee[t[e+10]]+ee[t[e+11]]+ee[t[e+12]]+ee[t[e+13]]+ee[t[e+14]]+ee[t[e+15]]).toLowerCase()}function Py(t,e=0){const n=Uy(t,e);if(!jy(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const ic=(t,e)=>Py(t,e),qe=-1,es={[Symbol.iterator]:()=>es,next:()=>({done:!0,value:void 0})},Ly=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Dy=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),ts=10,ac=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},oc="sy_x_telem_series";class te{key;discriminator=oc;dataType;sampleOffset;gl;_data;timeRange=x.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=qe;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=i.z.object({timeRange:x.z.optional(),dataType:p.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Ly,Dy,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:Cy.default("static").optional()});static z=te.crudeZ.transform(e=>new te(e));constructor(e){By(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:u=$s(),data:l}=e;if(cc(l)){const f=l;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=sc(l),d=Array.isArray(l);if(n!=null)this.dataType=new p(n);else{if(l instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(d||h){let f=l;if(!h){if(l.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=l[0]}if(typeof f=="string")this.dataType=p.STRING;else if(typeof f=="number")this.dataType=p.FLOAT64;else if(typeof f=="bigint")this.dataType=p.INT64;else if(typeof f=="boolean")this.dataType=p.UINT8;else if(f instanceof m||f instanceof Date||f instanceof m)this.dataType=p.TIMESTAMP;else if(typeof f=="object")this.dataType=p.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new p(l)}if(!d&&!h)this._data=l;else if(d&&l.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[l]:l;const b=f[0];(b instanceof m||b instanceof Date||b instanceof w)&&(f=f.map(N=>new m(N).valueOf())),this.dataType.equals(p.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
9
9
  `)}
10
- `).buffer):this.dataType.equals(y.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(S=>Ft.encodeString(S)).join(`
10
+ `).buffer):this.dataType.equals(p.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(N=>Wt.encodeString(N)).join(`
11
11
  `)}
12
- `).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(f.map(S=>BigInt(Math.round(S)))).buffer:!this.dataType.usesBigInt&&typeof O=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=l,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??x.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:n,...r}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const s=new new y(n).Array(e),a=new Q({data:s.buffer,dataType:n,...r});return a.writePos=0,a}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===De)return 0;const n=this.byteCapacity.valueOf()-this.writePos,r=e.subBytes(0,n);return this.writeToUnderlyingData(r),this.writePos+=r.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=r.length,this.calculateCachedLength()),r.length}writeFixed(e){if(this.writePos===De)return 0;const n=this.capacity-this.writePos,r=e.sub(0,n);return this.writeToUnderlyingData(r),this.cachedLength=void 0,this.maybeRecomputeMinMax(r),this.writePos+=r.length,r.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===De?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
13
- `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(y.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(Ft.decodeString(n)))}get byteCapacity(){return new $(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===De?this.byteCapacity:this.dataType.isVariable?new $(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===De?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const n=[0];return this.data.forEach((r,s)=>{r===Br&&(e++,n.push(s+1))}),this._cachedIndexes=n,this.cachedLength=e,e}convert(e,n=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let s=0;s<this.length;s++)r[s]=cp(this.dataType,e,this.data[s],n);return new Q({data:r.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(y.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}else{const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),_e(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(y.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}else{const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),_e(this.cachedMin,this.sampleOffset))}get bounds(){return W(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const n=e.cachedMin??e.calcRawMin();n<this.cachedMin&&(this.cachedMin=n)}if(this.cachedMax!=null){const n=e.cachedMax??e.calcRawMax();n>this.cachedMax&&(this.cachedMax=n)}}atAlignment(e,n){const r=Number((e-this.alignment)/this.alignmentMultiple);if(r<0||r>=this.length){if(n===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,n)}at(e,n=!1){if(this.dataType.isVariable)return this.atVariable(e,n??!1);if(this.dataType.equals(y.UUID))return this.atUUID(e,n);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(n===!0)throw new Error(`[series] - no value at index ${e}`);return}return _e(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=qo(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(r==null){if(n)throw new Error(`[series] - no value at index ${e}`);return}return r}atVariable(e,n){let r=0,s=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===Br){if(e===0){s=o;break}r=o+1,e--}if(s===0&&(s=this.data.length),r>=s||e>0){if(n)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(r,s);return this.dataType.equals(y.STRING)?new TextDecoder().decode(a):fs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=nn(e);for(;n<=r;){const a=Math.floor((n+r)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?n=a+1:r=a-1}return n}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(y.FLOAT32)&&!this.dataType.equals(y.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:n,bufferUsage:r,prevBuffer:s}=this.gl;if(n==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==De){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=De}as(e){return Fo(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:xi(this.alignmentBounds.lower),upper:xi(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return W(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new mp(this);return this.dataType.equals(y.JSON)?new As(e):e}return this.dataType.equals(y.UUID)?new gp(this):new wp(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new Zi(this,e,n??this.length)}subAlignmentIterator(e,n){const r=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),s=Math.ceil(Number(n-this.alignment)/Number(this.alignmentMultiple));return new Zi(this,r,s)}subBytes(e,n){if(e>=0&&(n==null||n>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,n);return new Q({data:r,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,n,r){if(n<=0&&(r==null||r>=this.length))return this;let s;return e?s=this.data.subarray(n,r):s=this.data.slice(n,r),new Q({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new Q({data:this.buffer,dataType:this.dataType,timeRange:x.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(n=>n.toString());else{for(let n=0;n<5;n++)e+=`${this.at(n)?.toString()}`,e+=",";e+="...,";for(let n=-5;n<0;n++)e+=this.at(n)?.toString(),n<-1&&(e+=",")}return e+="])",e}}const pp=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Q?!0:Bo(t),Go=Dd(Yo,Q);class Zi{series;end;index;constructor(e,n,r){this.series=e;const s=W(0,e.length+1);this.end=$i(s,r),this.index=$i(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class mp{series;index;decoder;constructor(e){if(!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,n=this.series.data;for(;this.index<n.length&&n[this.index]!==Br;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}}class As{wrapped;static schema=i.z.record(i.z.string(),i.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Ft.decodeString(e.value,As.schema)}}}class gp{series;index;data;density;constructor(e){if(!e.dataType.equals(y.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=y.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=qo(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}class wp{series;index;constructor(e){this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class Ho{series;constructor(e=[]){if(e.length!==0){const n=e[0].dataType;for(let r=1;r<e.length;r++)if(!e[r].dataType.equals(n))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){return Fo(e,this.dataType),this}get dataType(){return this.series.length===0?y.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?x.ZERO:new x(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?W(0n,0n):W(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){const n=()=>new Error(`cannot push a ${e.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),r=e.dataType.equals(this.dataType);if(Go(e)){if(this.series.length!==0&&!r)throw n();this.series.push(e)}else{if(this.series.length!==0&&e.series.length!==0&&!r)throw n();this.series.push(...e.series)}}get length(){return this.series.reduce((e,n)=>e+n.length,0)}atAlignment(e,n){for(const r of this.series)if(wn(r.alignmentBounds,e))return r.atAlignment(e,n);if(n)throw new Error(`[series] - no value at alignment ${e}`)}at(e,n=!1){e<0&&(e=this.length+e);for(const r of this.series){if(e<r.length)return r.at(e,n);e-=r.length}if(n)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,n){return new dr(this,e,n??this.length)}subAlignmentIterator(e,n){if(e>=this.alignmentBounds.upper||n<=this.alignmentBounds.lower)return Pr;let r=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)r+=o.length;else if(wn(o.alignmentBounds,e)){r+=Math.ceil(Number(e-o.alignment)/Number(o.alignmentMultiple));break}}let s=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(n<o.alignment)break;if(n>=o.alignmentBounds.upper)s+=o.length;else if(wn(o.alignmentBounds,n)){s+=Math.ceil(Number(n-o.alignment)/Number(o.alignmentMultiple));break}}return new dr(this,r,s)}subAlignmentSpanIterator(e,n){if(e>=this.alignmentBounds.upper)return Pr;n=Math.min(n,Number(this.distance(e,this.alignmentBounds.upper)));let r=0;for(let s=0;s<this.series.length;s++){const a=this.series[s];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)r+=a.length;else if(wn(a.alignmentBounds,e)){r+=Number(e-a.alignment);break}}return new dr(this,r,r+n)}updateGLBuffer(e){this.series.forEach(n=>n.updateGLBuffer(e))}get bounds(){return uy(this.series.map(e=>e.bounds))}get byteLength(){return new $(this.series.reduce((e,n)=>e+n.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let n=0;for(const r of this.series)e.set(r.data,n),n+=r.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,n){const r=this.series.map(s=>s.alignmentBounds);return ly(r,e,n)}acquire(e){this.series.forEach(n=>n.acquire(e))}release(){this.series.forEach(e=>e.release())}distance(e,n){const r=this.series.map(s=>s.alignmentBounds);return hy(r,e,n)}parseJSON(e){if(!this.dataType.equals(y.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(n=>n.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new bp(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}}class bp{series;seriesIndex;internal;constructor(e){this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[Symbol.iterator](){return this}}class dr{series;index;end;constructor(e,n,r){this.series=e,this.end=r,this.index=n}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}const xi=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},vp=async t=>await new Promise(e=>setTimeout(e,m.fromMilliseconds(t).milliseconds));class zp{config;retries;interval;constructor(e){this.config={baseInterval:new m(e?.baseInterval??m.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??vp},this.retries=0,this.interval=new m(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:n,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(n),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const Tp=i.z.object({baseInterval:m.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),$s=Object.freeze(Object.defineProperty({__proto__:null,Breaker:zp,breakerConfigZ:Tp},Symbol.toStringTag,{value:"Module"})),Op=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Vo=i.z.string().regex(Op),Tt=i.z.number().min(0).max(255),Wo=i.z.number().min(0).max(1),Ko=i.z.tuple([Tt,Tt,Tt,Wo]),Ep=i.z.tuple([Tt,Tt,Tt]),Np=i.z.object({rgba255:Ko}),Sp=i.z.number().min(0).max(360),kp=i.z.number().min(0).max(100),Ap=i.z.number().min(0).max(100),$p=i.z.tuple([Sp,kp,Ap,Wo]),Is=i.z.union([Vo,Ep,Ko,$p,Np]),Ip=Is.transform(t=>Zs(t)),Zs=(t,e=1)=>{if(t=Is.parse(t),typeof t=="string")return Zp(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return t.rgba255},Zp=(t,e=1)=>(t=Vo.parse(t),t=xp(t),[zn(t,0),zn(t,2),zn(t,4),t.length===8?zn(t,6)/255:e]),zn=(t,e)=>parseInt(t.slice(e,e+2),16),xp=t=>t.startsWith("#")?t.slice(1):t;Zs("#000000");Zs("#ffffff");const Cp=i.z.object({key:i.z.string(),color:Is,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(Cp);const _p=i.z.object({key:i.z.string(),name:i.z.string(),color:Ip});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(_p)});const Jo=i.z.int().min(0).max(255),Xo=255,Qo=0,Rp={lower:Qo,upper:Xo+1},ec=i.z.object({name:i.z.string(),key:i.z.string()}),Gt=t=>i.z.object({subject:ec,resource:t,authority:Jo}),jp=(...t)=>e=>e.filter(n=>{let r=!1;return n.to!=null&&(r=t.includes(n.to.resource)),n.from!=null&&!r&&(r=t.includes(n.from.resource)),r}),tc=t=>i.z.object({from:Gt(t),to:i.z.null()}),nc=t=>i.z.object({from:i.z.null(),to:Gt(t)}),Mp=t=>i.z.union([tc(t),nc(t),i.z.object({from:Gt(t),to:Gt(t)})]),le=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:Xo,AUTHORITY_BOUNDS:Rp,ZERO_AUTHORITY:Qo,acquireZ:nc,authorityZ:Jo,filterTransfersByChannelKey:jp,releaseZ:tc,stateZ:Gt,subjectZ:ec,transferZ:Mp},Symbol.toStringTag,{value:"Module"})),Up=t=>{switch(typeof t){case"bigint":case"number":return t.toString();case"boolean":return t?"1":"0";case"undefined":return"";case"string":case"symbol":case"function":return Ci(t.toString());case"object":return t==null?"":Ci(JSON.stringify(t))}},Dp=/[",\n]/,Ci=t=>Dp.test(t)?`"${t.replace(/"/g,'""')}"`:t,_i=Object.freeze(Object.defineProperty({__proto__:null,formatValue:Up},Symbol.toStringTag,{value:"Module"})),Lp=(t,e)=>{let n=null;return e===0?t:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>t(...r),e)}},qr=".",Pp=(t,e,n=qr)=>{const r=t.split(n);return r.map((s,a)=>{const o=e(s,a,r);return o==null?null:typeof o=="string"?o:o.join(n)}).filter(s=>s!=null).join(n)},Bp=(t,e)=>{if(!Array.isArray(t))return t[e];const n=t[e];if(n!=null||t.length==0)return n;const r=t[0];if(typeof r=="object"&&"key"in r)return t.find(s=>s.key===e)},qp=((t,e,n={optional:!1})=>{const{optional:r,getter:s=Bp}=n;if(e==="")return t;const a=e.split(qr);if(a.length===1){const c=s(t,a[0]);if(c===void 0){if(r)return null;throw new Error(`Path ${e} does not exist. ${a[0]} is undefined`)}return c}const o=(c,l)=>{if(l>=a.length)return c;for(let u=a.length-l;u>=1;u--){const h=a.slice(l,l+u).join(qr),d=s(c,h);if(d!==void 0){if(l+u===a.length)return d;if(d===null){if(r)return null;throw new Error(`Path ${e} does not exist. ${h} is null`)}return o(d,l+u)}}if(r)return null;throw new Error(`Path ${e} does not exist. ${a[l]} is undefined`)};return o(t,0)}),Fp=t=>Object.getOwnPropertySymbols(globalThis).includes(t),Yp=(t,e)=>{const n=Symbol.for(t);if(!Fp(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},rc="sy_x_error",Gp=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),sn=t=>class Pt extends Error{static discriminator=rc;discriminator=Pt.discriminator;static TYPE=t;type=Pt.TYPE;static matches=Gp(t);matches=Pt.matches;constructor(n,r){super(n,r),this.name=Pt.TYPE}static sub(n){return sn(`${t}.${n}`)}},sc=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==rc)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},bt="unknown",Fr="nil";class Hp{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Fr,data:""};if(sc(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:bt,data:e.message};if(typeof e=="string")return{type:bt,data:e};try{return{type:bt,data:JSON.stringify(e)}}catch{return{type:bt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Fr)return null;if(e.type===bt)return new Yr(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new Yr(e.data)}}const xs=Yp("synnax-error-registry",()=>new Hp),Vp=({encode:t,decode:e})=>xs().register({encode:t,decode:e}),Wp=t=>xs().encode(t),Kp=t=>t==null?null:xs().decode(t);class Yr extends sn("unknown"){}const Jp=i.z.object({type:i.z.string(),data:i.z.string()});class Xp extends sn("canceled"){}class Qp extends sn("not_implemented"){}const je=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Xp,NONE:Fr,NotImplemented:Qp,UNKNOWN:bt,Unknown:Yr,createTyped:sn,decode:Kp,encode:Wp,isTyped:sc,payloadZ:Jp,register:Vp},Symbol.toStringTag,{value:"Module"})),em=i.object({jsonrpc:i.literal("2.0"),method:i.string(),params:i.any().optional(),id:i.union([i.string(),i.number(),i.null()]).optional()}),ic=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()])}),tm=ic.extend({result:i.json()}),nm=ic.extend({error:i.object({code:i.number().int(),message:i.string().optional(),data:i.json().optional()})}),rm=i.union([tm,nm]);i.union([em,rm]);i.z.object({key:i.z.string(),value:i.z.string()});const ac=i.uuid(),oc=i.object({key:ac,name:i.string().min(1),color:i.string()}),cc=Object.freeze(Object.defineProperty({__proto__:null,keyZ:ac,labelZ:oc},Symbol.toStringTag,{value:"Module"})),Gr=i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/),sm=(t,e)=>{const n=t.split("."),r=e.split("."),s=Math.max(n.length,r.length);for(let a=0;a<s;a++){const o=n[a],c=r[a];if(o===void 0)return Ze;if(c===void 0)return xe;const l=/^\d+$/.test(o),u=/^\d+$/.test(c);if(l&&!u)return Ze;if(!l&&u)return xe;if(l&&u){const h=parseInt(o),d=parseInt(c);if(h<d)return Ze;if(h>d)return xe}else{if(o<c)return Ze;if(o>c)return xe}}return ht},an=((t,e,n={})=>{n.checkMajor??=!0,n.checkMinor??=!0,n.checkPatch??=!0;const r=Gr.parse(t),s=Gr.parse(e),[a,o]=r.split("-"),[c,l]=s.split("-"),[u,h,d]=a.split(".").map(Number),[f,O,S]=c.split(".").map(Number);if(n.checkMajor){if(u<f)return Ze;if(u>f)return xe}if(n.checkMinor){if(h<O)return Ze;if(h>O)return xe}if(n.checkPatch){if(d<S)return Ze;if(d>S)return xe}return o===void 0&&l===void 0?ht:o===void 0?xe:l===void 0?Ze:sm(o,l)}),im=(t,e,n={})=>uo(an(t,e,n)),uc=(t,e,n={})=>co(an(t,e,n)),am=(t,e,n={})=>oo(an(t,e,n)),om=({name:t,migrate:e})=>n=>{try{const r=e(n);return console.log(`${t} migrated: ${n.version} -> ${r.version}`),r}catch(r){throw console.log(`${t} failed to migrate from ${n.version}`),console.error(r),r}},cm=({name:t,migrations:e,targetSchema:n,defaultVersion:r,def:s})=>{const a=Object.keys(e).sort(an).pop();if(a==null)return u=>{if(u.version??=r,u.version!==s.version)return console.log(`${t} version ${u.version} is newer than latest version of ${s.version}.
12
+ `).buffer):this.dataType.usesBigInt&&typeof b=="number"?this._data=new this.dataType.Array(f.map(N=>BigInt(Math.round(N)))).buffer:!this.dataType.usesBigInt&&typeof b=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=u,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??x.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:n,...r}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const s=new new p(n).Array(e),a=new te({data:s.buffer,dataType:n,...r});return a.writePos=0,a}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===qe)return 0;const n=this.byteCapacity.valueOf()-this.writePos,r=e.subBytes(0,n);return this.writeToUnderlyingData(r),this.writePos+=r.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=r.length,this.calculateCachedLength()),r.length}writeFixed(e){if(this.writePos===qe)return 0;const n=this.capacity-this.writePos,r=e.sub(0,n);return this.writeToUnderlyingData(r),this.cachedLength=void 0,this.maybeRecomputeMinMax(r),this.writePos+=r.length,r.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===qe?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
13
+ `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(p.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(Wt.decodeString(n)))}get byteCapacity(){return new I(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===qe?this.byteCapacity:this.dataType.isVariable?new I(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===qe?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const n=[0];return this.data.forEach((r,s)=>{r===ts&&(e++,n.push(s+1))}),this._cachedIndexes=n,this.cachedLength=e,e}convert(e,n=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let s=0;s<this.length;s++)r[s]=My(this.dataType,e,this.data[s],n);return new te({data:r.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(p.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}else{const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),je(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(p.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}else{const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),je(this.cachedMin,this.sampleOffset))}get bounds(){return K(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const n=e.cachedMin??e.calcRawMin();n<this.cachedMin&&(this.cachedMin=n)}if(this.cachedMax!=null){const n=e.cachedMax??e.calcRawMax();n>this.cachedMax&&(this.cachedMax=n)}}atAlignment(e,n){const r=Number((e-this.alignment)/this.alignmentMultiple);if(r<0||r>=this.length){if(n===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,n)}at(e,n=!1){if(this.dataType.isVariable)return this.atVariable(e,n??!1);if(this.dataType.equals(p.UUID))return this.atUUID(e,n);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(n===!0)throw new Error(`[series] - no value at index ${e}`);return}return je(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=ic(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(r==null){if(n)throw new Error(`[series] - no value at index ${e}`);return}return r}atVariable(e,n){let r=0,s=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===ts){if(e===0){s=o;break}r=o+1,e--}if(s===0&&(s=this.data.length),r>=s||e>0){if(n)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(r,s);return this.dataType.equals(p.STRING)?new TextDecoder().decode(a):Es(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=un(e);for(;n<=r;){const a=Math.floor((n+r)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?n=a+1:r=a-1}return n}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(p.FLOAT32)&&!this.dataType.equals(p.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:n,bufferUsage:r,prevBuffer:s}=this.gl;if(n==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==qe){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=qe}as(e){return ac(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Vi(this.alignmentBounds.lower),upper:Vi(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return K(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new qy(this);return this.dataType.equals(p.JSON)?new Ds(e):e}return this.dataType.equals(p.UUID)?new Fy(this):new Yy(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new Hi(this,e,n??this.length)}subAlignmentIterator(e,n){const r=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),s=Math.ceil(Number(n-this.alignment)/Number(this.alignmentMultiple));return new Hi(this,r,s)}subBytes(e,n){if(e>=0&&(n==null||n>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,n);return new te({data:r,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,n,r){if(n<=0&&(r==null||r>=this.length))return this;let s;return e?s=this.data.subarray(n,r):s=this.data.slice(n,r),new te({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new te({data:this.buffer,dataType:this.dataType,timeRange:x.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(n=>n.toString());else{for(let n=0;n<5;n++)e+=`${this.at(n)?.toString()}`,e+=",";e+="...,";for(let n=-5;n<0;n++)e+=this.at(n)?.toString(),n<-1&&(e+=",")}return e+="])",e}}const By=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof te?!0:sc(t),cc=hp(oc,te);class Hi{series;end;index;constructor(e,n,r){this.series=e;const s=K(0,e.length+1);this.end=Bi(s,r),this.index=Bi(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class qy{series;index;decoder;constructor(e){if(!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,n=this.series.data;for(;this.index<n.length&&n[this.index]!==ts;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}}class Ds{wrapped;static schema=i.z.record(i.z.string(),i.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Wt.decodeString(e.value,Ds.schema)}}}class Fy{series;index;data;density;constructor(e){if(!e.dataType.equals(p.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=p.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=ic(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}class Yy{series;index;constructor(e){this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class uc{series;constructor(e=[]){if(e.length!==0){const n=e[0].dataType;for(let r=1;r<e.length;r++)if(!e[r].dataType.equals(n))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){return ac(e,this.dataType),this}get dataType(){return this.series.length===0?p.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?x.ZERO:new x(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?K(0n,0n):K(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){const n=()=>new Error(`cannot push a ${e.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),r=e.dataType.equals(this.dataType);if(cc(e)){if(this.series.length!==0&&!r)throw n();this.series.push(e)}else{if(this.series.length!==0&&e.series.length!==0&&!r)throw n();this.series.push(...e.series)}}get length(){return this.series.reduce((e,n)=>e+n.length,0)}atAlignment(e,n){for(const r of this.series)if(Nn(r.alignmentBounds,e))return r.atAlignment(e,n);if(n)throw new Error(`[series] - no value at alignment ${e}`)}at(e,n=!1){e<0&&(e=this.length+e);for(const r of this.series){if(e<r.length)return r.at(e,n);e-=r.length}if(n)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,n){return new $r(this,e,n??this.length)}subAlignmentIterator(e,n){if(e>=this.alignmentBounds.upper||n<=this.alignmentBounds.lower)return es;let r=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)r+=o.length;else if(Nn(o.alignmentBounds,e)){r+=Math.ceil(Number(e-o.alignment)/Number(o.alignmentMultiple));break}}let s=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(n<o.alignment)break;if(n>=o.alignmentBounds.upper)s+=o.length;else if(Nn(o.alignmentBounds,n)){s+=Math.ceil(Number(n-o.alignment)/Number(o.alignmentMultiple));break}}return new $r(this,r,s)}subAlignmentSpanIterator(e,n){if(e>=this.alignmentBounds.upper)return es;n=Math.min(n,Number(this.distance(e,this.alignmentBounds.upper)));let r=0;for(let s=0;s<this.series.length;s++){const a=this.series[s];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)r+=a.length;else if(Nn(a.alignmentBounds,e)){r+=Number(e-a.alignment);break}}return new $r(this,r,r+n)}updateGLBuffer(e){this.series.forEach(n=>n.updateGLBuffer(e))}get bounds(){return Rp(this.series.map(e=>e.bounds))}get byteLength(){return new I(this.series.reduce((e,n)=>e+n.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let n=0;for(const r of this.series)e.set(r.data,n),n+=r.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,n){const r=this.series.map(s=>s.alignmentBounds);return jp(r,e,n)}acquire(e){this.series.forEach(n=>n.acquire(e))}release(){this.series.forEach(e=>e.release())}distance(e,n){const r=this.series.map(s=>s.alignmentBounds);return Up(r,e,n)}parseJSON(e){if(!this.dataType.equals(p.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(n=>n.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new Hy(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}}class Hy{series;seriesIndex;internal;constructor(e){this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[Symbol.iterator](){return this}}class $r{series;index;end;constructor(e,n,r){this.series=e,this.end=r,this.index=n}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}const Vi=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},Vy=async t=>await new Promise(e=>setTimeout(e,w.fromMilliseconds(t).milliseconds));class Gy{config;retries;interval;constructor(e){this.config={baseInterval:new w(e?.baseInterval??w.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Vy},this.retries=0,this.interval=new w(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:n,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(n),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const Wy=i.z.object({baseInterval:w.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),Bs=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Gy,breakerConfigZ:Wy},Symbol.toStringTag,{value:"Module"})),Jy=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Un=i.z.string().regex(Jy),Ue=i.z.number().min(0).max(255),qs=i.z.number().min(0).max(1),Kn=i.z.tuple([Ue,Ue,Ue,qs]),Ky=i.z.tuple([Ue,Ue,Ue]),Xy=i.z.object({rgba255:Kn}),Qy=i.z.object({r:Ue,g:Ue,b:Ue,a:qs}),em=i.z.number().min(0).max(360),tm=i.z.number().min(0).max(100),nm=i.z.number().min(0).max(100),lc=i.z.tuple([em,tm,nm,qs]),Xn=i.z.union([Un,Ky,Kn,lc,Xy,Qy]),hn=Xn.transform(t=>P(t)),rm=t=>hn.safeParse(t).success,sm=t=>Kn.safeParse(t).success,im=(t=>{if(t==null)return;const e=hn.safeParse(t);if(e.success)return fc(e.data);if(typeof t=="string")return t;throw e.error}),P=(t,e=1)=>{if(t=Xn.parse(t),typeof t=="string")return Mn(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return"a"in t&&"r"in t?[t.r,t.g,t.b,t.a]:t.rgba255},hc=(t,e)=>{if(t==null||e==null)return t==e;const n=P(t),r=P(e);return n.every((s,a)=>s===r[a])},am=(t=>{if(t==null)return;const[e,n,r,s]=P(t),a=Math.round(s*255);return`#${An(e)}${An(n)}${An(r)}${a===255?"":An(a)}`}),fc=t=>{const[e,n,r,s]=P(t);return`rgba(${e}, ${n}, ${r}, ${s})`},om=t=>`rgb(${dc(t)})`,dc=t=>{const[e,n,r]=P(t);return`${e}, ${n}, ${r}`},cm=t=>[...Fs(t),Vt(t)],Fs=t=>[Ft(t)/255,Yt(t)/255,Ht(t)/255],Ft=t=>P(t)[0],Yt=t=>P(t)[1],Ht=t=>P(t)[2],Vt=t=>P(t)[3],um=t=>hc(Ys,t),lm=t=>bm(P(t)),hm=(t,e)=>{const[n,r,s]=P(t);if(e>100)throw new Error(`Color opacity must be between 0 and 100, got ${e}`);return e>1&&(e/=100),[n,r,s,e]},Kt=t=>{const[e,n,r]=Fs(t).map(s=>s<=.03928?s/12.92:((s+.055)/1.055)**2.4);return Number((.2126*e+.7152*n+.0722*r).toFixed(3))},fm=t=>{const[e,n,r]=Fs(t);return 1-(Math.max(e,n,r)-Math.min(e,n,r))},ns=(t,e)=>{const n=P(t),r=P(e),s=Kt(n),a=Kt(r);return(Math.max(s,a)+.5)/(Math.min(s,a)+.5)},dm=(t,...e)=>{if(e.length===0)throw new Error("[Color.pickByContrast] - must provide at least one color");const n=P(t),[r]=e.sort((s,a)=>ns(n,a)-ns(n,s));return P(r)},pm=t=>Kt(t)<.5,ym=t=>Kt(t)>.5,Mn=(t,e=1)=>(t=Un.parse(t),t=mm(t),[In(t,0),In(t,2),In(t,4),t.length===8?In(t,6)/255:e]),Ys=[0,0,0,0],An=t=>Math.floor(t).toString(16).padStart(2,"0"),In=(t,e)=>parseInt(t.slice(e,e+2),16),mm=t=>t.startsWith("#")?t.slice(1):t,Gi={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",blue:"#0000ff",yellow:"#ffff00",cyan:"#00ffff",magenta:"#ff00ff",silver:"#c0c0c0",gray:"#808080",grey:"#808080",maroon:"#800000",olive:"#808000",lime:"#00ff00",aqua:"#00ffff",teal:"#008080",navy:"#000080",fuchsia:"#ff00ff",purple:"#800080",orange:"#ffa500",brown:"#a52a2a",tan:"#d2b48c",gold:"#ffd700",indigo:"#4b0082",violet:"#ee82ee",pink:"#ffc0cb",coral:"#ff7f50",salmon:"#fa8072",khaki:"#f0e68c",crimson:"#dc143c",transparent:"transparent"},gm=t=>{if(!t)return;const e=t.trim().toLowerCase();if(!(e==="transparent"||e==="none")){if(e.startsWith("#")){if(e.length===4){const n=e[1],r=e[2],s=e[3],a=`#${n}${n}${r}${r}${s}${s}`;if(Un.safeParse(a).success)return Mn(a)}return(e.length===7||e.length===9)&&Un.safeParse(e).success?Mn(e):void 0}if(e.startsWith("rgb")){const n=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(n){const[,r,s,a,o]=n;return[parseInt(r),parseInt(s),parseInt(a),o?parseFloat(o):1]}}if(Gi[e])return Mn(Gi[e])}},wm=t=>{t=lc.parse(t);let[e,n,r]=t;const s=t[3];e/=360,n/=100,r/=100;let a,o,c;if(n===0)a=o=c=r;else{const u=r<.5?r*(1+n):r+n-r*n,l=2*r-u;a=kr(l,u,e+1/3),o=kr(l,u,e),c=kr(l,u,e-1/3)}return[Math.round(a*255),Math.round(o*255),Math.round(c*255),s]},kr=(t,e,n)=>(n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t),bm=t=>{t=Kn.parse(t);let[e,n,r]=t;const s=t[3];e/=255,n/=255,r/=255;const a=Math.max(e,n,r),o=Math.min(e,n,r);let c,u,l=(a+o)/2;if(a===o)c=u=0;else{const h=a-o;u=l>.5?h/(2-a-o):h/(a+o),a===e?c=(n-r)/h+(n<r?6:0):a===n?c=(r-e)/h+2:c=(e-n)/h+4,c/=6}return c*=360,u*=100,l*=100,[Math.round(c),Math.round(u),Math.round(l),s]},vm=P("#000000"),zm=P("#ffffff"),pc=i.z.object({key:i.z.string(),color:Xn,position:i.z.number(),switched:i.z.boolean().optional()}),Tm=i.z.array(pc),Om=(t,e)=>{if(t.length===0)return Ys;if(t=t.slice().sort((n,r)=>n.position-r.position),e<=t[0].position)return P(t[0].color);if(e>=t[t.length-1].position)return P(t[t.length-1].color);for(let n=0;n<t.length-1;n++){const r=t[n],s=t[n+1];if(e<r.position||e>s.position)continue;if(e===r.position)return P(r.color);if(e===s.position)return P(s.color);const a=(e-r.position)/(s.position-r.position),o=P(r.color),c=P(s.color),u=Math.round(Ft(o)+a*(Ft(c)-Ft(o))),l=Math.round(Yt(o)+a*(Yt(c)-Yt(o))),h=Math.round(Ht(o)+a*(Ht(c)-Ht(o))),d=Vt(o)+a*(Vt(c)-Vt(o));return P([u,l,h,d])}return P(t[t.length-1].color)},Sm=i.z.object({key:i.z.string(),name:i.z.string(),color:hn}),Em=i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(Sm)}),yc=Object.freeze(Object.defineProperty({__proto__:null,BLACK:vm,WHITE:zm,ZERO:Ys,aValue:Vt,bValue:Ht,colorZ:hn,construct:P,contrast:ns,crudeZ:Xn,cssString:im,equals:hc,fromCSS:gm,fromGradient:Om,fromHSLA:wm,gValue:Yt,gradientZ:Tm,grayness:fm,hex:am,hsla:lm,isColor:sm,isCrude:rm,isDark:pm,isLight:ym,isZero:um,luminance:Kt,paletteZ:Em,pickByContrast:dm,rValue:Ft,rgbCSS:om,rgbString:dc,rgba1:cm,rgbaCSS:fc,setAlpha:hm,stopZ:pc},Symbol.toStringTag,{value:"Module"})),mc=i.z.int().min(0).max(255),gc=255,wc=0,Nm={lower:wc,upper:gc+1},bc=i.z.object({name:i.z.string(),key:i.z.string()}),Xt=t=>i.z.object({subject:bc,resource:t,authority:mc}),$m=(...t)=>e=>e.filter(n=>{let r=!1;return n.to!=null&&(r=t.includes(n.to.resource)),n.from!=null&&!r&&(r=t.includes(n.from.resource)),r}),vc=t=>i.z.object({from:Xt(t),to:i.z.null()}),zc=t=>i.z.object({from:i.z.null(),to:Xt(t)}),km=t=>i.z.union([vc(t),zc(t),i.z.object({from:Xt(t),to:Xt(t)})]),pe=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:gc,AUTHORITY_BOUNDS:Nm,ZERO_AUTHORITY:wc,acquireZ:zc,authorityZ:mc,filterTransfersByChannelKey:$m,releaseZ:vc,stateZ:Xt,subjectZ:bc,transferZ:km},Symbol.toStringTag,{value:"Module"})),Am=t=>{switch(typeof t){case"bigint":case"number":return t.toString();case"boolean":return t?"1":"0";case"undefined":return"";case"string":case"symbol":case"function":return Wi(t.toString());case"object":return t==null?"":Wi(JSON.stringify(t))}},Im=/[",\n]/,Wi=t=>Im.test(t)?`"${t.replace(/"/g,'""')}"`:t,Ji=Object.freeze(Object.defineProperty({__proto__:null,formatValue:Am},Symbol.toStringTag,{value:"Module"})),Zm=(t,e)=>{let n=null;return e===0?t:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>t(...r),e)}},rs=".",xm=(t,e,n=rs)=>{const r=t.split(n);return r.map((s,a)=>{const o=e(s,a,r);return o==null?null:typeof o=="string"?o:o.join(n)}).filter(s=>s!=null).join(n)},Cm=(t,e)=>{if(!Array.isArray(t))return t[e];const n=t[e];if(n!=null||t.length==0)return n;const r=t[0];if(typeof r=="object"&&"key"in r)return t.find(s=>s.key===e)},_m=((t,e,n={optional:!1})=>{const{optional:r,getter:s=Cm}=n;if(e==="")return t;const a=e.split(rs);if(a.length===1){const c=s(t,a[0]);if(c===void 0){if(r)return null;throw new Error(`Path ${e} does not exist. ${a[0]} is undefined`)}return c}const o=(c,u)=>{if(u>=a.length)return c;for(let l=a.length-u;l>=1;l--){const h=a.slice(u,u+l).join(rs),d=s(c,h);if(d!==void 0){if(u+l===a.length)return d;if(d===null){if(r)return null;throw new Error(`Path ${e} does not exist. ${h} is null`)}return o(d,u+l)}}if(r)return null;throw new Error(`Path ${e} does not exist. ${a[u]} is undefined`)};return o(t,0)}),Mm=t=>Object.getOwnPropertySymbols(globalThis).includes(t),Rm=(t,e)=>{const n=Symbol.for(t);if(!Mm(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},Tc="sy_x_error",jm=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),fn=t=>class Dt extends Error{static discriminator=Tc;discriminator=Dt.discriminator;static TYPE=t;type=Dt.TYPE;static matches=jm(t);matches=Dt.matches;constructor(n,r){super(n,r),this.name=Dt.TYPE}static sub(n){return fn(`${t}.${n}`)}},Oc=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Tc)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Tt="unknown",ss="nil";class Um{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:ss,data:""};if(Oc(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:Tt,data:e.message};if(typeof e=="string")return{type:Tt,data:e};try{return{type:Tt,data:JSON.stringify(e)}}catch{return{type:Tt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===ss)return null;if(e.type===Tt)return new is(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new is(e.data)}}const Hs=Rm("synnax-error-registry",()=>new Um),Pm=({encode:t,decode:e})=>Hs().register({encode:t,decode:e}),Lm=t=>Hs().encode(t),Dm=t=>t==null?null:Hs().decode(t);class is extends fn("unknown"){}const Bm=i.z.object({type:i.z.string(),data:i.z.string()});class qm extends fn("canceled"){}class Fm extends fn("not_implemented"){}const Le=Object.freeze(Object.defineProperty({__proto__:null,Canceled:qm,NONE:ss,NotImplemented:Fm,UNKNOWN:Tt,Unknown:is,createTyped:fn,decode:Dm,encode:Lm,isTyped:Oc,payloadZ:Bm,register:Pm},Symbol.toStringTag,{value:"Module"}));i.z.string().regex(/^(?:$|(?:\/(?:[^~/]|~0|~1)*)+)$/,"must be a valid JSON pointer (RFC 6901)");i.z.union([i.z.string(),i.z.number(),i.z.boolean(),i.z.null()]);i.z.enum(["string","number","boolean","null"]);i.z.object({key:i.z.string(),value:i.z.string()});const Sc=i.uuid(),Ec=i.object({key:Sc,name:i.string().min(1),color:hn}),Nc=Object.freeze(Object.defineProperty({__proto__:null,keyZ:Sc,labelZ:Ec},Symbol.toStringTag,{value:"Module"})),as=i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/),Ym=(t,e)=>{const n=t.split("."),r=e.split("."),s=Math.max(n.length,r.length);for(let a=0;a<s;a++){const o=n[a],c=r[a];if(o===void 0)return Ce;if(c===void 0)return _e;const u=/^\d+$/.test(o),l=/^\d+$/.test(c);if(u&&!l)return Ce;if(!u&&l)return _e;if(u&&l){const h=parseInt(o),d=parseInt(c);if(h<d)return Ce;if(h>d)return _e}else{if(o<c)return Ce;if(o>c)return _e}}return pt},dn=((t,e,n={})=>{n.checkMajor??=!0,n.checkMinor??=!0,n.checkPatch??=!0;const r=as.parse(t),s=as.parse(e),[a,o]=r.split("-"),[c,u]=s.split("-"),[l,h,d]=a.split(".").map(Number),[f,b,N]=c.split(".").map(Number);if(n.checkMajor){if(l<f)return Ce;if(l>f)return _e}if(n.checkMinor){if(h<b)return Ce;if(h>b)return _e}if(n.checkPatch){if(d<N)return Ce;if(d>N)return _e}return o===void 0&&u===void 0?pt:o===void 0?_e:u===void 0?Ce:Ym(o,u)}),Hm=(t,e,n={})=>ko(dn(t,e,n)),$c=(t,e,n={})=>$o(dn(t,e,n)),Vm=(t,e,n={})=>No(dn(t,e,n)),Gm=({name:t,migrate:e})=>n=>{try{const r=e(n);return console.log(`${t} migrated: ${n.version} -> ${r.version}`),r}catch(r){throw console.log(`${t} failed to migrate from ${n.version}`),console.error(r),r}},Wm=({name:t,migrations:e,targetSchema:n,defaultVersion:r,def:s})=>{const a=Object.keys(e).sort(dn).pop();if(a==null)return l=>{if(l.version??=r,l.version!==s.version)return console.log(`${t} version ${l.version} is newer than latest version of ${s.version}.
14
14
  Returning default instead.
15
- `),s;try{return n!=null?n.parse(u):u}catch(h){return console.log(`${t} failed to parse default. Exiting with default`),console.error(h),s}};const o=Object.keys(e).length;let c=!1;const l=u=>{try{if(o===0||uc(u.version,a))return console.log(c?`${t} ${u.version} now up to date`:`${t} version ${u.version} is up to date with target version ${s.version}`),u;const h=u.version,d=e[h],f=d(u);return c=!0,l(f)}catch(h){return console.log(`${t} failed to migrate from ${u.version} to ${a}`),console.error(h),s}};return u=>{try{if(u.version==null)if(r!=null)console.log(`${t} version is null. Setting version to default of ${r}`),u.version=r;else return console.log(`${t} version is null and no default version set. Exiting with default`),s;return l(u)}catch(h){return console.log(`${t} failed to parse final result. Exiting with default`),console.error(h),s}}},Ri=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:an,createMigration:om,migrator:cm,semVerNewer:uc,semVerOlder:am,semVerZ:Gr,versionsEqual:im},Symbol.toStringTag,{value:"Module"})),um=["standard","scientific","engineering"];i.z.enum(um);class lm{handlers;transform;closer;constructor(e,n){this.transform=e,this.handlers=n??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let n=e;if(this.transform!=null){const[r,s]=this.transform(e);if(!s)return;n=r}this.handlers.forEach((r,s)=>s(n))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}}class hm{handlers;constructor(e){this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((n,r)=>r(e))}}const fm=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:hm,Observer:lm},Symbol.toStringTag,{value:"Module"})),lc=i.z.union([i.z.string(),i.z.number()]),dm=i.z.record(lc,i.z.unknown()),Cs=t=>Object.entries(t),ym=(t,e)=>Object.fromEntries(Cs(t).map(([n,r])=>[n,e(r,n)])),pm=t=>Object.fromEntries(Cs(t).filter(([e,n])=>n!==void 0)),mm=(t,...e)=>{const n={...t};for(const r of e)delete n[r];return n},fe=Object.freeze(Object.defineProperty({__proto__:null,entries:Cs,keyZ:lc,map:ym,omit:mm,purgeUndefined:pm,unknownZ:dm},Symbol.toStringTag,{value:"Module"})),hc=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",gm=hc(),fc=["macOS","Windows","Linux"],wm=["macos","windows","linux"],bm={macos:"macOS",windows:"Windows",linux:"Linux"},vm=i.z.enum(fc).or(i.z.enum(wm).transform(t=>bm[t])),zm=()=>{if(typeof window>"u")return;const t=window.navigator.userAgent.toLowerCase();if(t.includes("mac"))return"macOS";if(t.includes("win"))return"Windows";if(t.includes("linux"))return"Linux"};let yr;const Tm=((t={})=>{const{force:e,default:n}=t;return e??yr??(yr=zm(),yr??n)}),Om=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:fc,RUNTIME:gm,detect:hc,getOS:Tm,osZ:vm},Symbol.toStringTag,{value:"Module"})),dc=i.z.enum(["success","info","warning","error","loading","disabled"]),Em=t=>i.z.object({key:i.z.string(),name:i.z.string().default(""),variant:dc,message:i.z.string(),description:i.z.string().optional(),time:w.z,labels:Ka(oc).optional(),details:t??i.z.unknown().optional()}),Nm=i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)}),Sm=(t,e)=>{if(!(t instanceof Error))throw t;return yc({variant:"error",message:e??t.message,description:e!=null?t.message:void 0,details:{stack:t.stack??"",error:t}})},yc=t=>({key:ys(),time:w.now(),name:"",...t}),km=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?t:void 0:e===t?t:void 0},Am=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?void 0:t:e===t?void 0:t},We=Object.freeze(Object.defineProperty({__proto__:null,create:yc,exceptionDetailsSchema:Nm,fromException:Sm,keepVariants:km,removeVariants:Am,statusZ:Em,variantZ:dc},Symbol.toStringTag,{value:"Module"})),$m=(t,e)=>{if(!e.has(t))return t;let n=t,r=1,s=t;for(;e.has(s);){const a=s.match(Im);a?(n=s.slice(0,a.index).trim(),r=parseInt(a[1])+1):(n=s,r=1),s=`${n} (${r})`}return s},Im=/\((\d+)\)$/,Zm=(t,e="")=>{if(typeof t=="string")return t;const n=t.length;return n===0?e:n===1?t[0]:n===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[n-1]}`},xm=t=>{const e=t.split(" "),n=new Set,r=e.map(o=>o.charAt(0).toLowerCase()).join("");n.add(r.replace(/-/g,"_")),n.add(r.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const s=/\d+/g;t.match(s)&&e.forEach((o,c)=>{if(s.test(o)){const l=e.map((u,h)=>h!==c?u.charAt(0).toLowerCase():u).join("");n.add(l.replace(/-/g,"_")),n.add(l.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const a=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return n.add(a.join("").replace(/-/g,"_")),n.add(a.join("_").replace(/-/g,"_")),Array.from(n).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},Cm=(t,e)=>t.startsWith(e)?t.slice(e.length):t,Hr=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:xm,deduplicateFileName:$m,naturalLanguageJoin:Zm,trimPrefix:Cm},Symbol.toStringTag,{value:"Module"})),_m=(...t)=>t.map(pc).join(""),pc=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Rm=t=>t.endsWith("/")?t.slice(0,-1):t;class Ot{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=pc(s)}replace(e){return new Ot({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Ot({...this,pathPrefix:_m(this.path,e)})}toString(){return Rm(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new Ot({host:"unknown",port:0})}const jm=t=>t.nullable().transform(e=>e===null?void 0:e).optional(),Mm=i.z.int().min(0).max(mo),Um=t=>i.array(t).or(t.transform(e=>[e])),Dm=t=>t._zod.def.output,mc=t=>Pp(t,(e,n,r)=>{const s=n===r.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(r[n+1]));return a&&(e="element"),s||o?e:[e,"shape"]}),ji=(t,e)=>{if(t==null)return null;const n=t[e];return n==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:n},Lm=((t,e,n)=>e===""?t:qp(ji(t,"shape"),mc(e),{...n,getter:ji})),Ne=Object.freeze(Object.defineProperty({__proto__:null,functionOutput:Dm,getFieldSchema:Lm,getFieldSchemaPath:mc,nullToUndefined:jm,toArray:Um,uint12:Mm},Symbol.toStringTag,{value:"Module"})),_s=i.z.enum(["create","delete","retrieve","update"]);class ke extends je.createTyped("sy"){}class H extends ke.sub("validation"){}class Ht extends H.sub("path"){path;error;static encodedSchema=i.z.object({path:i.z.string().array(),error:je.payloadZ});constructor(e,n){const r=N.toArray(e);super(`${r.join(".")}: ${n.message}`),this.path=r.flatMap(s=>s.split(".")),this.error=n}static decode(e){const n=Ht.encodedSchema.parse(JSON.parse(e.data));return new Ht(n.path,je.decode(n.error))}}class kt extends ke.sub("auth"){}class Vr extends kt.sub("invalid_token"){}class Wr extends kt.sub("expired_token"){}class _k extends kt.sub("access_denied"){}class st extends ke.sub("unexpected"){constructor(e){super(`
15
+ `),s;try{return n!=null?n.parse(l):l}catch(h){return console.log(`${t} failed to parse default. Exiting with default`),console.error(h),s}};const o=Object.keys(e).length;let c=!1;const u=l=>{try{if(o===0||$c(l.version,a))return console.log(c?`${t} ${l.version} now up to date`:`${t} version ${l.version} is up to date with target version ${s.version}`),l;const h=l.version,d=e[h],f=d(l);return c=!0,u(f)}catch(h){return console.log(`${t} failed to migrate from ${l.version} to ${a}`),console.error(h),s}};return l=>{try{if(l.version==null)if(r!=null)console.log(`${t} version is null. Setting version to default of ${r}`),l.version=r;else return console.log(`${t} version is null and no default version set. Exiting with default`),s;return u(l)}catch(h){return console.log(`${t} failed to parse final result. Exiting with default`),console.error(h),s}}},Ki=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:dn,createMigration:Gm,migrator:Wm,semVerNewer:$c,semVerOlder:Vm,semVerZ:as,versionsEqual:Hm},Symbol.toStringTag,{value:"Module"})),Jm=["standard","scientific","engineering"];i.z.enum(Jm);class Km{handlers;transform;closer;constructor(e,n){this.transform=e,this.handlers=n??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let n=e;if(this.transform!=null){const[r,s]=this.transform(e);if(!s)return;n=r}this.handlers.forEach((r,s)=>s(n))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}}class Xm{handlers;constructor(e){this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((n,r)=>r(e))}}const Qm=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:Xm,Observer:Km},Symbol.toStringTag,{value:"Module"})),kc=i.z.union([i.z.string(),i.z.number()]),Ac=i.z.record(kc,i.z.unknown()),eg=()=>i.z.union([i.z.union([i.z.null(),i.z.undefined()]).transform(()=>({})),Ac]),Vs=t=>Object.entries(t),tg=(t,e)=>Object.fromEntries(Vs(t).map(([n,r])=>[n,e(r,n)])),ng=t=>Object.fromEntries(Vs(t).filter(([e,n])=>n!==void 0)),rg=(t,...e)=>{const n={...t};for(const r of e)delete n[r];return n},oe=Object.freeze(Object.defineProperty({__proto__:null,entries:Vs,keyZ:kc,map:tg,nullishToEmpty:eg,omit:rg,purgeUndefined:ng,unknownZ:Ac},Symbol.toStringTag,{value:"Module"})),Ic=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",sg=Ic(),Zc=["macOS","Windows","Linux"],ig=["macos","windows","linux"],ag={macos:"macOS",windows:"Windows",linux:"Linux"},og=i.z.enum(Zc).or(i.z.enum(ig).transform(t=>ag[t])),cg=()=>{if(typeof window>"u")return;const t=window.navigator.userAgent.toLowerCase();if(t.includes("mac"))return"macOS";if(t.includes("win"))return"Windows";if(t.includes("linux"))return"Linux"};let Ar;const ug=((t={})=>{const{force:e,default:n}=t;return e??Ar??(Ar=cg(),Ar??n)}),lg=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:Zc,RUNTIME:sg,detect:Ic,getOS:ug,osZ:og},Symbol.toStringTag,{value:"Module"})),xc=i.z.enum(["success","info","warning","error","loading","disabled"]),hg=t=>i.z.object({key:i.z.string(),name:i.z.string().default(""),variant:xc,message:i.z.string(),description:i.z.string().optional(),time:m.z,labels:po(Ec).optional(),details:t??i.z.unknown().optional()}),fg=i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)}),dg=(t,e)=>{if(!(t instanceof Error))throw t;return Cc({variant:"error",message:e??t.message,description:e!=null?t.message:void 0,details:{stack:t.stack??"",error:t}})},Cc=t=>({key:$s(),time:m.now(),name:"",...t}),pg=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?t:void 0:e===t?t:void 0},yg=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?void 0:t:e===t?void 0:t},mg={includeTimestamp:!1,includeName:!0},gg=(t,e={})=>{const n={...mg,...e},r=[];let s=t.variant.toUpperCase();if(n.includeName&&t.name.length>0&&(s+=` [${t.name}]`),s+=`: ${t.message}`,n.includeTimestamp&&(s+=` (${t.time.toString("dateTime","local")})`),r.push(s),t.description!=null){let a;try{const o=JSON.parse(t.description);a=`Description:
16
+ ${JSON.stringify(o,null,2)}`}catch{a=`Description: ${t.description}`}r.push(a)}if("details"in t&&bo(t.details)){const a=t.details;"stack"in a&&r.push(`Stack Trace:
17
+ ${String(a.stack)}`);const o=Object.fromEntries(Object.entries(a).filter(([c])=>c!=="stack"&&c!=="error"));Object.keys(o).length>0&&r.push(`Details:
18
+ ${JSON.stringify(o,null,2)}`)}return r.join(`
19
+
20
+ `)},Qe=Object.freeze(Object.defineProperty({__proto__:null,create:Cc,exceptionDetailsSchema:fg,fromException:dg,keepVariants:pg,removeVariants:yg,statusZ:hg,toString:gg,variantZ:xc},Symbol.toStringTag,{value:"Module"})),wg=(t,e)=>{if(!e.has(t))return t;let n=t,r=1,s=t;for(;e.has(s);){const a=s.match(bg);a?(n=s.slice(0,a.index).trim(),r=parseInt(a[1])+1):(n=s,r=1),s=`${n} (${r})`}return s},bg=/\((\d+)\)$/,vg=(t,e="")=>{if(typeof t=="string")return t;const n=t.length;return n===0?e:n===1?t[0]:n===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[n-1]}`},zg=t=>{const e=t.split(" "),n=new Set,r=e.map(o=>o.charAt(0).toLowerCase()).join("");n.add(r.replace(/-/g,"_")),n.add(r.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const s=/\d+/g;t.match(s)&&e.forEach((o,c)=>{if(s.test(o)){const u=e.map((l,h)=>h!==c?l.charAt(0).toLowerCase():l).join("");n.add(u.replace(/-/g,"_")),n.add(u.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const a=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return n.add(a.join("").replace(/-/g,"_")),n.add(a.join("_").replace(/-/g,"_")),Array.from(n).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},Tg=(t,e)=>t.startsWith(e)?t.slice(e.length):t,os=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:zg,deduplicateFileName:wg,naturalLanguageJoin:vg,trimPrefix:Tg},Symbol.toStringTag,{value:"Module"})),Og=(...t)=>t.map(_c).join(""),_c=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Sg=t=>t.endsWith("/")?t.slice(0,-1):t;class St{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=_c(s)}replace(e){return new St({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new St({...this,pathPrefix:Og(this.path,e)})}toString(){return Sg(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new St({host:"unknown",port:0})}const Eg=t=>t.nullable().transform(e=>e===null?void 0:e).optional(),Ng=i.z.int().min(0).max(_o),$g=t=>i.array(t).or(t.transform(e=>[e])),kg=t=>t._zod.def.output,Mc=t=>xm(t,(e,n,r)=>{const s=n===r.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(r[n+1]));return a&&(e="element"),s||o?e:[e,"shape"]}),Xi=(t,e)=>{if(t==null)return null;const n=t[e];return n==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:n},Ag=((t,e,n)=>e===""?t:_m(Xi(t,"shape"),Mc(e),{...n,getter:Xi})),be=Object.freeze(Object.defineProperty({__proto__:null,functionOutput:kg,getFieldSchema:Ag,getFieldSchemaPath:Mc,nullToUndefined:Eg,toArray:$g,uint12:Ng},Symbol.toStringTag,{value:"Module"})),Gs=i.z.enum(["create","delete","retrieve","update"]);class Ae extends Le.createTyped("sy"){}class W extends Ae.sub("validation"){}class Qt extends W.sub("path"){path;error;static encodedSchema=i.z.object({path:i.z.string().array(),error:Le.payloadZ});constructor(e,n){const r=E.toArray(e);super(`${r.join(".")}: ${n.message}`),this.path=r.flatMap(s=>s.split(".")),this.error=n}static decode(e){const n=Qt.encodedSchema.parse(JSON.parse(e.data));return new Qt(n.path,Le.decode(n.error))}}class kt extends Ae.sub("auth"){}class cs extends kt.sub("invalid_token"){}class us extends kt.sub("expired_token"){}class B$ extends kt.sub("access_denied"){}class ct extends Ae.sub("unexpected"){constructor(e){super(`
16
21
  Unexpected error encountered:
17
22
 
18
23
  ${e}
19
24
 
20
25
  Please report this to the Synnax team.
21
- `)}}class He extends ke.sub("query"){}class Vt extends He.sub("not_found"){}class Wt extends He.sub("multiple_results"){}class Kr extends ke.sub("route"){path;constructor(e,n){super(e),this.path=n}}class Jr extends ke.sub("control"){}class Mi extends Jr.sub("unauthorized"){}class Pm extends ke.sub("disconnected"){constructor(e="Operation failed because no Core is connected."){super(e)}}class Bm extends ke.sub("contiguity"){}const qm=t=>t.type.startsWith(ke.TYPE)?t.type.startsWith(H.TYPE)?t.type===Ht.TYPE?Ht.decode(t):new H(t.data):t.type.startsWith(kt.TYPE)?t.type.startsWith(Vr.TYPE)?new Vr(t.data):t.type.startsWith(Wr.TYPE)?new Wr(t.data):new kt(t.data):t.type.startsWith(st.TYPE)?new st(t.data):t.type.startsWith(He.TYPE)?t.type.startsWith(Vt.TYPE)?new Vt(t.data):t.type.startsWith(Wt.TYPE)?new Wt(t.data):new He(t.data):t.type.startsWith(Jr.TYPE)?t.type.startsWith(Mi.TYPE)?new Mi(t.data):new Jr(t.data):t.type.startsWith(Kr.TYPE)?new Kr(t.data,t.data):new st(t.data):null,Fm=()=>{throw new je.NotImplemented};je.register({encode:Fm,decode:qm});const Ym=async(t,e)=>{const[n,r]=await e(t);return r==null?[n,r]:r instanceof Ge?[n,new Ge({message:`Cannot reach Core at ${r.url.host}:${r.url.port}`,url:r.url})]:[n,r]},Dn=i.z.enum(["label","log","builtin","cluster","channel","node","group","range","framer","range-alias","user","workspace","schematic","lineplot","rack","device","task","policy","role","table","arc","schematic_symbol","status","view"]),gc=i.z.string().transform(t=>{const[e,n]=t.split(":");return{type:Dn.parse(e),key:n??""}}),L=i.z.object({type:Dn,key:i.z.string()}).or(gc),Gm={type:"builtin",key:"root"},V=t=>{const e=n=>({type:t,key:kd.isZero(n)?"":n.toString()});return(n=>Array.isArray(n)?n.map(e):e(n))},Se=(t=>(typeof t=="string"&&(t=gc.parse(t)),Array.isArray(t)?t.map(e=>Se(e)):`${t.type}:${t.key}`)),Hm=(t,e)=>t.type===e.type&&t.key===e.key,wc=t=>{const e=N.toArray(t);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:n})=>n):e.map(n=>L.parse(n))},bc=i.z.object({id:L,name:i.z.string(),data:fe.unknownZ.optional().nullable()}).transform(t=>({key:Se(t.id),...t})),Vm=t=>t==="to"?"from":"to",Wm=i.z.object({from:L,type:i.z.string(),to:L}).or(i.z.string().transform(t=>{const[e,n,r]=t.split("->");return{from:L.parse(e),type:n,to:L.parse(r)}})),Km=t=>`${Se(t.from)}->${t.type}->${Se(t.to)}`,Jm="parent",Xm=(t,e)=>!(e.type!=null&&e.type!==t.type||e.from?.type!=null&&e.from.type!==t.from.type||e.to?.type!=null&&e.to.type!==t.to.type||e.from?.key!=null&&e.from.key!==t.from.key||e.to?.key!=null&&e.to.key!==t.to.key),on=i.z.uuid(),vc=i.z.string(),Ln=i.z.object({key:on,name:vc}),Qm=V("group"),eg="sy_group_set",tg="sy_group_delete",ng=i.object({group:Ln}),rg=i.object({parent:L,key:on.optional(),name:i.string()}),sg=i.object({key:on,name:i.string()}),ig=i.object({keys:i.array(on)});let zc=class{client;constructor(e){this.client=e}async create(e){return(await z(this.client,"/ontology/create-group",e,rg,ng)).group}async rename(e,n){await z(this.client,"/ontology/rename-group",{key:e,name:n},sg,i.object({}))}async delete(e){await z(this.client,"/ontology/delete-group",{keys:N.toArray(e)},ig,i.object({}))}};const ag=Object.freeze(Object.defineProperty({__proto__:null,Client:zc,DELETE_CHANNEL_NAME:tg,SET_CHANNEL_NAME:eg,groupZ:Ln,keyZ:on,nameZ:vc,ontologyID:Qm},Symbol.toStringTag,{value:"Module"})),Ui=i.z.object({id:L,children:L.array()}),og=i.z.object({from:L,to:L,children:L.array()}),pr=i.z.object({});let cg=class{client;constructor(e){this.client=e}async addChildren(e,...n){await z(this.client,"/ontology/add-children",{id:e,children:n},Ui,pr)}async removeChildren(e,...n){await z(this.client,"/ontology/remove-children",{id:e,children:n},Ui,pr)}async moveChildren(e,n,...r){await z(this.client,"/ontology/move-children",{from:e,to:n,children:r},og,pr)}};const ug=i.z.object({ids:L.array().optional(),children:i.z.boolean().optional(),parents:i.z.boolean().optional(),excludeFieldData:i.z.boolean().optional(),types:Dn.array().optional(),searchTerm:i.z.string().optional(),limit:i.z.int().optional(),offset:i.z.int().optional()}),lg=i.z.object({resources:bc.array()});let Tc=class{type="ontology";groups;client;writer;framer;constructor(e,n){this.client=e,this.writer=new cg(e),this.groups=new zc(e),this.framer=n}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object"&&!("key"in e))return this.execRetrieve(e);const r=wc(e),s=await this.execRetrieve({ids:r,...n});if(Array.isArray(e))return s;if(s.length===0)throw new He(`No resource found with ID ${Hr.naturalLanguageJoin(r.map(a=>Se(a)))}`);return s[0]}async retrieveChildren(e,n){return await this.execRetrieve({ids:N.toArray(e),children:!0,...n})}async retrieveParents(e,n){return await this.execRetrieve({ids:N.toArray(e),parents:!0,...n})}async addChildren(e,...n){return await this.writer.addChildren(e,...n)}async removeChildren(e,...n){return await this.writer.removeChildren(e,...n)}async moveChildren(e,n,...r){return await this.writer.moveChildren(e,n,...r)}async execRetrieve(e){const{resources:n}=await z(this.client,"/ontology/retrieve",e,ug,lg);return n}};const hg="sy_ontology_resource_set",fg="sy_ontology_resource_delete",dg="sy_ontology_relationship_set",yg="sy_ontology_relationship_delete",pg=Object.freeze(Object.defineProperty({__proto__:null,Client:Tc,PARENT_OF_RELATIONSHIP_TYPE:Jm,RELATIONSHIP_DELETE_CHANNEL_NAME:yg,RELATIONSHIP_SET_CHANNEL_NAME:dg,RESOURCE_DELETE_CHANNEL_NAME:fg,RESOURCE_SET_CHANNEL_NAME:hg,ROOT_ID:Gm,createIDFactory:V,idToString:Se,idZ:L,idsEqual:Hm,matchRelationship:Xm,oppositeRelationshipDirection:Vm,parseIDs:wc,relationshipToString:Km,relationshipZ:Wm,resourceTypeZ:Dn,resourceZ:bc},Symbol.toStringTag,{value:"Module"})),Zt=i.z.uuid(),Rs=i.z.object({key:Zt,name:i.z.string(),objects:N.nullableZ(L),actions:N.nullableZ(_s),internal:i.z.boolean()}),js=i.z.object({key:Zt.optional(),name:i.z.string(),objects:Ne.toArray(L),actions:Ne.toArray(_s)}),Ms=V("policy"),mg=Ms(""),gg="sy_policy_set",wg="sy_policy_delete",bg=i.z.object({keys:Zt.array().optional(),subjects:L.array().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),internal:i.z.boolean().optional()}),vg=i.z.object({key:Zt}).transform(({key:t})=>({keys:[t]})),zg=i.z.union([i.z.object({for:L}).transform(({for:t})=>({subjects:[t]})),i.z.object({for:L.array()}).transform(({for:t})=>({subjects:t})),bg]),Tg=i.z.union([vg,zg]),Og=i.z.object({policies:N.nullableZ(Rs)}),Eg=js.transform(t=>({policies:[t]})),Oc=js.array().transform(t=>({policies:t})),Ec=i.z.union([Eg,Oc]),Ng=i.z.object({policies:Rs.array()}),Sg=i.z.object({keys:Zt.array()}),kg=i.z.object({});let Nc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await z(this.client,"/access/policy/create",e,Ec,Ng);return n?r.policies:r.policies[0]}async retrieve(e){const n="key"in e,r=await z(this.client,"/access/policy/retrieve",e,Tg,Og);return n?r.policies[0]:r.policies}async delete(e){await z(this.client,"/access/policy/delete",{keys:N.toArray(e)},Sg,kg)}};const Ag=Object.freeze(Object.defineProperty({__proto__:null,Client:Nc,DELETE_CHANNEL_NAME:wg,SET_CHANNEL_NAME:gg,TYPE_ONTOLOGY_ID:mg,createArgsZ:Ec,keyZ:Zt,multipleCreateArgsZ:Oc,newZ:js,ontologyID:Ms,policyZ:Rs},Symbol.toStringTag,{value:"Module"})),Ve=i.z.uuid(),Pn=i.z.object({key:Ve,name:i.z.string(),description:i.z.string().optional(),internal:i.z.boolean().optional()}),Us=Pn.partial({key:!0}),Ds=V("role"),$g=Ds(""),Ae=i.z.uuid(),cn=i.z.object({key:Ae,username:i.z.string().min(1,"Username is required"),firstName:i.z.string().default(""),lastName:i.z.string().default(""),rootUser:i.z.boolean().default(!1)}),Sc=cn.omit({rootUser:!0}).partial({key:!0,firstName:!0,lastName:!0}).extend({password:i.z.string().min(1)}),Ig=i.z.object({keys:Ae.array().optional(),usernames:i.z.string().array().optional()}),Zg=i.z.object({key:Ae}).transform(({key:t})=>({keys:[t]})),xg=i.z.object({username:i.z.string()}).transform(({username:t})=>({usernames:[t]})),Cg=i.z.object({usernames:i.z.string().array()}).transform(({usernames:t})=>({usernames:t})),_g=i.z.union([Zg,xg,Cg,Ig]),Rg=i.z.object({users:N.nullableZ(cn)}),jg=i.z.object({users:Sc.array()}),Mg=i.z.object({users:cn.array()}),Ug=i.z.object({key:Ae,username:i.z.string().min(1)}),Dg=i.z.object({}),Lg=i.z.object({key:Ae,firstName:i.z.string().optional(),lastName:i.z.string().optional()}),Pg=i.z.object({}),Bg=i.z.object({keys:Ae.array()}),qg=i.z.object({}),Fg="sy_user_set",Yg="sy_user_delete";let kc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await z(this.client,"/user/create",{users:N.toArray(e)},jg,Mg);return n?r.users:r.users[0]}async changeUsername(e,n){await z(this.client,"/user/change-username",{key:e,username:n},Ug,Dg)}async retrieve(e){const n="key"in e||"username"in e,r=await z(this.client,"/user/retrieve",e,_g,Rg);if(!n)return r.users;if(r.users.length===0){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new Vt(`No user with ${s} found`)}if(r.users.length>1){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new Wt(`Multiple users found with ${s}`)}return r.users[0]}async rename(e,n,r){await z(this.client,"/user/rename",{key:e,firstName:n,lastName:r},Lg,Pg)}async delete(e){await z(this.client,"/user/delete",{keys:N.toArray(e)},Bg,qg)}};const Ac=V("user"),Gg=Ac(""),Hg=Object.freeze(Object.defineProperty({__proto__:null,Client:kc,DELETE_CHANNEL_NAME:Yg,SET_CHANNEL_NAME:Fg,TYPE_ONTOLOGY_ID:Gg,keyZ:Ae,newZ:Sc,ontologyID:Ac,userZ:cn},Symbol.toStringTag,{value:"Module"})),Vg=i.z.object({keys:Ve.array().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),internal:i.z.boolean().optional()}),Wg=i.z.object({key:Ve}).transform(({key:t})=>({keys:[t]})),Kg=Us.transform(t=>({roles:[t]})),$c=Us.array().transform(t=>({roles:t})),Ic=i.z.union([Kg,$c]),Jg=i.z.object({roles:Pn.array()}),Xg=i.z.object({roles:N.nullableZ(Pn)}),Zc=i.z.union([Wg,Vg]),Qg=i.z.object({}),ew=Ve.transform(t=>({keys:[t]})).or(Ve.array().transform(t=>({keys:t}))),tw=i.z.object({user:Ae,role:Ve}),nw=i.z.object({}),rw=i.z.object({user:Ae,role:Ve}),sw=i.z.object({}),iw="sy_role_set",aw="sy_role_delete";let xc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await z(this.client,"/access/role/create",e,Ic,Jg);return n?r.roles:r.roles[0]}async retrieve(e){const n="key"in e,r=await z(this.client,"/access/role/retrieve",e,Zc,Xg);return n?r.roles[0]:r.roles}async delete(e){await z(this.client,"/access/role/delete",e,ew,Qg)}async assign(e){await z(this.client,"/access/role/assign",e,tw,nw)}async unassign(e){await z(this.client,"/access/role/unassign",e,rw,sw)}};const ow=Object.freeze(Object.defineProperty({__proto__:null,Client:xc,DELETE_CHANNEL_NAME:aw,SET_CHANNEL_NAME:iw,TYPE_ONTOLOGY_ID:$g,createArgsZ:Ic,keyZ:Ve,multipleCreateArgsZ:$c,newZ:Us,ontologyID:Ds,retrieveArgsZ:Zc,roleZ:Pn},Symbol.toStringTag,{value:"Module"}));let Cc=class{policies;roles;constructor(e){this.policies=new Nc(e),this.roles=new xc(e)}};const cw=(t,e)=>{const n=N.toArray(t.objects),{action:r}=t;for(const s of n){let a=!1;for(const o of e)if(o.actions.includes(r)){for(const l of o.objects)if(l.key===""){if(l.type===s.type){a=!0;break}}else if(l.type===s.type&&l.key===s.key){a=!0;break}if(a)break}if(!a)return!1}return!0},uw=Object.freeze(Object.defineProperty({__proto__:null,Client:Cc,actionZ:_s,allowRequest:cw,policy:Ag,role:ow},Symbol.toStringTag,{value:"Module"}));function g(t,e,n){function r(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:o,traits:new Set},enumerable:!1}),c._zod.traits.has(t))return;c._zod.traits.add(t),e(c,l);const u=o.prototype,h=Object.keys(u);for(let d=0;d<h.length;d++){const f=h[d];f in c||(c[f]=u[f].bind(c))}}const s=n?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:t});function o(c){var l;const u=n?.Parent?new a:this;r(u,c),(l=u._zod).deferred??(l.deferred=[]);for(const h of u._zod.deferred)h();return u}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}class Et extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class _c extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Rc={};function ot(t){return Rc}function lw(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function Xr(t,e){return typeof e=="bigint"?e.toString():e}function Ls(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Ps(t){return t==null}function Bs(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function hw(t,e){const n=(t.toString().split(".")[1]||"").length,r=e.toString();let s=(r.split(".")[1]||"").length;if(s===0&&/\d?e-\d?/.test(r)){const l=r.match(/\d?e-(\d?)/);l?.[1]&&(s=Number.parseInt(l[1]))}const a=n>s?n:s,o=Number.parseInt(t.toFixed(a).replace(".","")),c=Number.parseInt(e.toFixed(a).replace(".",""));return o%c/10**a}const Di=Symbol("evaluating");function M(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Di)return r===void 0&&(r=Di,r=n()),r},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function ft(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function dt(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function Li(t){return JSON.stringify(t)}function fw(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const jc="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function $n(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const dw=Ls(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Kt(t){if($n(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const n=e.prototype;return!($n(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Mc(t){return Kt(t)?{...t}:Array.isArray(t)?[...t]:t}const yw=new Set(["string","number","symbol"]);function At(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ke(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function k(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function pw(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const mw={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function gw(t,e){const n=t._zod.def,r=dt(t._zod.def,{get shape(){const s={};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=n.shape[a])}return ft(this,"shape",s),s},checks:[]});return Ke(t,r)}function ww(t,e){const n=t._zod.def,r=dt(t._zod.def,{get shape(){const s={...t._zod.def.shape};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return ft(this,"shape",s),s},checks:[]});return Ke(t,r)}function bw(t,e){if(!Kt(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const s=dt(t._zod.def,{get shape(){const a={...t._zod.def.shape,...e};return ft(this,"shape",a),a},checks:[]});return Ke(t,s)}function vw(t,e){if(!Kt(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...t._zod.def,get shape(){const r={...t._zod.def.shape,...e};return ft(this,"shape",r),r},checks:t._zod.def.checks};return Ke(t,n)}function zw(t,e){const n=dt(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return ft(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return Ke(t,n)}function Tw(t,e,n){const r=dt(e._zod.def,{get shape(){const s=e._zod.def.shape,a={...s};if(n)for(const o in n){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(a[o]=t?new t({type:"optional",innerType:s[o]}):s[o])}else for(const o in s)a[o]=t?new t({type:"optional",innerType:s[o]}):s[o];return ft(this,"shape",a),a},checks:[]});return Ke(e,r)}function Ow(t,e,n){const r=dt(e._zod.def,{get shape(){const s=e._zod.def.shape,a={...s};if(n)for(const o in n){if(!(o in a))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(a[o]=new t({type:"nonoptional",innerType:s[o]}))}else for(const o in s)a[o]=new t({type:"nonoptional",innerType:s[o]});return ft(this,"shape",a),a},checks:[]});return Ke(e,r)}function vt(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Uc(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Tn(t){return typeof t=="string"?t:t?.message}function ct(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const s=Tn(t.inst?._zod.def?.error?.(t))??Tn(e?.error?.(t))??Tn(n.customError?.(t))??Tn(n.localeError?.(t))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function qs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Jt(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const Dc=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Xr,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Lc=g("$ZodError",Dc),Pc=g("$ZodError",Dc,{Parent:Error});function Ew(t,e=n=>n.message){const n={},r=[];for(const s of t.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}function Nw(t,e=n=>n.message){const n={_errors:[]},r=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(o=>r({issues:o}));else if(a.code==="invalid_key")r({issues:a.issues});else if(a.code==="invalid_element")r({issues:a.issues});else if(a.path.length===0)n._errors.push(e(a));else{let o=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(e(a))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return r(t),n}const Fs=t=>(e,n,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},o=e._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Et;if(o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>ct(l,a,ot())));throw jc(c,s?.callee),c}return o.value},Ys=t=>async(e,n,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>ct(l,a,ot())));throw jc(c,s?.callee),c}return o.value},Bn=t=>(e,n,r)=>{const s=r?{...r,async:!1}:{async:!1},a=e._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new Et;return a.issues.length?{success:!1,error:new(t??Lc)(a.issues.map(o=>ct(o,s,ot())))}:{success:!0,data:a.value}},Sw=Bn(Pc),qn=t=>async(e,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=e._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(o=>ct(o,s,ot())))}:{success:!0,data:a.value}},kw=qn(Pc),Aw=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Fs(t)(e,n,s)},$w=t=>(e,n,r)=>Fs(t)(e,n,r),Iw=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ys(t)(e,n,s)},Zw=t=>async(e,n,r)=>Ys(t)(e,n,r),xw=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Bn(t)(e,n,s)},Cw=t=>(e,n,r)=>Bn(t)(e,n,r),_w=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return qn(t)(e,n,s)},Rw=t=>async(e,n,r)=>qn(t)(e,n,r),jw=/^[cC][^\s-]{8,}$/,Mw=/^[0-9a-z]+$/,Uw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Dw=/^[0-9a-vA-V]{20}$/,Lw=/^[A-Za-z0-9]{27}$/,Pw=/^[a-zA-Z0-9_-]{21}$/,Bw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,qw=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Pi=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Fw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Yw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Gw(){return new RegExp(Yw,"u")}const Hw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Vw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ww=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Kw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Jw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Bc=/^[A-Za-z0-9_-]*$/,Xw=/^\+(?:[0-9]){6,14}[0-9]$/,qc="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Qw=new RegExp(`^${qc}$`);function Fc(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function eb(t){return new RegExp(`^${Fc(t)}$`)}function tb(t){const e=Fc({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${qc}T(?:${r})$`)}const nb=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},rb=/^-?\d+$/,sb=/^-?\d+(?:\.\d+)?/,ib=/^(?:true|false)$/i,ab=/^[^A-Z]*$/,ob=/^[^a-z]*$/,re=g("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Yc={number:"number",bigint:"bigint",object:"date"},Gc=g("$ZodCheckLessThan",(t,e)=>{re.init(t,e);const n=Yc[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<a&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Hc=g("$ZodCheckGreaterThan",(t,e)=>{re.init(t,e);const n=Yc[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),cb=g("$ZodCheckMultipleOf",(t,e)=>{re.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):hw(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),ub=g("$ZodCheckNumberFormat",(t,e)=>{re.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[s,a]=mw[e.format];t._zod.onattach.push(o=>{const c=o._zod.bag;c.format=e.format,c.minimum=s,c.maximum=a,n&&(c.pattern=rb)}),t._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}c<s&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),c>a&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inst:t})}}),lb=g("$ZodCheckMaxLength",(t,e)=>{var n;re.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ps(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const s=r.value;if(s.length<=e.maximum)return;const o=qs(s);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),hb=g("$ZodCheckMinLength",(t,e)=>{var n;re.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ps(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const s=r.value;if(s.length>=e.minimum)return;const o=qs(s);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),fb=g("$ZodCheckLengthEquals",(t,e)=>{var n;re.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ps(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{const s=r.value,a=s.length;if(a===e.length)return;const o=qs(s),c=a>e.length;r.issues.push({origin:o,...c?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Fn=g("$ZodCheckStringFormat",(t,e)=>{var n,r;re.init(t,e),t._zod.onattach.push(s=>{const a=s._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),db=g("$ZodCheckRegex",(t,e)=>{Fn.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),yb=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ab),Fn.init(t,e)}),pb=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=ob),Fn.init(t,e)}),mb=g("$ZodCheckIncludes",(t,e)=>{re.init(t,e);const n=At(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),gb=g("$ZodCheckStartsWith",(t,e)=>{re.init(t,e);const n=new RegExp(`^${At(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),wb=g("$ZodCheckEndsWith",(t,e)=>{re.init(t,e);const n=new RegExp(`.*${At(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),bb=g("$ZodCheckOverwrite",(t,e)=>{re.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class vb{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
26
+ `)}}class Ke extends Ae.sub("query"){}class en extends Ke.sub("not_found"){}class tn extends Ke.sub("multiple_results"){}class ls extends Ae.sub("route"){path;constructor(e,n){super(e),this.path=n}}class hs extends Ae.sub("control"){}class Qi extends hs.sub("unauthorized"){}class Ig extends Ae.sub("disconnected"){constructor(e="Operation failed because no Core is connected."){super(e)}}class Zg extends Ae.sub("contiguity"){}const xg=t=>t.type.startsWith(Ae.TYPE)?t.type.startsWith(W.TYPE)?t.type===Qt.TYPE?Qt.decode(t):new W(t.data):t.type.startsWith(kt.TYPE)?t.type.startsWith(cs.TYPE)?new cs(t.data):t.type.startsWith(us.TYPE)?new us(t.data):new kt(t.data):t.type.startsWith(ct.TYPE)?new ct(t.data):t.type.startsWith(Ke.TYPE)?t.type.startsWith(en.TYPE)?new en(t.data):t.type.startsWith(tn.TYPE)?new tn(t.data):new Ke(t.data):t.type.startsWith(hs.TYPE)?t.type.startsWith(Qi.TYPE)?new Qi(t.data):new hs(t.data):t.type.startsWith(ls.TYPE)?new ls(t.data,t.data):new ct(t.data):null,Cg=()=>{throw new Le.NotImplemented};Le.register({encode:Cg,decode:xg});const _g=async(t,e)=>{const[n,r]=await e(t);return r==null?[n,r]:r instanceof Je?[n,new Je({message:`Cannot reach Core at ${r.url.host}:${r.url.port}`,url:r.url})]:[n,r]},Qn=i.z.enum(["label","log","builtin","cluster","channel","node","group","range","framer","range-alias","user","workspace","schematic","lineplot","rack","device","task","policy","role","table","arc","schematic_symbol","status","view"]),Rc=i.z.string().transform(t=>{const[e,n]=t.split(":");return{type:Qn.parse(e),key:n??""}}),B=i.z.object({type:Qn,key:i.z.string()}).or(Rc),Mg={type:"builtin",key:"root"},J=t=>{const e=n=>({type:t,key:Qd.isZero(n)?"":n.toString()});return(n=>Array.isArray(n)?n.map(e):e(n))},ke=(t=>(typeof t=="string"&&(t=Rc.parse(t)),Array.isArray(t)?t.map(e=>ke(e)):`${t.type}:${t.key}`)),Rg=(t,e)=>t.type===e.type&&t.key===e.key,jc=t=>{const e=E.toArray(t);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:n})=>n):e.map(n=>B.parse(n))},Uc=i.z.object({id:B,name:i.z.string(),data:oe.unknownZ.optional().nullable()}).transform(t=>({key:ke(t.id),...t})),jg=t=>t==="to"?"from":"to",Ug=i.z.object({from:B,type:i.z.string(),to:B}).or(i.z.string().transform(t=>{const[e,n,r]=t.split("->");return{from:B.parse(e),type:n,to:B.parse(r)}})),Pg=t=>`${ke(t.from)}->${t.type}->${ke(t.to)}`,Lg="parent",Dg=(t,e)=>!(e.type!=null&&e.type!==t.type||e.from?.type!=null&&e.from.type!==t.from.type||e.to?.type!=null&&e.to.type!==t.to.type||e.from?.key!=null&&e.from.key!==t.from.key||e.to?.key!=null&&e.to.key!==t.to.key),ea=i.z.object({id:B,children:B.array()}),Bg=i.z.object({from:B,to:B,children:B.array()}),Ir=i.z.object({});let qg=class{client;constructor(e){this.client=e}async addChildren(e,...n){await T(this.client,"/ontology/add-children",{id:e,children:n},ea,Ir)}async removeChildren(e,...n){await T(this.client,"/ontology/remove-children",{id:e,children:n},ea,Ir)}async moveChildren(e,n,...r){await T(this.client,"/ontology/move-children",{from:e,to:n,children:r},Bg,Ir)}};const Fg=i.z.object({ids:B.array().optional(),children:i.z.boolean().optional(),parents:i.z.boolean().optional(),excludeFieldData:i.z.boolean().optional(),types:Qn.array().optional(),searchTerm:i.z.string().optional(),limit:i.z.int().optional(),offset:i.z.int().optional()}),Yg=i.z.object({resources:Uc.array()});let Pc=class{type="ontology";client;writer;constructor(e){this.client=e,this.writer=new qg(e)}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object"&&!("key"in e))return this.execRetrieve(e);const r=jc(e),s=await this.execRetrieve({ids:r,...n});if(Array.isArray(e))return s;if(s.length===0)throw new Ke(`No resource found with ID ${os.naturalLanguageJoin(r.map(a=>ke(a)))}`);return s[0]}async retrieveChildren(e,n){return await this.execRetrieve({ids:E.toArray(e),children:!0,...n})}async retrieveParents(e,n){return await this.execRetrieve({ids:E.toArray(e),parents:!0,...n})}async addChildren(e,...n){return await this.writer.addChildren(e,...n)}async removeChildren(e,...n){return await this.writer.removeChildren(e,...n)}async moveChildren(e,n,...r){return await this.writer.moveChildren(e,n,...r)}async execRetrieve(e){const{resources:n}=await T(this.client,"/ontology/retrieve",e,Fg,Yg);return n}};const Hg="sy_ontology_resource_set",Vg="sy_ontology_resource_delete",Gg="sy_ontology_relationship_set",Wg="sy_ontology_relationship_delete",Jg=Object.freeze(Object.defineProperty({__proto__:null,Client:Pc,PARENT_OF_RELATIONSHIP_TYPE:Lg,RELATIONSHIP_DELETE_CHANNEL_NAME:Wg,RELATIONSHIP_SET_CHANNEL_NAME:Gg,RESOURCE_DELETE_CHANNEL_NAME:Vg,RESOURCE_SET_CHANNEL_NAME:Hg,ROOT_ID:Mg,createIDFactory:J,idToString:ke,idZ:B,idsEqual:Rg,matchRelationship:Dg,oppositeRelationshipDirection:jg,parseIDs:jc,relationshipToString:Pg,relationshipZ:Ug,resourceTypeZ:Qn,resourceZ:Uc},Symbol.toStringTag,{value:"Module"})),xt=i.z.uuid(),Ws=i.z.object({key:xt,name:i.z.string(),objects:E.nullableZ(B),actions:E.nullableZ(Gs),internal:i.z.boolean()}),Js=i.z.object({key:xt.optional(),name:i.z.string(),objects:be.toArray(B),actions:be.toArray(Gs)}),Ks=J("policy"),Kg=Ks(""),Xg="sy_policy_set",Qg="sy_policy_delete",ew=i.z.object({keys:xt.array().optional(),subjects:B.array().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),internal:i.z.boolean().optional()}),tw=i.z.object({key:xt}).transform(({key:t})=>({keys:[t]})),nw=i.z.union([i.z.object({for:B}).transform(({for:t})=>({subjects:[t]})),i.z.object({for:B.array()}).transform(({for:t})=>({subjects:t})),ew]),rw=i.z.union([tw,nw]),sw=i.z.object({policies:E.nullableZ(Ws)}),iw=Js.transform(t=>({policies:[t]})),Lc=Js.array().transform(t=>({policies:t})),Dc=i.z.union([iw,Lc]),aw=i.z.object({policies:Ws.array()}),ow=i.z.object({keys:xt.array()}),cw=i.z.object({});let Bc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await T(this.client,"/access/policy/create",e,Dc,aw);return n?r.policies:r.policies[0]}async retrieve(e){const n="key"in e,r=await T(this.client,"/access/policy/retrieve",e,rw,sw);return n?r.policies[0]:r.policies}async delete(e){await T(this.client,"/access/policy/delete",{keys:E.toArray(e)},ow,cw)}};const uw=Object.freeze(Object.defineProperty({__proto__:null,Client:Bc,DELETE_CHANNEL_NAME:Qg,SET_CHANNEL_NAME:Xg,TYPE_ONTOLOGY_ID:Kg,createArgsZ:Dc,keyZ:xt,multipleCreateArgsZ:Lc,newZ:Js,ontologyID:Ks,policyZ:Ws},Symbol.toStringTag,{value:"Module"})),Xe=i.z.uuid(),er=i.z.object({key:Xe,name:i.z.string(),description:i.z.string().optional(),internal:i.z.boolean().optional()}),Xs=er.partial({key:!0}),Qs=J("role"),lw=Qs(""),Ie=i.z.uuid(),pn=i.z.object({key:Ie,username:i.z.string().min(1,"Username is required"),firstName:i.z.string().default(""),lastName:i.z.string().default(""),rootUser:i.z.boolean().default(!1)}),qc=pn.omit({rootUser:!0}).partial({key:!0,firstName:!0,lastName:!0}).extend({password:i.z.string().min(1)}),hw=i.z.object({keys:Ie.array().optional(),usernames:i.z.string().array().optional()}),fw=i.z.object({key:Ie}).transform(({key:t})=>({keys:[t]})),dw=i.z.object({username:i.z.string()}).transform(({username:t})=>({usernames:[t]})),pw=i.z.object({usernames:i.z.string().array()}).transform(({usernames:t})=>({usernames:t})),yw=i.z.union([fw,dw,pw,hw]),mw=i.z.object({users:E.nullableZ(pn)}),gw=i.z.object({users:qc.array()}),ww=i.z.object({users:pn.array()}),bw=i.z.object({key:Ie,username:i.z.string().min(1)}),vw=i.z.object({}),zw=i.z.object({key:Ie,firstName:i.z.string().optional(),lastName:i.z.string().optional()}),Tw=i.z.object({}),Ow=i.z.object({keys:Ie.array()}),Sw=i.z.object({}),Ew="sy_user_set",Nw="sy_user_delete";let Fc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await T(this.client,"/user/create",{users:E.toArray(e)},gw,ww);return n?r.users:r.users[0]}async changeUsername(e,n){await T(this.client,"/user/change-username",{key:e,username:n},bw,vw)}async retrieve(e){const n="key"in e||"username"in e,r=await T(this.client,"/user/retrieve",e,yw,mw);if(!n)return r.users;if(r.users.length===0){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new en(`No user with ${s} found`)}if(r.users.length>1){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new tn(`Multiple users found with ${s}`)}return r.users[0]}async rename(e,n,r){await T(this.client,"/user/rename",{key:e,firstName:n,lastName:r},zw,Tw)}async delete(e){await T(this.client,"/user/delete",{keys:E.toArray(e)},Ow,Sw)}};const Yc=J("user"),$w=Yc(""),kw=Object.freeze(Object.defineProperty({__proto__:null,Client:Fc,DELETE_CHANNEL_NAME:Nw,SET_CHANNEL_NAME:Ew,TYPE_ONTOLOGY_ID:$w,keyZ:Ie,newZ:qc,ontologyID:Yc,userZ:pn},Symbol.toStringTag,{value:"Module"})),Aw=i.z.object({keys:Xe.array().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),internal:i.z.boolean().optional()}),Iw=i.z.object({key:Xe}).transform(({key:t})=>({keys:[t]})),Zw=Xs.transform(t=>({roles:[t]})),Hc=Xs.array().transform(t=>({roles:t})),Vc=i.z.union([Zw,Hc]),xw=i.z.object({roles:er.array()}),Cw=i.z.object({roles:E.nullableZ(er)}),Gc=i.z.union([Iw,Aw]),_w=i.z.object({}),Mw=Xe.transform(t=>({keys:[t]})).or(Xe.array().transform(t=>({keys:t}))),Rw=i.z.object({user:Ie,role:Xe}),jw=i.z.object({}),Uw=i.z.object({user:Ie,role:Xe}),Pw=i.z.object({}),Lw="sy_role_set",Dw="sy_role_delete";let Wc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await T(this.client,"/access/role/create",e,Vc,xw);return n?r.roles:r.roles[0]}async retrieve(e){const n="key"in e,r=await T(this.client,"/access/role/retrieve",e,Gc,Cw);return n?r.roles[0]:r.roles}async delete(e){await T(this.client,"/access/role/delete",e,Mw,_w)}async assign(e){await T(this.client,"/access/role/assign",e,Rw,jw)}async unassign(e){await T(this.client,"/access/role/unassign",e,Uw,Pw)}};const Bw=Object.freeze(Object.defineProperty({__proto__:null,Client:Wc,DELETE_CHANNEL_NAME:Dw,SET_CHANNEL_NAME:Lw,TYPE_ONTOLOGY_ID:lw,createArgsZ:Vc,keyZ:Xe,multipleCreateArgsZ:Hc,newZ:Xs,ontologyID:Qs,retrieveArgsZ:Gc,roleZ:er},Symbol.toStringTag,{value:"Module"}));let Jc=class{policies;roles;constructor(e){this.policies=new Bc(e),this.roles=new Wc(e)}};const qw=(t,e)=>{const n=E.toArray(t.objects),{action:r}=t;for(const s of n){let a=!1;for(const o of e)if(o.actions.includes(r)){for(const u of o.objects)if(u.key===""){if(u.type===s.type){a=!0;break}}else if(u.type===s.type&&u.key===s.key){a=!0;break}if(a)break}if(!a)return!1}return!0},Fw=Object.freeze(Object.defineProperty({__proto__:null,Client:Jc,actionZ:Gs,allowRequest:qw,policy:uw,role:Bw},Symbol.toStringTag,{value:"Module"}));function g(t,e,n){function r(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:o,traits:new Set},enumerable:!1}),c._zod.traits.has(t))return;c._zod.traits.add(t),e(c,u);const l=o.prototype,h=Object.keys(l);for(let d=0;d<h.length;d++){const f=h[d];f in c||(c[f]=l[f].bind(c))}}const s=n?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:t});function o(c){var u;const l=n?.Parent?new a:this;r(l,c),(u=l._zod).deferred??(u.deferred=[]);for(const h of l._zod.deferred)h();return l}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}class Et extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Kc extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Xc={};function ht(t){return Xc}function Qc(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function fs(t,e){return typeof e=="bigint"?e.toString():e}function ei(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function ti(t){return t==null}function ni(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Yw(t,e){const n=(t.toString().split(".")[1]||"").length,r=e.toString();let s=(r.split(".")[1]||"").length;if(s===0&&/\d?e-\d?/.test(r)){const u=r.match(/\d?e-(\d?)/);u?.[1]&&(s=Number.parseInt(u[1]))}const a=n>s?n:s,o=Number.parseInt(t.toFixed(a).replace(".","")),c=Number.parseInt(e.toFixed(a).replace(".",""));return o%c/10**a}const ta=Symbol("evaluating");function U(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==ta)return r===void 0&&(r=ta,r=n()),r},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function yt(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function et(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function na(t){return JSON.stringify(t)}function Hw(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const eu="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Pn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Vw=ei(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function nn(t){if(Pn(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const n=e.prototype;return!(Pn(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function tu(t){return nn(t)?{...t}:Array.isArray(t)?[...t]:t}const Gw=new Set(["string","number","symbol"]);function At(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tt(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function $(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Ww(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const Jw={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Kw(t,e){const n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a=et(t._zod.def,{get shape(){const o={};for(const c in e){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);e[c]&&(o[c]=n.shape[c])}return yt(this,"shape",o),o},checks:[]});return tt(t,a)}function Xw(t,e){const n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=et(t._zod.def,{get shape(){const o={...t._zod.def.shape};for(const c in e){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);e[c]&&delete o[c]}return yt(this,"shape",o),o},checks:[]});return tt(t,a)}function Qw(t,e){if(!nn(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0){const a=t._zod.def.shape;for(const o in e)if(Object.getOwnPropertyDescriptor(a,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const s=et(t._zod.def,{get shape(){const a={...t._zod.def.shape,...e};return yt(this,"shape",a),a}});return tt(t,s)}function eb(t,e){if(!nn(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n=et(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e};return yt(this,"shape",r),r}});return tt(t,n)}function tb(t,e){const n=et(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return yt(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return tt(t,n)}function nb(t,e,n){const s=e._zod.def.checks;if(s&&s.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const o=et(e._zod.def,{get shape(){const c=e._zod.def.shape,u={...c};if(n)for(const l in n){if(!(l in c))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(u[l]=t?new t({type:"optional",innerType:c[l]}):c[l])}else for(const l in c)u[l]=t?new t({type:"optional",innerType:c[l]}):c[l];return yt(this,"shape",u),u},checks:[]});return tt(e,o)}function rb(t,e,n){const r=et(e._zod.def,{get shape(){const s=e._zod.def.shape,a={...s};if(n)for(const o in n){if(!(o in a))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(a[o]=new t({type:"nonoptional",innerType:s[o]}))}else for(const o in s)a[o]=new t({type:"nonoptional",innerType:s[o]});return yt(this,"shape",a),a}});return tt(e,r)}function Ot(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function nu(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Zn(t){return typeof t=="string"?t:t?.message}function ft(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const s=Zn(t.inst?._zod.def?.error?.(t))??Zn(e?.error?.(t))??Zn(n.customError?.(t))??Zn(n.localeError?.(t))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function ri(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function rn(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const ru=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,fs,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},su=g("$ZodError",ru),iu=g("$ZodError",ru,{Parent:Error});function sb(t,e=n=>n.message){const n={},r=[];for(const s of t.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}function ib(t,e=n=>n.message){const n={_errors:[]},r=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(o=>r({issues:o}));else if(a.code==="invalid_key")r({issues:a.issues});else if(a.code==="invalid_element")r({issues:a.issues});else if(a.path.length===0)n._errors.push(e(a));else{let o=n,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(e(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return r(t),n}const si=t=>(e,n,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},o=e._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Et;if(o.issues.length){const c=new(s?.Err??t)(o.issues.map(u=>ft(u,a,ht())));throw eu(c,s?.callee),c}return o.value},ii=t=>async(e,n,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){const c=new(s?.Err??t)(o.issues.map(u=>ft(u,a,ht())));throw eu(c,s?.callee),c}return o.value},tr=t=>(e,n,r)=>{const s=r?{...r,async:!1}:{async:!1},a=e._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new Et;return a.issues.length?{success:!1,error:new(t??su)(a.issues.map(o=>ft(o,s,ht())))}:{success:!0,data:a.value}},ab=tr(iu),nr=t=>async(e,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=e._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(o=>ft(o,s,ht())))}:{success:!0,data:a.value}},ob=nr(iu),cb=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return si(t)(e,n,s)},ub=t=>(e,n,r)=>si(t)(e,n,r),lb=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ii(t)(e,n,s)},hb=t=>async(e,n,r)=>ii(t)(e,n,r),fb=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return tr(t)(e,n,s)},db=t=>(e,n,r)=>tr(t)(e,n,r),pb=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return nr(t)(e,n,s)},yb=t=>async(e,n,r)=>nr(t)(e,n,r),mb=/^[cC][^\s-]{8,}$/,gb=/^[0-9a-z]+$/,wb=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,bb=/^[0-9a-vA-V]{20}$/,vb=/^[A-Za-z0-9]{27}$/,zb=/^[a-zA-Z0-9_-]{21}$/,Tb=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ob=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ra=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Sb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Eb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Nb(){return new RegExp(Eb,"u")}const $b=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,kb=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ab=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ib=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Zb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,au=/^[A-Za-z0-9_-]*$/,xb=/^\+[1-9]\d{6,14}$/,ou="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Cb=new RegExp(`^${ou}$`);function cu(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function _b(t){return new RegExp(`^${cu(t)}$`)}function Mb(t){const e=cu({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${ou}T(?:${r})$`)}const Rb=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},jb=/^-?\d+$/,Ub=/^-?\d+(?:\.\d+)?$/,Pb=/^(?:true|false)$/i,Lb=/^[^A-Z]*$/,Db=/^[^a-z]*$/,ce=g("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),uu={number:"number",bigint:"bigint",object:"date"},lu=g("$ZodCheckLessThan",(t,e)=>{ce.init(t,e);const n=uu[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<a&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),hu=g("$ZodCheckGreaterThan",(t,e)=>{ce.init(t,e);const n=uu[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Bb=g("$ZodCheckMultipleOf",(t,e)=>{ce.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Yw(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),qb=g("$ZodCheckNumberFormat",(t,e)=>{ce.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[s,a]=Jw[e.format];t._zod.onattach.push(o=>{const c=o._zod.bag;c.format=e.format,c.minimum=s,c.maximum=a,n&&(c.pattern=jb)}),t._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort});return}}c<s&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),c>a&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inclusive:!0,inst:t,continue:!e.abort})}}),Fb=g("$ZodCheckMaxLength",(t,e)=>{var n;ce.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!ti(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const s=r.value;if(s.length<=e.maximum)return;const o=ri(s);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Yb=g("$ZodCheckMinLength",(t,e)=>{var n;ce.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!ti(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const s=r.value;if(s.length>=e.minimum)return;const o=ri(s);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Hb=g("$ZodCheckLengthEquals",(t,e)=>{var n;ce.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!ti(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{const s=r.value,a=s.length;if(a===e.length)return;const o=ri(s),c=a>e.length;r.issues.push({origin:o,...c?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),rr=g("$ZodCheckStringFormat",(t,e)=>{var n,r;ce.init(t,e),t._zod.onattach.push(s=>{const a=s._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Vb=g("$ZodCheckRegex",(t,e)=>{rr.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Gb=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Lb),rr.init(t,e)}),Wb=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Db),rr.init(t,e)}),Jb=g("$ZodCheckIncludes",(t,e)=>{ce.init(t,e);const n=At(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),Kb=g("$ZodCheckStartsWith",(t,e)=>{ce.init(t,e);const n=new RegExp(`^${At(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Xb=g("$ZodCheckEndsWith",(t,e)=>{ce.init(t,e);const n=new RegExp(`.*${At(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),Qb=g("$ZodCheckOverwrite",(t,e)=>{ce.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class ev{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
22
27
  `).filter(o=>o),s=Math.min(...r.map(o=>o.length-o.trimStart().length)),a=r.map(o=>o.slice(s)).map(o=>" ".repeat(this.indent*2)+o);for(const o of a)this.content.push(o)}compile(){const e=Function,n=this?.args,s=[...(this?.content??[""]).map(a=>` ${a}`)];return new e(...n,s.join(`
23
- `))}}const zb={major:4,minor:1,patch:13},q=g("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=zb;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const a of s._zod.onattach)a(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,c,l)=>{let u=vt(o),h;for(const d of c){if(d._zod.def.when){if(!d._zod.def.when(o))continue}else if(u)continue;const f=o.issues.length,O=d._zod.check(o);if(O instanceof Promise&&l?.async===!1)throw new Et;if(h||O instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await O,o.issues.length!==f&&(u||(u=vt(o,f)))});else{if(o.issues.length===f)continue;u||(u=vt(o,f))}}return h?h.then(()=>o):o},a=(o,c,l)=>{if(vt(o))return o.aborted=!0,o;const u=s(c,r,l);if(u instanceof Promise){if(l.async===!1)throw new Et;return u.then(h=>t._zod.parse(h,l))}return t._zod.parse(u,l)};t._zod.run=(o,c)=>{if(c.skipChecks)return t._zod.parse(o,c);if(c.direction==="backward"){const u=t._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(h=>a(h,o,c)):a(u,o,c)}const l=t._zod.parse(o,c);if(l instanceof Promise){if(c.async===!1)throw new Et;return l.then(u=>s(u,r,c))}return s(l,r,c)}}t["~standard"]={validate:s=>{try{const a=Sw(t,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return kw(t,s).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),Gs=g("$ZodString",(t,e)=>{q.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??nb(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),P=g("$ZodStringFormat",(t,e)=>{Fn.init(t,e),Gs.init(t,e)}),Tb=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=qw),P.init(t,e)}),Ob=g("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Pi(r))}else e.pattern??(e.pattern=Pi());P.init(t,e)}),Eb=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Fw),P.init(t,e)}),Nb=g("$ZodURL",(t,e)=>{P.init(t,e),t._zod.check=n=>{try{const r=n.value.trim(),s=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=s.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),Sb=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Gw()),P.init(t,e)}),kb=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Pw),P.init(t,e)}),Ab=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=jw),P.init(t,e)}),$b=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Mw),P.init(t,e)}),Ib=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Uw),P.init(t,e)}),Zb=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Dw),P.init(t,e)}),xb=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Lw),P.init(t,e)}),Cb=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=tb(e)),P.init(t,e)}),_b=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Qw),P.init(t,e)}),Rb=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=eb(e)),P.init(t,e)}),jb=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Bw),P.init(t,e)}),Mb=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Hw),P.init(t,e),t._zod.bag.format="ipv4"}),Ub=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Vw),P.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Db=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ww),P.init(t,e)}),Lb=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Kw),P.init(t,e),t._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[s,a]=r;if(!a)throw new Error;const o=Number(a);if(`${o}`!==a)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${s}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function Vc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const Pb=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Jw),P.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Vc(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Bb(t){if(!Bc.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Vc(n)}const qb=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Bc),P.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Bb(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Fb=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Xw),P.init(t,e)});function Yb(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const Gb=g("$ZodJWT",(t,e)=>{P.init(t,e),t._zod.check=n=>{Yb(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Wc=g("$ZodNumber",(t,e)=>{q.init(t,e),t._zod.pattern=t._zod.bag.pattern??sb,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;const a=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...a?{received:a}:{}}),n}}),Hb=g("$ZodNumberFormat",(t,e)=>{ub.init(t,e),Wc.init(t,e)}),Vb=g("$ZodBoolean",(t,e)=>{q.init(t,e),t._zod.pattern=ib,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const s=n.value;return typeof s=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),n}}),Wb=g("$ZodUnknown",(t,e)=>{q.init(t,e),t._zod.parse=n=>n}),Kb=g("$ZodNever",(t,e)=>{q.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Bi(t,e,n){t.issues.length&&e.issues.push(...Uc(n,t.issues)),e.value[n]=t.value}const Jb=g("$ZodArray",(t,e)=>{q.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),n;n.value=Array(s.length);const a=[];for(let o=0;o<s.length;o++){const c=s[o],l=e.element._zod.run({value:c,issues:[]},r);l instanceof Promise?a.push(l.then(u=>Bi(u,n,o))):Bi(l,n,o)}return a.length?Promise.all(a).then(()=>n):n}});function In(t,e,n,r){t.issues.length&&e.issues.push(...Uc(n,t.issues)),t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Kc(t){const e=Object.keys(t.shape);for(const r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=pw(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Jc(t,e,n,r,s,a){const o=[],c=s.keySet,l=s.catchall._zod,u=l.def.type;for(const h in e){if(c.has(h))continue;if(u==="never"){o.push(h);continue}const d=l.run({value:e[h],issues:[]},r);d instanceof Promise?t.push(d.then(f=>In(f,n,h,e))):In(d,n,h,e)}return o.length&&n.issues.push({code:"unrecognized_keys",keys:o,input:e,inst:a}),t.length?Promise.all(t).then(()=>n):n}const Xb=g("$ZodObject",(t,e)=>{if(q.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){const c=e.shape;Object.defineProperty(e,"shape",{get:()=>{const l={...c};return Object.defineProperty(e,"shape",{value:l}),l}})}const r=Ls(()=>Kc(e));M(t._zod,"propValues",()=>{const c=e.shape,l={};for(const u in c){const h=c[u]._zod;if(h.values){l[u]??(l[u]=new Set);for(const d of h.values)l[u].add(d)}}return l});const s=$n,a=e.catchall;let o;t._zod.parse=(c,l)=>{o??(o=r.value);const u=c.value;if(!s(u))return c.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),c;c.value={};const h=[],d=o.shape;for(const f of o.keys){const S=d[f]._zod.run({value:u[f],issues:[]},l);S instanceof Promise?h.push(S.then(Z=>In(Z,c,f,u))):In(S,c,f,u)}return a?Jc(h,u,c,l,r.value,t):h.length?Promise.all(h).then(()=>c):c}}),Qb=g("$ZodObjectJIT",(t,e)=>{Xb.init(t,e);const n=t._zod.parse,r=Ls(()=>Kc(e)),s=f=>{const O=new vb(["shape","payload","ctx"]),S=r.value,Z=D=>{const _=Li(D);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};O.write("const input = payload.value;");const T=Object.create(null);let E=0;for(const D of S.keys)T[D]=`key_${E++}`;O.write("const newResult = {};");for(const D of S.keys){const _=T[D],j=Li(D);O.write(`const ${_} = ${Z(D)};`),O.write(`
24
- if (${_}.issues.length) {
25
- payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
28
+ `))}}const tv={major:4,minor:3,patch:6},Y=g("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=tv;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const a of s._zod.onattach)a(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,c,u)=>{let l=Ot(o),h;for(const d of c){if(d._zod.def.when){if(!d._zod.def.when(o))continue}else if(l)continue;const f=o.issues.length,b=d._zod.check(o);if(b instanceof Promise&&u?.async===!1)throw new Et;if(h||b instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await b,o.issues.length!==f&&(l||(l=Ot(o,f)))});else{if(o.issues.length===f)continue;l||(l=Ot(o,f))}}return h?h.then(()=>o):o},a=(o,c,u)=>{if(Ot(o))return o.aborted=!0,o;const l=s(c,r,u);if(l instanceof Promise){if(u.async===!1)throw new Et;return l.then(h=>t._zod.parse(h,u))}return t._zod.parse(l,u)};t._zod.run=(o,c)=>{if(c.skipChecks)return t._zod.parse(o,c);if(c.direction==="backward"){const l=t._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return l instanceof Promise?l.then(h=>a(h,o,c)):a(l,o,c)}const u=t._zod.parse(o,c);if(u instanceof Promise){if(c.async===!1)throw new Et;return u.then(l=>s(l,r,c))}return s(u,r,c)}}U(t,"~standard",()=>({validate:s=>{try{const a=ab(t,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return ob(t,s).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),ai=g("$ZodString",(t,e)=>{Y.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Rb(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),q=g("$ZodStringFormat",(t,e)=>{rr.init(t,e),ai.init(t,e)}),nv=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Ob),q.init(t,e)}),rv=g("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=ra(r))}else e.pattern??(e.pattern=ra());q.init(t,e)}),sv=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Sb),q.init(t,e)}),iv=g("$ZodURL",(t,e)=>{q.init(t,e),t._zod.check=n=>{try{const r=n.value.trim(),s=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=s.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),av=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Nb()),q.init(t,e)}),ov=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=zb),q.init(t,e)}),cv=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=mb),q.init(t,e)}),uv=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=gb),q.init(t,e)}),lv=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=wb),q.init(t,e)}),hv=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=bb),q.init(t,e)}),fv=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=vb),q.init(t,e)}),dv=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Mb(e)),q.init(t,e)}),pv=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Cb),q.init(t,e)}),yv=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=_b(e)),q.init(t,e)}),mv=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Tb),q.init(t,e)}),gv=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=$b),q.init(t,e),t._zod.bag.format="ipv4"}),wv=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=kb),q.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),bv=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ab),q.init(t,e)}),vv=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ib),q.init(t,e),t._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[s,a]=r;if(!a)throw new Error;const o=Number(a);if(`${o}`!==a)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${s}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function fu(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const zv=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Zb),q.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{fu(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Tv(t){if(!au.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return fu(n)}const Ov=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=au),q.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Tv(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Sv=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=xb),q.init(t,e)});function Ev(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const Nv=g("$ZodJWT",(t,e)=>{q.init(t,e),t._zod.check=n=>{Ev(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),du=g("$ZodNumber",(t,e)=>{Y.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ub,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;const a=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...a?{received:a}:{}}),n}}),$v=g("$ZodNumberFormat",(t,e)=>{qb.init(t,e),du.init(t,e)}),kv=g("$ZodBoolean",(t,e)=>{Y.init(t,e),t._zod.pattern=Pb,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const s=n.value;return typeof s=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),n}}),Av=g("$ZodUnknown",(t,e)=>{Y.init(t,e),t._zod.parse=n=>n}),Iv=g("$ZodNever",(t,e)=>{Y.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function sa(t,e,n){t.issues.length&&e.issues.push(...nu(n,t.issues)),e.value[n]=t.value}const Zv=g("$ZodArray",(t,e)=>{Y.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),n;n.value=Array(s.length);const a=[];for(let o=0;o<s.length;o++){const c=s[o],u=e.element._zod.run({value:c,issues:[]},r);u instanceof Promise?a.push(u.then(l=>sa(l,n,o))):sa(u,n,o)}return a.length?Promise.all(a).then(()=>n):n}});function Ln(t,e,n,r,s){if(t.issues.length){if(s&&!(n in r))return;e.issues.push(...nu(n,t.issues))}t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function pu(t){const e=Object.keys(t.shape);for(const r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=Ww(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function yu(t,e,n,r,s,a){const o=[],c=s.keySet,u=s.catchall._zod,l=u.def.type,h=u.optout==="optional";for(const d in e){if(c.has(d))continue;if(l==="never"){o.push(d);continue}const f=u.run({value:e[d],issues:[]},r);f instanceof Promise?t.push(f.then(b=>Ln(b,n,d,e,h))):Ln(f,n,d,e,h)}return o.length&&n.issues.push({code:"unrecognized_keys",keys:o,input:e,inst:a}),t.length?Promise.all(t).then(()=>n):n}const xv=g("$ZodObject",(t,e)=>{if(Y.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){const c=e.shape;Object.defineProperty(e,"shape",{get:()=>{const u={...c};return Object.defineProperty(e,"shape",{value:u}),u}})}const r=ei(()=>pu(e));U(t._zod,"propValues",()=>{const c=e.shape,u={};for(const l in c){const h=c[l]._zod;if(h.values){u[l]??(u[l]=new Set);for(const d of h.values)u[l].add(d)}}return u});const s=Pn,a=e.catchall;let o;t._zod.parse=(c,u)=>{o??(o=r.value);const l=c.value;if(!s(l))return c.issues.push({expected:"object",code:"invalid_type",input:l,inst:t}),c;c.value={};const h=[],d=o.shape;for(const f of o.keys){const b=d[f],N=b._zod.optout==="optional",k=b._zod.run({value:l[f],issues:[]},u);k instanceof Promise?h.push(k.then(O=>Ln(O,c,f,l,N))):Ln(k,c,f,l,N)}return a?yu(h,l,c,u,r.value,t):h.length?Promise.all(h).then(()=>c):c}}),Cv=g("$ZodObjectJIT",(t,e)=>{xv.init(t,e);const n=t._zod.parse,r=ei(()=>pu(e)),s=f=>{const b=new ev(["shape","payload","ctx"]),N=r.value,k=D=>{const C=na(D);return`shape[${C}]._zod.run({ value: input[${C}], issues: [] }, ctx)`};b.write("const input = payload.value;");const O=Object.create(null);let S=0;for(const D of N.keys)O[D]=`key_${S++}`;b.write("const newResult = {};");for(const D of N.keys){const C=O[D],_=na(D),ae=f[D]?._zod?.optout==="optional";b.write(`const ${C} = ${k(D)};`),ae?b.write(`
29
+ if (${C}.issues.length) {
30
+ if (${_} in input) {
31
+ payload.issues = payload.issues.concat(${C}.issues.map(iss => ({
32
+ ...iss,
33
+ path: iss.path ? [${_}, ...iss.path] : [${_}]
34
+ })));
35
+ }
36
+ }
37
+
38
+ if (${C}.value === undefined) {
39
+ if (${_} in input) {
40
+ newResult[${_}] = undefined;
41
+ }
42
+ } else {
43
+ newResult[${_}] = ${C}.value;
44
+ }
45
+
46
+ `):b.write(`
47
+ if (${C}.issues.length) {
48
+ payload.issues = payload.issues.concat(${C}.issues.map(iss => ({
26
49
  ...iss,
27
- path: iss.path ? [${j}, ...iss.path] : [${j}]
50
+ path: iss.path ? [${_}, ...iss.path] : [${_}]
28
51
  })));
29
52
  }
30
53
 
31
-
32
- if (${_}.value === undefined) {
33
- if (${j} in input) {
34
- newResult[${j}] = undefined;
54
+ if (${C}.value === undefined) {
55
+ if (${_} in input) {
56
+ newResult[${_}] = undefined;
35
57
  }
36
58
  } else {
37
- newResult[${j}] = ${_}.value;
59
+ newResult[${_}] = ${C}.value;
38
60
  }
39
61
 
40
- `)}O.write("payload.value = newResult;"),O.write("return payload;");const A=O.compile();return(D,_)=>A(f,D,_)};let a;const o=$n,c=!Rc.jitless,u=c&&dw.value,h=e.catchall;let d;t._zod.parse=(f,O)=>{d??(d=r.value);const S=f.value;return o(S)?c&&u&&O?.async===!1&&O.jitless!==!0?(a||(a=s(e.shape)),f=a(f,O),h?Jc([],S,f,O,d,t):f):n(f,O):(f.issues.push({expected:"object",code:"invalid_type",input:S,inst:t}),f)}});function qi(t,e,n,r){for(const a of t)if(a.issues.length===0)return e.value=a.value,e;const s=t.filter(a=>!vt(a));return s.length===1?(e.value=s[0].value,s[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(a=>a.issues.map(o=>ct(o,r,ot())))}),e)}const ev=g("$ZodUnion",(t,e)=>{q.init(t,e),M(t._zod,"optin",()=>e.options.some(s=>s._zod.optin==="optional")?"optional":void 0),M(t._zod,"optout",()=>e.options.some(s=>s._zod.optout==="optional")?"optional":void 0),M(t._zod,"values",()=>{if(e.options.every(s=>s._zod.values))return new Set(e.options.flatMap(s=>Array.from(s._zod.values)))}),M(t._zod,"pattern",()=>{if(e.options.every(s=>s._zod.pattern)){const s=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${s.map(a=>Bs(a.source)).join("|")})$`)}});const n=e.options.length===1,r=e.options[0]._zod.run;t._zod.parse=(s,a)=>{if(n)return r(s,a);let o=!1;const c=[];for(const l of e.options){const u=l._zod.run({value:s.value,issues:[]},a);if(u instanceof Promise)c.push(u),o=!0;else{if(u.issues.length===0)return u;c.push(u)}}return o?Promise.all(c).then(l=>qi(l,s,t,a)):qi(c,s,t,a)}}),tv=g("$ZodIntersection",(t,e)=>{q.init(t,e),t._zod.parse=(n,r)=>{const s=n.value,a=e.left._zod.run({value:s,issues:[]},r),o=e.right._zod.run({value:s,issues:[]},r);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([l,u])=>Fi(n,l,u)):Fi(n,a,o)}});function Qr(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Kt(t)&&Kt(e)){const n=Object.keys(e),r=Object.keys(t).filter(a=>n.indexOf(a)!==-1),s={...t,...e};for(const a of r){const o=Qr(t[a],e[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};s[a]=o.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const s=t[r],a=e[r],o=Qr(s,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Fi(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),vt(t))return t;const r=Qr(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}const nv=g("$ZodEnum",(t,e)=>{q.init(t,e);const n=lw(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(s=>yw.has(typeof s)).map(s=>typeof s=="string"?At(s):s.toString()).join("|")})$`),t._zod.parse=(s,a)=>{const o=s.value;return r.has(o)||s.issues.push({code:"invalid_value",values:n,input:o,inst:t}),s}}),rv=g("$ZodLiteral",(t,e)=>{if(q.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?At(r):r?At(r.toString()):String(r)).join("|")})$`),t._zod.parse=(r,s)=>{const a=r.value;return n.has(a)||r.issues.push({code:"invalid_value",values:e.values,input:a,inst:t}),r}}),sv=g("$ZodTransform",(t,e)=>{q.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new _c(t.constructor.name);const s=e.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(o=>(n.value=o,n));if(s instanceof Promise)throw new Et;return n.value=s,n}});function Yi(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const iv=g("$ZodOptional",(t,e)=>{q.init(t,e),t._zod.optin="optional",t._zod.optout="optional",M(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),M(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Bs(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Yi(a,n.value)):Yi(s,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),av=g("$ZodNullable",(t,e)=>{q.init(t,e),M(t._zod,"optin",()=>e.innerType._zod.optin),M(t._zod,"optout",()=>e.innerType._zod.optout),M(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Bs(n.source)}|null)$`):void 0}),M(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),ov=g("$ZodDefault",(t,e)=>{q.init(t,e),t._zod.optin="optional",M(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Gi(a,e)):Gi(s,e)}});function Gi(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const cv=g("$ZodPrefault",(t,e)=>{q.init(t,e),t._zod.optin="optional",M(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),uv=g("$ZodNonOptional",(t,e)=>{q.init(t,e),M(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Hi(a,t)):Hi(s,t)}});function Hi(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const lv=g("$ZodCatch",(t,e)=>{q.init(t,e),M(t._zod,"optin",()=>e.innerType._zod.optin),M(t._zod,"optout",()=>e.innerType._zod.optout),M(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>(n.value=a.value,a.issues.length&&(n.value=e.catchValue({...n,error:{issues:a.issues.map(o=>ct(o,r,ot()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(a=>ct(a,r,ot()))},input:n.value}),n.issues=[]),n)}}),hv=g("$ZodPipe",(t,e)=>{q.init(t,e),M(t._zod,"values",()=>e.in._zod.values),M(t._zod,"optin",()=>e.in._zod.optin),M(t._zod,"optout",()=>e.out._zod.optout),M(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){const a=e.out._zod.run(n,r);return a instanceof Promise?a.then(o=>On(o,e.in,r)):On(a,e.in,r)}const s=e.in._zod.run(n,r);return s instanceof Promise?s.then(a=>On(a,e.out,r)):On(s,e.out,r)}});function On(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const fv=g("$ZodReadonly",(t,e)=>{q.init(t,e),M(t._zod,"propValues",()=>e.innerType._zod.propValues),M(t._zod,"values",()=>e.innerType._zod.values),M(t._zod,"optin",()=>e.innerType?._zod?.optin),M(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(Vi):Vi(s)}});function Vi(t){return t.value=Object.freeze(t.value),t}const dv=g("$ZodCustom",(t,e)=>{re.init(t,e),q.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,s=e.fn(r);if(s instanceof Promise)return s.then(a=>Wi(a,n,r,t));Wi(s,n,r,t)}});function Wi(t,e,n,r){if(!t){const s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),e.issues.push(Jt(s))}}var Ki;class yv{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){const r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const s={...r,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function pv(){return new yv}(Ki=globalThis).__zod_globalRegistry??(Ki.__zod_globalRegistry=pv());const En=globalThis.__zod_globalRegistry;function mv(t,e){return new t({type:"string",...k(e)})}function gv(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...k(e)})}function Ji(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...k(e)})}function Xc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...k(e)})}function wv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...k(e)})}function bv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...k(e)})}function vv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...k(e)})}function zv(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...k(e)})}function Tv(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...k(e)})}function Ov(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...k(e)})}function Ev(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...k(e)})}function Nv(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...k(e)})}function Sv(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...k(e)})}function kv(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...k(e)})}function Av(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...k(e)})}function $v(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...k(e)})}function Iv(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...k(e)})}function Zv(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...k(e)})}function xv(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...k(e)})}function Cv(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...k(e)})}function _v(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...k(e)})}function Rv(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...k(e)})}function jv(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...k(e)})}function Mv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...k(e)})}function Uv(t,e){return new t({type:"string",format:"date",check:"string_format",...k(e)})}function Dv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...k(e)})}function Lv(t,e){return new t({type:"string",format:"duration",check:"string_format",...k(e)})}function Pv(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...k(e)})}function Bv(t,e){return new t({type:"boolean",...k(e)})}function qv(t){return new t({type:"unknown"})}function Fv(t,e){return new t({type:"never",...k(e)})}function Xi(t,e){return new Gc({check:"less_than",...k(e),value:t,inclusive:!1})}function mr(t,e){return new Gc({check:"less_than",...k(e),value:t,inclusive:!0})}function Qi(t,e){return new Hc({check:"greater_than",...k(e),value:t,inclusive:!1})}function gr(t,e){return new Hc({check:"greater_than",...k(e),value:t,inclusive:!0})}function ea(t,e){return new cb({check:"multiple_of",...k(e),value:t})}function Qc(t,e){return new lb({check:"max_length",...k(e),maximum:t})}function Zn(t,e){return new hb({check:"min_length",...k(e),minimum:t})}function eu(t,e){return new fb({check:"length_equals",...k(e),length:t})}function Yv(t,e){return new db({check:"string_format",format:"regex",...k(e),pattern:t})}function Gv(t){return new yb({check:"string_format",format:"lowercase",...k(t)})}function Hv(t){return new pb({check:"string_format",format:"uppercase",...k(t)})}function Vv(t,e){return new mb({check:"string_format",format:"includes",...k(e),includes:t})}function Wv(t,e){return new gb({check:"string_format",format:"starts_with",...k(e),prefix:t})}function Kv(t,e){return new wb({check:"string_format",format:"ends_with",...k(e),suffix:t})}function xt(t){return new bb({check:"overwrite",tx:t})}function Jv(t){return xt(e=>e.normalize(t))}function Xv(){return xt(t=>t.trim())}function Qv(){return xt(t=>t.toLowerCase())}function ez(){return xt(t=>t.toUpperCase())}function tz(){return xt(t=>fw(t))}function nz(t,e,n){return new t({type:"array",element:e,...k(n)})}function rz(t,e,n){return new t({type:"custom",check:"custom",fn:e,...k(n)})}function sz(t){const e=iz(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Jt(r,n.value,e._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),n.issues.push(Jt(s))}},t(n.value,n)));return e}function iz(t,e){const n=new re({check:"custom",...k(e)});return n._zod.check=t,n}const az=g("ZodISODateTime",(t,e)=>{Cb.init(t,e),B.init(t,e)});function oz(t){return Mv(az,t)}const cz=g("ZodISODate",(t,e)=>{_b.init(t,e),B.init(t,e)});function uz(t){return Uv(cz,t)}const lz=g("ZodISOTime",(t,e)=>{Rb.init(t,e),B.init(t,e)});function hz(t){return Dv(lz,t)}const fz=g("ZodISODuration",(t,e)=>{jb.init(t,e),B.init(t,e)});function dz(t){return Lv(fz,t)}const yz=(t,e)=>{Lc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Nw(t,n)},flatten:{value:n=>Ew(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Xr,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Xr,2)}},isEmpty:{get(){return t.issues.length===0}}})},de=g("ZodError",yz,{Parent:Error}),pz=Fs(de),mz=Ys(de),gz=Bn(de),wz=qn(de),bz=Aw(de),vz=$w(de),zz=Iw(de),Tz=Zw(de),Oz=xw(de),Ez=Cw(de),Nz=_w(de),Sz=Rw(de),Y=g("ZodType",(t,e)=>(q.init(t,e),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone(dt(e,{checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]})),t.clone=(n,r)=>Ke(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>pz(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>gz(t,n,r),t.parseAsync=async(n,r)=>mz(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>wz(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>bz(t,n,r),t.decode=(n,r)=>vz(t,n,r),t.encodeAsync=async(n,r)=>zz(t,n,r),t.decodeAsync=async(n,r)=>Tz(t,n,r),t.safeEncode=(n,r)=>Oz(t,n,r),t.safeDecode=(n,r)=>Ez(t,n,r),t.safeEncodeAsync=async(n,r)=>Nz(t,n,r),t.safeDecodeAsync=async(n,r)=>Sz(t,n,r),t.refine=(n,r)=>t.check(vT(n,r)),t.superRefine=n=>t.check(zT(n)),t.overwrite=n=>t.check(xt(n)),t.optional=()=>ra(t),t.nullable=()=>sa(t),t.nullish=()=>ra(sa(t)),t.nonoptional=n=>dT(t,n),t.array=()=>Qz(t),t.or=n=>Vs([t,n]),t.and=n=>rT(t,n),t.transform=n=>ia(t,oT(n)),t.default=n=>lT(t,n),t.prefault=n=>fT(t,n),t.catch=n=>pT(t,n),t.pipe=n=>ia(t,n),t.readonly=()=>wT(t),t.describe=n=>{const r=t.clone();return En.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return En.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return En.get(t);const r=t.clone();return En.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),tu=g("_ZodString",(t,e)=>{Gs.init(t,e),Y.init(t,e);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(Yv(...r)),t.includes=(...r)=>t.check(Vv(...r)),t.startsWith=(...r)=>t.check(Wv(...r)),t.endsWith=(...r)=>t.check(Kv(...r)),t.min=(...r)=>t.check(Zn(...r)),t.max=(...r)=>t.check(Qc(...r)),t.length=(...r)=>t.check(eu(...r)),t.nonempty=(...r)=>t.check(Zn(1,...r)),t.lowercase=r=>t.check(Gv(r)),t.uppercase=r=>t.check(Hv(r)),t.trim=()=>t.check(Xv()),t.normalize=(...r)=>t.check(Jv(...r)),t.toLowerCase=()=>t.check(Qv()),t.toUpperCase=()=>t.check(ez()),t.slugify=()=>t.check(tz())}),kz=g("ZodString",(t,e)=>{Gs.init(t,e),tu.init(t,e),t.email=n=>t.check(gv(Az,n)),t.url=n=>t.check(zv(Iz,n)),t.jwt=n=>t.check(jv(Yz,n)),t.emoji=n=>t.check(Tv(Zz,n)),t.guid=n=>t.check(Ji(ta,n)),t.uuid=n=>t.check(Xc(Bt,n)),t.uuidv4=n=>t.check(wv(Bt,n)),t.uuidv6=n=>t.check(bv(Bt,n)),t.uuidv7=n=>t.check(vv(Bt,n)),t.nanoid=n=>t.check(Ov(xz,n)),t.guid=n=>t.check(Ji(ta,n)),t.cuid=n=>t.check(Ev(Cz,n)),t.cuid2=n=>t.check(Nv(_z,n)),t.ulid=n=>t.check(Sv(Rz,n)),t.base64=n=>t.check(Cv(Bz,n)),t.base64url=n=>t.check(_v(qz,n)),t.xid=n=>t.check(kv(jz,n)),t.ksuid=n=>t.check(Av(Mz,n)),t.ipv4=n=>t.check($v(Uz,n)),t.ipv6=n=>t.check(Iv(Dz,n)),t.cidrv4=n=>t.check(Zv(Lz,n)),t.cidrv6=n=>t.check(xv(Pz,n)),t.e164=n=>t.check(Rv(Fz,n)),t.datetime=n=>t.check(oz(n)),t.date=n=>t.check(uz(n)),t.time=n=>t.check(hz(n)),t.duration=n=>t.check(dz(n))});function he(t){return mv(kz,t)}const B=g("ZodStringFormat",(t,e)=>{P.init(t,e),tu.init(t,e)}),Az=g("ZodEmail",(t,e)=>{Eb.init(t,e),B.init(t,e)}),ta=g("ZodGUID",(t,e)=>{Tb.init(t,e),B.init(t,e)}),Bt=g("ZodUUID",(t,e)=>{Ob.init(t,e),B.init(t,e)});function $z(t){return Xc(Bt,t)}const Iz=g("ZodURL",(t,e)=>{Nb.init(t,e),B.init(t,e)}),Zz=g("ZodEmoji",(t,e)=>{Sb.init(t,e),B.init(t,e)}),xz=g("ZodNanoID",(t,e)=>{kb.init(t,e),B.init(t,e)}),Cz=g("ZodCUID",(t,e)=>{Ab.init(t,e),B.init(t,e)}),_z=g("ZodCUID2",(t,e)=>{$b.init(t,e),B.init(t,e)}),Rz=g("ZodULID",(t,e)=>{Ib.init(t,e),B.init(t,e)}),jz=g("ZodXID",(t,e)=>{Zb.init(t,e),B.init(t,e)}),Mz=g("ZodKSUID",(t,e)=>{xb.init(t,e),B.init(t,e)}),Uz=g("ZodIPv4",(t,e)=>{Mb.init(t,e),B.init(t,e)}),Dz=g("ZodIPv6",(t,e)=>{Ub.init(t,e),B.init(t,e)}),Lz=g("ZodCIDRv4",(t,e)=>{Db.init(t,e),B.init(t,e)}),Pz=g("ZodCIDRv6",(t,e)=>{Lb.init(t,e),B.init(t,e)}),Bz=g("ZodBase64",(t,e)=>{Pb.init(t,e),B.init(t,e)}),qz=g("ZodBase64URL",(t,e)=>{qb.init(t,e),B.init(t,e)}),Fz=g("ZodE164",(t,e)=>{Fb.init(t,e),B.init(t,e)}),Yz=g("ZodJWT",(t,e)=>{Gb.init(t,e),B.init(t,e)}),Gz=g("ZodNumber",(t,e)=>{Wc.init(t,e),Y.init(t,e),t.gt=(r,s)=>t.check(Qi(r,s)),t.gte=(r,s)=>t.check(gr(r,s)),t.min=(r,s)=>t.check(gr(r,s)),t.lt=(r,s)=>t.check(Xi(r,s)),t.lte=(r,s)=>t.check(mr(r,s)),t.max=(r,s)=>t.check(mr(r,s)),t.int=r=>t.check(xn(r)),t.safe=r=>t.check(xn(r)),t.positive=r=>t.check(Qi(0,r)),t.nonnegative=r=>t.check(gr(0,r)),t.negative=r=>t.check(Xi(0,r)),t.nonpositive=r=>t.check(mr(0,r)),t.multipleOf=(r,s)=>t.check(ea(r,s)),t.step=(r,s)=>t.check(ea(r,s)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null}),Hz=g("ZodNumberFormat",(t,e)=>{Hb.init(t,e),Gz.init(t,e)});function xn(t){return Pv(Hz,t)}const Vz=g("ZodBoolean",(t,e)=>{Vb.init(t,e),Y.init(t,e)});function Hs(t){return Bv(Vz,t)}const Wz=g("ZodUnknown",(t,e)=>{Wb.init(t,e),Y.init(t,e)});function na(){return qv(Wz)}const Kz=g("ZodNever",(t,e)=>{Kb.init(t,e),Y.init(t,e)});function Jz(t){return Fv(Kz,t)}const Xz=g("ZodArray",(t,e)=>{Jb.init(t,e),Y.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Zn(n,r)),t.nonempty=n=>t.check(Zn(1,n)),t.max=(n,r)=>t.check(Qc(n,r)),t.length=(n,r)=>t.check(eu(n,r)),t.unwrap=()=>t.element});function Qz(t,e){return nz(Xz,t,e)}const eT=g("ZodObject",(t,e)=>{Qb.init(t,e),Y.init(t,e),M(t,"shape",()=>e.shape),t.keyof=()=>nu(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:na()}),t.loose=()=>t.clone({...t._zod.def,catchall:na()}),t.strict=()=>t.clone({...t._zod.def,catchall:Jz()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>bw(t,n),t.safeExtend=n=>vw(t,n),t.merge=n=>zw(t,n),t.pick=n=>gw(t,n),t.omit=n=>ww(t,n),t.partial=(...n)=>Tw(ru,t,n[0]),t.required=(...n)=>Ow(su,t,n[0])});function te(t,e){const n={type:"object",shape:t??{},...k(e)};return new eT(n)}const tT=g("ZodUnion",(t,e)=>{ev.init(t,e),Y.init(t,e),t.options=e.options});function Vs(t,e){return new tT({type:"union",options:t,...k(e)})}const nT=g("ZodIntersection",(t,e)=>{tv.init(t,e),Y.init(t,e)});function rT(t,e){return new nT({type:"intersection",left:t,right:e})}const es=g("ZodEnum",(t,e)=>{nv.init(t,e),Y.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,s)=>{const a={};for(const o of r)if(n.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new es({...e,checks:[],...k(s),entries:a})},t.exclude=(r,s)=>{const a={...e.entries};for(const o of r)if(n.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new es({...e,checks:[],...k(s),entries:a})}});function nu(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new es({type:"enum",entries:n,...k(e)})}const sT=g("ZodLiteral",(t,e)=>{rv.init(t,e),Y.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function iT(t,e){return new sT({type:"literal",values:Array.isArray(t)?t:[t],...k(e)})}const aT=g("ZodTransform",(t,e)=>{sv.init(t,e),Y.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new _c(t.constructor.name);n.addIssue=a=>{if(typeof a=="string")n.issues.push(Jt(a,n.value,e));else{const o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),n.issues.push(Jt(o))}};const s=e.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function oT(t){return new aT({type:"transform",transform:t})}const ru=g("ZodOptional",(t,e)=>{iv.init(t,e),Y.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ra(t){return new ru({type:"optional",innerType:t})}const cT=g("ZodNullable",(t,e)=>{av.init(t,e),Y.init(t,e),t.unwrap=()=>t._zod.def.innerType});function sa(t){return new cT({type:"nullable",innerType:t})}const uT=g("ZodDefault",(t,e)=>{ov.init(t,e),Y.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function lT(t,e){return new uT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Mc(e)}})}const hT=g("ZodPrefault",(t,e)=>{cv.init(t,e),Y.init(t,e),t.unwrap=()=>t._zod.def.innerType});function fT(t,e){return new hT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Mc(e)}})}const su=g("ZodNonOptional",(t,e)=>{uv.init(t,e),Y.init(t,e),t.unwrap=()=>t._zod.def.innerType});function dT(t,e){return new su({type:"nonoptional",innerType:t,...k(e)})}const yT=g("ZodCatch",(t,e)=>{lv.init(t,e),Y.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function pT(t,e){return new yT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const mT=g("ZodPipe",(t,e)=>{hv.init(t,e),Y.init(t,e),t.in=e.in,t.out=e.out});function ia(t,e){return new mT({type:"pipe",in:t,out:e})}const gT=g("ZodReadonly",(t,e)=>{fv.init(t,e),Y.init(t,e),t.unwrap=()=>t._zod.def.innerType});function wT(t){return new gT({type:"readonly",innerType:t})}const bT=g("ZodCustom",(t,e)=>{dv.init(t,e),Y.init(t,e)});function vT(t,e={}){return rz(bT,t,e)}function zT(t){return sz(t)}const $e=t=>t?JSON.parse(t):{},Ws=te({key:he(),type:he(),config:fe.unknownZ.or(he().transform($e))}),iu=Ws.extend({position:Ss.xy}),ts=te({param:he(),node:he()}),Ks=te({source:ts,target:ts}),TT=te({nodes:Ws.array(),edges:Ks.array()}),au=te({nodes:iu.array(),edges:Ks.array()}),ou=te({raw:he()}),un=$z(),cu=nu(["graph","text"]).or(iT("").transform(()=>"graph")),Yn=te({key:un,name:he(),graph:au,text:ou,version:he(),mode:cu}),uu=Yn.partial({key:!0,mode:!0}),OT="arc",lu=V("arc"),ET=lu(""),NT=(t,e,{convertNumericStrings:n=!0}={})=>{const r=!Array.isArray(t);let s=N.toArray(t);const a=s[0],o=typeof a;let c;return o==="string"&&n&&!isNaN(parseInt(a))&&"number"in e?(c=e.number,s=s.map(l=>parseInt(l))):c=e[o],{single:r,variant:c,normalized:s,actual:t}},se=(t,e,n,r)=>{if(r){if(n.length===0)throw new Vt(`${t} not found matching ${JSON.stringify(e)}`);if(n.length>1)throw new Wt(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${n.length}`)}},ST="sy_arc_set",kT="sy_arc_delete",AT=te({keys:un.array().optional(),names:he().array().optional(),searchTerm:he().optional(),limit:xn().optional(),offset:xn().optional(),includeStatus:Hs().optional()}),$T=te({arcs:uu.array()}),IT=te({keys:un.array()}),ZT=te({arcs:N.nullableZ(Yn)}),xT=te({arcs:Yn.array()}),CT=te({}),ns=te({content:he()}),_T=te({key:un,includeStatus:Hs().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),RT=te({name:he(),includeStatus:Hs().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),hu=Vs([_T,RT]),jT=Vs([hu,AT]);let fu=class{client;streamClient;constructor(e,n){this.client=e,this.streamClient=n}async create(e){const n=Array.isArray(e),r=await z(this.client,"/arc/create",{arcs:N.toArray(e)},$T,xT);return n?r.arcs:r.arcs[0]}async retrieve(e){const n="key"in e||"name"in e,r=await z(this.client,"/arc/retrieve",e,jT,ZT);return se("Arc",e,r.arcs,n),n?r.arcs[0]:r.arcs}async delete(e){await z(this.client,"/arc/delete",{keys:N.toArray(e)},IT,CT)}async openLSP(){return await this.streamClient.stream("/arc/lsp",ns,ns)}};const MT=Object.freeze(Object.defineProperty({__proto__:null,Client:fu,DELETE_CHANNEL_NAME:kT,ONTOLOGY_TYPE:OT,SET_CHANNEL_NAME:ST,TYPE_ONTOLOGY_ID:ET,arcZ:Yn,edgeZ:Ks,graphNodeZ:iu,graphZ:au,handleZ:ts,irNodeZ:Ws,irZ:TT,keyZ:un,lspMessageZ:ns,modeZ:cu,newZ:uu,ontologyID:lu,singleRetrieveArgsZ:hu,textZ:ou},Symbol.toStringTag,{value:"Module"})),aa="Channel key must be a valid uint32.",U=i.z.uint32().or(i.z.string().refine(t=>!isNaN(Number(t)),{message:aa}).transform(Number).refine(t=>t<Dr.MAX_UINT32,{message:aa})),du=/^[a-zA-Z_][a-zA-Z0-9_]*$/,Re=i.z.string().min(1,"Name must not be empty").regex(du,"Name can only contain letters, digits, and underscores, and cannot start with a digit"),yu=["min","max","avg","none"],pu=i.z.enum(yu),Js=i.z.object({type:pu,resetChannel:U.optional(),duration:m.z.optional()}),mu=We.statusZ(),gu=i.z.object({channel:U}),UT=We.statusZ(gu),DT=t=>Se(Gn(t)),Ct=i.z.object({name:i.z.string(),key:U,dataType:y.z,leaseholder:Ne.uint12,index:U,isIndex:i.z.boolean(),internal:i.z.boolean(),virtual:i.z.boolean(),alias:i.z.string().optional(),expression:i.z.string().default(""),status:mu.optional(),operations:N.nullableZ(Js)}),wu=Ct.extend({key:U.optional(),name:Re,leaseholder:Ne.uint12.optional(),index:U.optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().default(!1),virtual:i.z.boolean().default(!1),expression:i.z.string().default(""),operations:N.nullableZ(Js).optional()}),yt=i.z.union([Ne.toArray(U),Ne.toArray(Re),Ne.toArray(Ct).transform(t=>t.map(e=>e.key))]),Gn=V("channel"),LT=Gn(0),PT=/[a-zA-Z0-9_]/,BT=(t,e=!1)=>{if(t==="")return e?"_":"";if(t.match(du))return t;let n="";for(const r of t)r.match(PT)?n+=r:n+="_";return n[0].match(/^\d/)&&(n=`_${n}`),n},qT=new Error("request for lock canceled");var FT=function(t,e,n,r){function s(a){return a instanceof n?a:new n(function(o){o(a)})}return new(n||(n=Promise))(function(a,o){function c(h){try{u(r.next(h))}catch(d){o(d)}}function l(h){try{u(r.throw(h))}catch(d){o(d)}}function u(h){h.done?a(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class YT{constructor(e,n=qT){this._value=e,this._cancelError=n,this._queue=[],this._weightedWaiters=[]}acquire(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,s)=>{const a={resolve:r,reject:s,weight:e,priority:n},o=bu(this._queue,c=>n<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return FT(this,arguments,void 0,function*(n,r=1,s=0){const[a,o]=yield this.acquire(r,s);try{return yield n(a)}finally{o()}})}waitForUnlock(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,n)?Promise.resolve():new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),GT(this._weightedWaiters[e-1],{resolve:r,priority:n})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const n=this._value;this._value-=e.weight,e.resolve([n,this._newReleaser(e.weight)])}_newReleaser(e){let n=!1;return()=>{n||(n=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const n=this._weightedWaiters[e-1];n&&(n.forEach(r=>r.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let n=this._value;n>0;n--){const r=this._weightedWaiters[n-1];if(!r)continue;const s=r.findIndex(a=>a.priority<=e);(s===-1?r:r.splice(0,s)).forEach((a=>a.resolve()))}}}_couldLockImmediately(e,n){return(this._queue.length===0||this._queue[0].priority<n)&&e<=this._value}}function GT(t,e){const n=bu(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function bu(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var HT=function(t,e,n,r){function s(a){return a instanceof n?a:new n(function(o){o(a)})}return new(n||(n=Promise))(function(a,o){function c(h){try{u(r.next(h))}catch(d){o(d)}}function l(h){try{u(r.throw(h))}catch(d){o(d)}}function u(h){h.done?a(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class VT{constructor(e){this._semaphore=new YT(1,e)}acquire(){return HT(this,arguments,void 0,function*(e=0){const[,n]=yield this._semaphore.acquire(1,e);return n})}runExclusive(e,n=0){return this._semaphore.runExclusive(()=>e(),1,n)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const Je=cc.keyZ,ln=cc.labelZ,WT="labeled_by",KT="sy_label_set",JT="sy_label_delete",vu=ln.extend({key:Je.optional()}),XT=i.object({labels:vu.array()}),QT=i.object({labels:ln.array()}),eO=i.object({keys:Je.array()}),zu=i.object({id:L,labels:Je.array(),replace:i.boolean().optional()}),tO=zu.omit({replace:!0}),wr=i.object({}),nO=i.object({keys:Je.array().optional(),names:i.string().array().optional(),for:L.optional(),searchTerm:i.string().optional(),offset:i.int().optional(),limit:i.int().optional()}),rO=i.object({key:Je}).transform(({key:t})=>({keys:[t]})),sO=i.union([rO,nO]),iO=i.object({labels:N.nullableZ(ln)});let Tu=class{type="label";client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await z(this.client,"/label/retrieve",e,sO,iO);return se("Label",e,r.labels,n),n?r.labels[0]:r.labels}async label(e,n,r={}){await z(this.client,"/label/set",{id:e,labels:n,replace:r.replace},zu,wr)}async remove(e,n){await z(this.client,"/label/remove",{id:e,labels:n},tO,wr)}async create(e){const n=Array.isArray(e),r=await z(this.client,"/label/create",{labels:N.toArray(e)},XT,QT);return n?r.labels:r.labels[0]}async delete(e){await z(this.client,"/label/delete",{keys:N.toArray(e)},eO,wr)}};const Ou=V("label"),aO=Ou(""),oO=Object.freeze(Object.defineProperty({__proto__:null,Client:Tu,DELETE_CHANNEL_NAME:JT,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:WT,SET_CHANNEL_NAME:KT,TYPE_ONTOLOGY_ID:aO,keyZ:Je,labelZ:ln,newZ:vu,ontologyID:Ou},Symbol.toStringTag,{value:"Module"})),K=i.z.uuid(),Xs=i.z.string().min(1),hn=i.z.object({key:K,name:Xs,timeRange:x.z.refine(({isValid:t})=>t,{error:"Time range start time must be before or equal to time range end time"}).refine(({end:t})=>t.valueOf()<=Dr.MAX_INT64,{error:"Time range end time must be less than or equal to the maximum value of an int64"}).refine(({start:t})=>t.valueOf()>=Dr.MIN_INT64,{error:"Time range start time must be greater than or equal to the minimum value of an int64"}),color:i.z.string().optional(),labels:ln.array().or(i.z.null().transform(()=>{})).optional(),get parent(){return hn.optional().nullable().transform(t=>t===void 0?null:t)}}),Eu=hn.omit({parent:!0,labels:!0}).partial({key:!0}),cO=i.z.object({nodeKey:Ne.uint12.optional(),keys:U.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),rangeKey:K.optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),dataTypes:y.z.array().optional(),notDataTypes:y.z.array().optional(),virtual:i.z.boolean().optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional(),legacyCalculated:i.z.boolean().optional()}),uO=i.z.object({channels:N.nullableZ(Ct)}),ge=t=>(Array.isArray(t)&&t.length>0&&typeof t[0]=="object"?t=t.map(e=>e.key):typeof t=="object"&&"key"in t&&(t=[t.key]),NT(t,{number:"keys",string:"names"}));class Qs{client;constructor(e){this.client=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const r=ge(e),{variant:s}=r;let{normalized:a}=r;return s==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[s]:a,...n})}async execute(e){return(await z(this.client,"/channel/retrieve",e,cO,uO)).channels}}class ei{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:r}=ge(e),s=[],a=[];if(r.forEach(c=>{const l=this.get(c);l!=null?s.push(...l):a.push(c)}),a.length===0)return s;const o=await this.wrapped.retrieve(a,n);return this.set(o),s.concat(o)}delete(e){const{variant:n,normalized:r}=ge(e);n==="names"?r.forEach(s=>{const a=this.namesToKeys.get(s);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(s))}):r.forEach(s=>{const a=this.cache.get(s);a!=null&&(this.cache.delete(s),this.namesToKeys.delete(a.name))})}rename(e,n){e.forEach((r,s)=>{const a=n[s],o=this.cache.get(r);if(o==null)return;this.cache.delete(r);const c=this.namesToKeys.get(o.name);c!=null&&(c.delete(r),c.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(r,o);const l=this.namesToKeys.get(a);l==null?this.namesToKeys.set(a,new Set([r])):l.add(r)})}set(e){e.forEach(n=>{this.cache.set(n.key,n);const r=this.namesToKeys.get(n.name);r==null?this.namesToKeys.set(n.name,new Set([n.key])):r.add(n.key)})}get(e){if(typeof e=="number"){const s=this.cache.get(e);return s==null?void 0:[s]}const n=this.namesToKeys.get(e);if(n==null)return;const r=[];if(n.forEach(s=>{const a=this.cache.get(s);a!=null&&r.push(a)}),r.length!==0)return r}}class Nu{mu=new VT;requests=new Map;wrapped;debouncedRun;constructor(e,n){this.wrapped=e,this.debouncedRun=Lp(()=>{this.run()},n)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n,variant:r}=ge(e);return r==="names"?await this.wrapped.retrieve(n):await new Promise((a,o)=>{this.mu.runExclusive(()=>{this.requests.set(n,{resolve:a,reject:o}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((n,r)=>r.forEach(s=>e.add(s)));try{const n=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((r,s)=>r.resolve(n.filter(a=>s.includes(a.key))))}catch(n){this.requests.forEach(r=>r.reject(n))}finally{this.requests.clear()}})}}const Su=async(t,e)=>{const{normalized:n}=ge(e),r=await t.retrieve(n),s=[];if(n.forEach(a=>{r.find(o=>o.name===a||o.key===a)==null&&s.push(a)}),s.length>0)throw new He(`Could not find channels: ${JSON.stringify(s)}`);return r},lO="sy_channel_set",hO="sy_channel_delete";class Cn{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;operations;status;constructor({dataType:e,name:n,leaseholder:r=0,key:s=0,isIndex:a=!1,index:o=0,internal:c=!1,virtual:l=!1,frameClient:u,alias:h,status:d,expression:f="",operations:O=[]}){this.key=U.parse(s),this.name=n,this.dataType=new y(e),this.leaseholder=r,this.index=U.parse(o),this.isIndex=a,this.internal=c,this.alias=h,this.virtual=l,this.expression=f,this.operations=O,d!=null&&(this.status=We.create(d)),this._frameClient=u??null}get framer(){if(this._frameClient==null)throw new H("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Ct.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,expression:this.expression,status:this.status,operations:this.operations})}get isCalculated(){return ti(this.payload)}get ontologyID(){return Gn(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,n){return await this.framer.write(e,this.key,n)}}const fO=i.z.object({}),dO=i.z.object({group:Ln});let ku=class{frameClient;client;retriever;writer;constructor(e,n,r,s){this.frameClient=e,this.retriever=n,this.client=r,this.writer=s}async create(e,n={}){const{retrieveIfNameExists:r=!1}=n,s=!Array.isArray(e);let a=N.toArray(e),o=[];if(r){const c=await this.retriever.retrieve(a.map(u=>u.name)),l=new Set(c.map(u=>u.name));a=a.filter(u=>!l.has(u.name)),o=this.sugar(c)}return o=o.concat(this.sugar(await this.writer.create(a))),s?o[0]:o}async retrieve(e,n){if(typeof e=="object"&&!Array.isArray(e))return this.sugar(await this.retriever.retrieve(e));const r=!Array.isArray(e),s=this.sugar(await this.retriever.retrieve(e,n));return se("channel",e,s,r),r?s[0]:s}async delete(e){const{normalized:n,variant:r}=ge(e);return r==="keys"?await this.writer.delete({keys:n}):await this.writer.delete({names:n})}async rename(e,n){return await this.writer.rename(N.toArray(e),N.toArray(n))}createDebouncedBatchRetriever(e=10){return new ei(new Nu(new Qs(this.client),e))}sugar(e){const{frameClient:n}=this;return Array.isArray(e)?e.map(r=>new Cn({...r,frameClient:n})):new Cn({...e,frameClient:n})}async retrieveGroup(){return(await z(this.client,"/channel/retrieve-group",{},fO,dO)).group}};const ti=({virtual:t,expression:e})=>t&&e!=="",yO=i.z.object({channels:wu.array()}),pO=i.z.object({channels:Ct.array()}),mO=i.z.object({keys:U.array().optional(),names:Re.array().optional()}),gO=i.z.object({}),wO=i.z.object({keys:U.array(),names:Re.array()}),bO=i.z.object({});let Au=class{client;cache;constructor(e,n){this.client=e,this.cache=n}async create(e){const{channels:n}=await z(this.client,"/channel/create",{channels:e.map(r=>({...r,dataType:r.dataType}))},yO,pO);return this.cache.set(n),n}async delete(e){const n=U.array().parse(e.keys??[]);await z(this.client,"/channel/delete",e,mO,gO),n.length>0&&this.cache.delete(n),e.names!=null&&this.cache.delete(e.names)}async rename(e,n){await z(this.client,"/channel/rename",{keys:e,names:n},wO,bO),this.cache.rename(e,n)}};const vO=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:ei,Channel:Cn,Client:ku,ClusterRetriever:Qs,DELETE_CHANNEL_NAME:hO,DebouncedBatchRetriever:Nu,OPERATION_TYPES:yu,SET_CHANNEL_NAME:lO,TYPE_ONTOLOGY_ID:LT,Writer:Au,analyzeParams:ge,calculationStatusDetailsZ:gu,calculationStatusZ:UT,escapeInvalidName:BT,isCalculated:ti,keyZ:U,nameZ:Re,newZ:wu,ontologyID:Gn,operationType:pu,operationZ:Js,paramsZ:yt,payloadZ:Ct,retrieveRequired:Su,statusKey:DT,statusZ:mu},Symbol.toStringTag,{value:"Module"})),zO=i.z.object({username:i.z.string(),password:i.z.string()}),TO=i.z.object({token:i.z.string(),user:cn}),oa="/auth/login",OO=3,EO=i.z.object({username:i.z.string(),password:i.z.string(),newPassword:i.z.string().min(1)}),NO=i.z.object({}),SO=[Vr,Wr];let kO=class{client;credentials;authState={authenticated:!1};authenticating;retryCount;constructor(e,n){this.client=e,this.credentials=n,this.retryCount=0}get authenticated(){return this.authState.authenticated}get user(){return this.authState.authenticated?this.authState.user:void 0}get token(){return this.authState.authenticated?this.authState.token:void 0}async retrieveUser(){this.authState.authenticated||await this.authenticating;const{authState:e}=this;if(!e.authenticated)throw new Error("Authentication failed: user not available");return e.user}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await z(this.client,"/auth/change-password",{username:this.credentials.username,password:this.credentials.password,newPassword:e},EO,NO),this.credentials.password=e}middleware(){const e=async(n,r)=>{if(!this.authenticated&&!n.target.endsWith(oa)){this.authenticating??=new Promise((c,l)=>{this.client.send(oa,this.credentials,zO,TO).then(([u,h])=>{if(h!=null)return c(h);if(u==null)return c(new Error("No response from login"));this.authState={authenticated:!0,user:u.user,token:u.token},c(null)}).catch(l)});const o=await this.authenticating;if(o!=null)return[n,o]}n.params.Authorization=`Bearer ${this.token}`;const[s,a]=await r(n);return SO.some(o=>o.matches(a))&&this.retryCount<OO?(this.authState={authenticated:!1},this.authenticating=void 0,this.retryCount+=1,e(n,r)):(this.retryCount=0,[s,a])};return e}};const $u=i.z.enum(["disconnected","connecting","connected","failed"]),Iu=i.z.object({status:$u,error:i.z.instanceof(Error).optional(),message:i.z.string().optional(),clusterKey:i.z.string(),clientVersion:i.z.string(),clientServerCompatible:i.z.boolean(),nodeVersion:i.z.string().optional()}),AO=i.z.object({clusterKey:i.z.string(),nodeVersion:i.z.string().optional()}),$O=i.z.void(),ca={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.50.0"},ua=(t,e,n)=>{const r=n?"Core":"client";return`Synnax Core version ${t!=null?`${t} `:""}is too ${n?"old":"new"} for client version ${e}.
62
+ `)}b.write("payload.value = newResult;"),b.write("return payload;");const A=b.compile();return(D,C)=>A(f,D,C)};let a;const o=Pn,c=!Xc.jitless,l=c&&Vw.value,h=e.catchall;let d;t._zod.parse=(f,b)=>{d??(d=r.value);const N=f.value;return o(N)?c&&l&&b?.async===!1&&b.jitless!==!0?(a||(a=s(e.shape)),f=a(f,b),h?yu([],N,f,b,d,t):f):n(f,b):(f.issues.push({expected:"object",code:"invalid_type",input:N,inst:t}),f)}});function ia(t,e,n,r){for(const a of t)if(a.issues.length===0)return e.value=a.value,e;const s=t.filter(a=>!Ot(a));return s.length===1?(e.value=s[0].value,s[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(a=>a.issues.map(o=>ft(o,r,ht())))}),e)}const _v=g("$ZodUnion",(t,e)=>{Y.init(t,e),U(t._zod,"optin",()=>e.options.some(s=>s._zod.optin==="optional")?"optional":void 0),U(t._zod,"optout",()=>e.options.some(s=>s._zod.optout==="optional")?"optional":void 0),U(t._zod,"values",()=>{if(e.options.every(s=>s._zod.values))return new Set(e.options.flatMap(s=>Array.from(s._zod.values)))}),U(t._zod,"pattern",()=>{if(e.options.every(s=>s._zod.pattern)){const s=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${s.map(a=>ni(a.source)).join("|")})$`)}});const n=e.options.length===1,r=e.options[0]._zod.run;t._zod.parse=(s,a)=>{if(n)return r(s,a);let o=!1;const c=[];for(const u of e.options){const l=u._zod.run({value:s.value,issues:[]},a);if(l instanceof Promise)c.push(l),o=!0;else{if(l.issues.length===0)return l;c.push(l)}}return o?Promise.all(c).then(u=>ia(u,s,t,a)):ia(c,s,t,a)}}),Mv=g("$ZodIntersection",(t,e)=>{Y.init(t,e),t._zod.parse=(n,r)=>{const s=n.value,a=e.left._zod.run({value:s,issues:[]},r),o=e.right._zod.run({value:s,issues:[]},r);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([u,l])=>aa(n,u,l)):aa(n,a,o)}});function ds(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(nn(t)&&nn(e)){const n=Object.keys(e),r=Object.keys(t).filter(a=>n.indexOf(a)!==-1),s={...t,...e};for(const a of r){const o=ds(t[a],e[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};s[a]=o.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const s=t[r],a=e[r],o=ds(s,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function aa(t,e,n){const r=new Map;let s;for(const c of e.issues)if(c.code==="unrecognized_keys"){s??(s=c);for(const u of c.keys)r.has(u)||r.set(u,{}),r.get(u).l=!0}else t.issues.push(c);for(const c of n.issues)if(c.code==="unrecognized_keys")for(const u of c.keys)r.has(u)||r.set(u,{}),r.get(u).r=!0;else t.issues.push(c);const a=[...r].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(a.length&&s&&t.issues.push({...s,keys:a}),Ot(t))return t;const o=ds(e.value,n.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return t.value=o.data,t}const Rv=g("$ZodEnum",(t,e)=>{Y.init(t,e);const n=Qc(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(s=>Gw.has(typeof s)).map(s=>typeof s=="string"?At(s):s.toString()).join("|")})$`),t._zod.parse=(s,a)=>{const o=s.value;return r.has(o)||s.issues.push({code:"invalid_value",values:n,input:o,inst:t}),s}}),jv=g("$ZodLiteral",(t,e)=>{if(Y.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?At(r):r?At(r.toString()):String(r)).join("|")})$`),t._zod.parse=(r,s)=>{const a=r.value;return n.has(a)||r.issues.push({code:"invalid_value",values:e.values,input:a,inst:t}),r}}),Uv=g("$ZodTransform",(t,e)=>{Y.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Kc(t.constructor.name);const s=e.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(o=>(n.value=o,n));if(s instanceof Promise)throw new Et;return n.value=s,n}});function oa(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const mu=g("$ZodOptional",(t,e)=>{Y.init(t,e),t._zod.optin="optional",t._zod.optout="optional",U(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),U(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${ni(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>oa(a,n.value)):oa(s,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),Pv=g("$ZodExactOptional",(t,e)=>{mu.init(t,e),U(t._zod,"values",()=>e.innerType._zod.values),U(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),Lv=g("$ZodNullable",(t,e)=>{Y.init(t,e),U(t._zod,"optin",()=>e.innerType._zod.optin),U(t._zod,"optout",()=>e.innerType._zod.optout),U(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${ni(n.source)}|null)$`):void 0}),U(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),Dv=g("$ZodDefault",(t,e)=>{Y.init(t,e),t._zod.optin="optional",U(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>ca(a,e)):ca(s,e)}});function ca(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const Bv=g("$ZodPrefault",(t,e)=>{Y.init(t,e),t._zod.optin="optional",U(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),qv=g("$ZodNonOptional",(t,e)=>{Y.init(t,e),U(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>ua(a,t)):ua(s,t)}});function ua(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const Fv=g("$ZodCatch",(t,e)=>{Y.init(t,e),U(t._zod,"optin",()=>e.innerType._zod.optin),U(t._zod,"optout",()=>e.innerType._zod.optout),U(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>(n.value=a.value,a.issues.length&&(n.value=e.catchValue({...n,error:{issues:a.issues.map(o=>ft(o,r,ht()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(a=>ft(a,r,ht()))},input:n.value}),n.issues=[]),n)}}),Yv=g("$ZodPipe",(t,e)=>{Y.init(t,e),U(t._zod,"values",()=>e.in._zod.values),U(t._zod,"optin",()=>e.in._zod.optin),U(t._zod,"optout",()=>e.out._zod.optout),U(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){const a=e.out._zod.run(n,r);return a instanceof Promise?a.then(o=>xn(o,e.in,r)):xn(a,e.in,r)}const s=e.in._zod.run(n,r);return s instanceof Promise?s.then(a=>xn(a,e.out,r)):xn(s,e.out,r)}});function xn(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const Hv=g("$ZodReadonly",(t,e)=>{Y.init(t,e),U(t._zod,"propValues",()=>e.innerType._zod.propValues),U(t._zod,"values",()=>e.innerType._zod.values),U(t._zod,"optin",()=>e.innerType?._zod?.optin),U(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(la):la(s)}});function la(t){return t.value=Object.freeze(t.value),t}const Vv=g("$ZodCustom",(t,e)=>{ce.init(t,e),Y.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,s=e.fn(r);if(s instanceof Promise)return s.then(a=>ha(a,n,r,t));ha(s,n,r,t)}});function ha(t,e,n,r){if(!t){const s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),e.issues.push(rn(s))}}var fa;class Gv{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){const r=n[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const s={...r,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Wv(){return new Gv}(fa=globalThis).__zod_globalRegistry??(fa.__zod_globalRegistry=Wv());const Bt=globalThis.__zod_globalRegistry;function Jv(t,e){return new t({type:"string",...$(e)})}function Kv(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...$(e)})}function da(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...$(e)})}function gu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...$(e)})}function Xv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...$(e)})}function Qv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...$(e)})}function ez(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...$(e)})}function tz(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...$(e)})}function nz(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...$(e)})}function rz(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...$(e)})}function sz(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...$(e)})}function iz(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...$(e)})}function az(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...$(e)})}function oz(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...$(e)})}function cz(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...$(e)})}function uz(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...$(e)})}function lz(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...$(e)})}function hz(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...$(e)})}function fz(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...$(e)})}function dz(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...$(e)})}function pz(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...$(e)})}function yz(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...$(e)})}function mz(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...$(e)})}function gz(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...$(e)})}function wz(t,e){return new t({type:"string",format:"date",check:"string_format",...$(e)})}function bz(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...$(e)})}function vz(t,e){return new t({type:"string",format:"duration",check:"string_format",...$(e)})}function zz(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...$(e)})}function Tz(t,e){return new t({type:"boolean",...$(e)})}function Oz(t){return new t({type:"unknown"})}function Sz(t,e){return new t({type:"never",...$(e)})}function pa(t,e){return new lu({check:"less_than",...$(e),value:t,inclusive:!1})}function Zr(t,e){return new lu({check:"less_than",...$(e),value:t,inclusive:!0})}function ya(t,e){return new hu({check:"greater_than",...$(e),value:t,inclusive:!1})}function xr(t,e){return new hu({check:"greater_than",...$(e),value:t,inclusive:!0})}function ma(t,e){return new Bb({check:"multiple_of",...$(e),value:t})}function wu(t,e){return new Fb({check:"max_length",...$(e),maximum:t})}function Dn(t,e){return new Yb({check:"min_length",...$(e),minimum:t})}function bu(t,e){return new Hb({check:"length_equals",...$(e),length:t})}function Ez(t,e){return new Vb({check:"string_format",format:"regex",...$(e),pattern:t})}function Nz(t){return new Gb({check:"string_format",format:"lowercase",...$(t)})}function $z(t){return new Wb({check:"string_format",format:"uppercase",...$(t)})}function kz(t,e){return new Jb({check:"string_format",format:"includes",...$(e),includes:t})}function Az(t,e){return new Kb({check:"string_format",format:"starts_with",...$(e),prefix:t})}function Iz(t,e){return new Xb({check:"string_format",format:"ends_with",...$(e),suffix:t})}function Ct(t){return new Qb({check:"overwrite",tx:t})}function Zz(t){return Ct(e=>e.normalize(t))}function xz(){return Ct(t=>t.trim())}function Cz(){return Ct(t=>t.toLowerCase())}function _z(){return Ct(t=>t.toUpperCase())}function Mz(){return Ct(t=>Hw(t))}function Rz(t,e,n){return new t({type:"array",element:e,...$(n)})}function jz(t,e,n){return new t({type:"custom",check:"custom",fn:e,...$(n)})}function Uz(t){const e=Pz(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(rn(r,n.value,e._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),n.issues.push(rn(s))}},t(n.value,n)));return e}function Pz(t,e){const n=new ce({check:"custom",...$(e)});return n._zod.check=t,n}function vu(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Bt,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function ne(t,e,n={path:[],schemaPath:[]}){var r;const s=t._zod.def,a=e.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;const o={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,o);const c=t._zod.toJSONSchema?.();if(c)o.schema=c;else{const h={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,o.schema,h);else{const f=o.schema,b=e.processors[s.type];if(!b)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);b(t,e,f,h)}const d=t._zod.parent;d&&(o.ref||(o.ref=d),ne(d,e,h),e.seen.get(d).isParent=!0)}const u=e.metadataRegistry.get(t);return u&&Object.assign(o.schema,u),e.io==="input"&&ie(t)&&(delete o.schema.examples,delete o.schema.default),e.io==="input"&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,e.seen.get(t).schema}function zu(t,e){const n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const o of t.seen.entries()){const c=t.metadataRegistry.get(o[0])?.id;if(c){const u=r.get(c);if(u&&u!==o[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(c,o[0])}}const s=o=>{const c=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const d=t.external.registry.get(o[0])?.id,f=t.external.uri??(N=>N);if(d)return{ref:f(d)};const b=o[1].defId??o[1].schema.id??`schema${t.counter++}`;return o[1].defId=b,{defId:b,ref:`${f("__shared")}#/${c}/${b}`}}if(o[1]===n)return{ref:"#"};const l=`#/${c}/`,h=o[1].schema.id??`__schema${t.counter++}`;return{defId:h,ref:l+h}},a=o=>{if(o[1].schema.$ref)return;const c=o[1],{ref:u,defId:l}=s(o);c.def={...c.schema},l&&(c.defId=l);const h=c.schema;for(const d in h)delete h[d];h.$ref=u};if(t.cycles==="throw")for(const o of t.seen.entries()){const c=o[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
63
+
64
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of t.seen.entries()){const c=o[1];if(e===o[0]){a(o);continue}if(t.external){const l=t.external.registry.get(o[0])?.id;if(e!==o[0]&&l){a(o);continue}}if(t.metadataRegistry.get(o[0])?.id){a(o);continue}if(c.cycle){a(o);continue}if(c.count>1&&t.reused==="ref"){a(o);continue}}}function Tu(t,e){const n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=o=>{const c=t.seen.get(o);if(c.ref===null)return;const u=c.def??c.schema,l={...u},h=c.ref;if(c.ref=null,h){r(h);const f=t.seen.get(h),b=f.schema;if(b.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(b)):Object.assign(u,b),Object.assign(u,l),o._zod.parent===h)for(const k in u)k==="$ref"||k==="allOf"||k in l||delete u[k];if(b.$ref&&f.def)for(const k in u)k==="$ref"||k==="allOf"||k in f.def&&JSON.stringify(u[k])===JSON.stringify(f.def[k])&&delete u[k]}const d=o._zod.parent;if(d&&d!==h){r(d);const f=t.seen.get(d);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(const b in u)b==="$ref"||b==="allOf"||b in f.def&&JSON.stringify(u[b])===JSON.stringify(f.def[b])&&delete u[b]}t.override({zodSchema:o,jsonSchema:u,path:c.path??[]})};for(const o of[...t.seen.entries()].reverse())r(o[0]);const s={};if(t.target==="draft-2020-12"?s.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?s.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?s.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){const o=t.external.registry.get(e)?.id;if(!o)throw new Error("Schema is missing an `id` property");s.$id=t.external.uri(o)}Object.assign(s,n.def??n.schema);const a=t.external?.defs??{};for(const o of t.seen.entries()){const c=o[1];c.def&&c.defId&&(a[c.defId]=c.def)}t.external||Object.keys(a).length>0&&(t.target==="draft-2020-12"?s.$defs=a:s.definitions=a);try{const o=JSON.parse(JSON.stringify(s));return Object.defineProperty(o,"~standard",{value:{...e["~standard"],jsonSchema:{input:Bn(e,"input",t.processors),output:Bn(e,"output",t.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function ie(t,e){const n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);const r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return ie(r.element,n);if(r.type==="set")return ie(r.valueType,n);if(r.type==="lazy")return ie(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return ie(r.innerType,n);if(r.type==="intersection")return ie(r.left,n)||ie(r.right,n);if(r.type==="record"||r.type==="map")return ie(r.keyType,n)||ie(r.valueType,n);if(r.type==="pipe")return ie(r.in,n)||ie(r.out,n);if(r.type==="object"){for(const s in r.shape)if(ie(r.shape[s],n))return!0;return!1}if(r.type==="union"){for(const s of r.options)if(ie(s,n))return!0;return!1}if(r.type==="tuple"){for(const s of r.items)if(ie(s,n))return!0;return!!(r.rest&&ie(r.rest,n))}return!1}const Lz=(t,e={})=>n=>{const r=vu({...n,processors:e});return ne(t,r),zu(r,t),Tu(r,t)},Bn=(t,e,n={})=>r=>{const{libraryOptions:s,target:a}=r??{},o=vu({...s??{},target:a,io:e,processors:n});return ne(t,o),zu(o,t),Tu(o,t)},Dz={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Bz=(t,e,n,r)=>{const s=n;s.type="string";const{minimum:a,maximum:o,format:c,patterns:u,contentEncoding:l}=t._zod.bag;if(typeof a=="number"&&(s.minLength=a),typeof o=="number"&&(s.maxLength=o),c&&(s.format=Dz[c]??c,s.format===""&&delete s.format,c==="time"&&delete s.format),l&&(s.contentEncoding=l),u&&u.size>0){const h=[...u];h.length===1?s.pattern=h[0].source:h.length>1&&(s.allOf=[...h.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},qz=(t,e,n,r)=>{const s=n,{minimum:a,maximum:o,format:c,multipleOf:u,exclusiveMaximum:l,exclusiveMinimum:h}=t._zod.bag;typeof c=="string"&&c.includes("int")?s.type="integer":s.type="number",typeof h=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(s.minimum=h,s.exclusiveMinimum=!0):s.exclusiveMinimum=h),typeof a=="number"&&(s.minimum=a,typeof h=="number"&&e.target!=="draft-04"&&(h>=a?delete s.minimum:delete s.exclusiveMinimum)),typeof l=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(s.maximum=l,s.exclusiveMaximum=!0):s.exclusiveMaximum=l),typeof o=="number"&&(s.maximum=o,typeof l=="number"&&e.target!=="draft-04"&&(l<=o?delete s.maximum:delete s.exclusiveMaximum)),typeof u=="number"&&(s.multipleOf=u)},Fz=(t,e,n,r)=>{n.type="boolean"},Yz=(t,e,n,r)=>{n.not={}},Hz=(t,e,n,r)=>{},Vz=(t,e,n,r)=>{const s=t._zod.def,a=Qc(s.entries);a.every(o=>typeof o=="number")&&(n.type="number"),a.every(o=>typeof o=="string")&&(n.type="string"),n.enum=a},Gz=(t,e,n,r)=>{const s=t._zod.def,a=[];for(const o of s.values)if(o===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(o))}else a.push(o);if(a.length!==0)if(a.length===1){const o=a[0];n.type=o===null?"null":typeof o,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[o]:n.const=o}else a.every(o=>typeof o=="number")&&(n.type="number"),a.every(o=>typeof o=="string")&&(n.type="string"),a.every(o=>typeof o=="boolean")&&(n.type="boolean"),a.every(o=>o===null)&&(n.type="null"),n.enum=a},Wz=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Jz=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Kz=(t,e,n,r)=>{const s=n,a=t._zod.def,{minimum:o,maximum:c}=t._zod.bag;typeof o=="number"&&(s.minItems=o),typeof c=="number"&&(s.maxItems=c),s.type="array",s.items=ne(a.element,e,{...r,path:[...r.path,"items"]})},Xz=(t,e,n,r)=>{const s=n,a=t._zod.def;s.type="object",s.properties={};const o=a.shape;for(const l in o)s.properties[l]=ne(o[l],e,{...r,path:[...r.path,"properties",l]});const c=new Set(Object.keys(o)),u=new Set([...c].filter(l=>{const h=a.shape[l]._zod;return e.io==="input"?h.optin===void 0:h.optout===void 0}));u.size>0&&(s.required=Array.from(u)),a.catchall?._zod.def.type==="never"?s.additionalProperties=!1:a.catchall?a.catchall&&(s.additionalProperties=ne(a.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(s.additionalProperties=!1)},Qz=(t,e,n,r)=>{const s=t._zod.def,a=s.inclusive===!1,o=s.options.map((c,u)=>ne(c,e,{...r,path:[...r.path,a?"oneOf":"anyOf",u]}));a?n.oneOf=o:n.anyOf=o},eT=(t,e,n,r)=>{const s=t._zod.def,a=ne(s.left,e,{...r,path:[...r.path,"allOf",0]}),o=ne(s.right,e,{...r,path:[...r.path,"allOf",1]}),c=l=>"allOf"in l&&Object.keys(l).length===1,u=[...c(a)?a.allOf:[a],...c(o)?o.allOf:[o]];n.allOf=u},tT=(t,e,n,r)=>{const s=t._zod.def,a=ne(s.innerType,e,r),o=e.seen.get(t);e.target==="openapi-3.0"?(o.ref=s.innerType,n.nullable=!0):n.anyOf=[a,{type:"null"}]},nT=(t,e,n,r)=>{const s=t._zod.def;ne(s.innerType,e,r);const a=e.seen.get(t);a.ref=s.innerType},rT=(t,e,n,r)=>{const s=t._zod.def;ne(s.innerType,e,r);const a=e.seen.get(t);a.ref=s.innerType,n.default=JSON.parse(JSON.stringify(s.defaultValue))},sT=(t,e,n,r)=>{const s=t._zod.def;ne(s.innerType,e,r);const a=e.seen.get(t);a.ref=s.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(s.defaultValue)))},iT=(t,e,n,r)=>{const s=t._zod.def;ne(s.innerType,e,r);const a=e.seen.get(t);a.ref=s.innerType;let o;try{o=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o},aT=(t,e,n,r)=>{const s=t._zod.def,a=e.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;ne(a,e,r);const o=e.seen.get(t);o.ref=a},oT=(t,e,n,r)=>{const s=t._zod.def;ne(s.innerType,e,r);const a=e.seen.get(t);a.ref=s.innerType,n.readOnly=!0},Ou=(t,e,n,r)=>{const s=t._zod.def;ne(s.innerType,e,r);const a=e.seen.get(t);a.ref=s.innerType},cT=g("ZodISODateTime",(t,e)=>{dv.init(t,e),F.init(t,e)});function uT(t){return gz(cT,t)}const lT=g("ZodISODate",(t,e)=>{pv.init(t,e),F.init(t,e)});function hT(t){return wz(lT,t)}const fT=g("ZodISOTime",(t,e)=>{yv.init(t,e),F.init(t,e)});function dT(t){return bz(fT,t)}const pT=g("ZodISODuration",(t,e)=>{mv.init(t,e),F.init(t,e)});function yT(t){return vz(pT,t)}const mT=(t,e)=>{su.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ib(t,n)},flatten:{value:n=>sb(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,fs,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,fs,2)}},isEmpty:{get(){return t.issues.length===0}}})},me=g("ZodError",mT,{Parent:Error}),gT=si(me),wT=ii(me),bT=tr(me),vT=nr(me),zT=cb(me),TT=ub(me),OT=lb(me),ST=hb(me),ET=fb(me),NT=db(me),$T=pb(me),kT=yb(me),H=g("ZodType",(t,e)=>(Y.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Bn(t,"input"),output:Bn(t,"output")}}),t.toJSONSchema=Lz(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone(et(e,{checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0}),t.with=t.check,t.clone=(n,r)=>tt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>gT(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>bT(t,n,r),t.parseAsync=async(n,r)=>wT(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>vT(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>zT(t,n,r),t.decode=(n,r)=>TT(t,n,r),t.encodeAsync=async(n,r)=>OT(t,n,r),t.decodeAsync=async(n,r)=>ST(t,n,r),t.safeEncode=(n,r)=>ET(t,n,r),t.safeDecode=(n,r)=>NT(t,n,r),t.safeEncodeAsync=async(n,r)=>$T(t,n,r),t.safeDecodeAsync=async(n,r)=>kT(t,n,r),t.refine=(n,r)=>t.check(SO(n,r)),t.superRefine=n=>t.check(EO(n)),t.overwrite=n=>t.check(Ct(n)),t.optional=()=>ba(t),t.exactOptional=()=>hO(t),t.nullable=()=>va(t),t.nullish=()=>ba(va(t)),t.nonoptional=n=>gO(t,n),t.array=()=>tO(t),t.or=n=>ci([t,n]),t.and=n=>iO(t,n),t.transform=n=>za(t,uO(n)),t.default=n=>pO(t,n),t.prefault=n=>mO(t,n),t.catch=n=>bO(t,n),t.pipe=n=>za(t,n),t.readonly=()=>TO(t),t.describe=n=>{const r=t.clone();return Bt.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Bt.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Bt.get(t);const r=t.clone();return Bt.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=n=>n(t),t)),Su=g("_ZodString",(t,e)=>{ai.init(t,e),H.init(t,e),t._zod.processJSONSchema=(r,s,a)=>Bz(t,r,s);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(Ez(...r)),t.includes=(...r)=>t.check(kz(...r)),t.startsWith=(...r)=>t.check(Az(...r)),t.endsWith=(...r)=>t.check(Iz(...r)),t.min=(...r)=>t.check(Dn(...r)),t.max=(...r)=>t.check(wu(...r)),t.length=(...r)=>t.check(bu(...r)),t.nonempty=(...r)=>t.check(Dn(1,...r)),t.lowercase=r=>t.check(Nz(r)),t.uppercase=r=>t.check($z(r)),t.trim=()=>t.check(xz()),t.normalize=(...r)=>t.check(Zz(...r)),t.toLowerCase=()=>t.check(Cz()),t.toUpperCase=()=>t.check(_z()),t.slugify=()=>t.check(Mz())}),AT=g("ZodString",(t,e)=>{ai.init(t,e),Su.init(t,e),t.email=n=>t.check(Kv(IT,n)),t.url=n=>t.check(tz(xT,n)),t.jwt=n=>t.check(mz(VT,n)),t.emoji=n=>t.check(nz(CT,n)),t.guid=n=>t.check(da(ga,n)),t.uuid=n=>t.check(gu(qt,n)),t.uuidv4=n=>t.check(Xv(qt,n)),t.uuidv6=n=>t.check(Qv(qt,n)),t.uuidv7=n=>t.check(ez(qt,n)),t.nanoid=n=>t.check(rz(_T,n)),t.guid=n=>t.check(da(ga,n)),t.cuid=n=>t.check(sz(MT,n)),t.cuid2=n=>t.check(iz(RT,n)),t.ulid=n=>t.check(az(jT,n)),t.base64=n=>t.check(dz(FT,n)),t.base64url=n=>t.check(pz(YT,n)),t.xid=n=>t.check(oz(UT,n)),t.ksuid=n=>t.check(cz(PT,n)),t.ipv4=n=>t.check(uz(LT,n)),t.ipv6=n=>t.check(lz(DT,n)),t.cidrv4=n=>t.check(hz(BT,n)),t.cidrv6=n=>t.check(fz(qT,n)),t.e164=n=>t.check(yz(HT,n)),t.datetime=n=>t.check(uT(n)),t.date=n=>t.check(hT(n)),t.time=n=>t.check(dT(n)),t.duration=n=>t.check(yT(n))});function ye(t){return Jv(AT,t)}const F=g("ZodStringFormat",(t,e)=>{q.init(t,e),Su.init(t,e)}),IT=g("ZodEmail",(t,e)=>{sv.init(t,e),F.init(t,e)}),ga=g("ZodGUID",(t,e)=>{nv.init(t,e),F.init(t,e)}),qt=g("ZodUUID",(t,e)=>{rv.init(t,e),F.init(t,e)});function ZT(t){return gu(qt,t)}const xT=g("ZodURL",(t,e)=>{iv.init(t,e),F.init(t,e)}),CT=g("ZodEmoji",(t,e)=>{av.init(t,e),F.init(t,e)}),_T=g("ZodNanoID",(t,e)=>{ov.init(t,e),F.init(t,e)}),MT=g("ZodCUID",(t,e)=>{cv.init(t,e),F.init(t,e)}),RT=g("ZodCUID2",(t,e)=>{uv.init(t,e),F.init(t,e)}),jT=g("ZodULID",(t,e)=>{lv.init(t,e),F.init(t,e)}),UT=g("ZodXID",(t,e)=>{hv.init(t,e),F.init(t,e)}),PT=g("ZodKSUID",(t,e)=>{fv.init(t,e),F.init(t,e)}),LT=g("ZodIPv4",(t,e)=>{gv.init(t,e),F.init(t,e)}),DT=g("ZodIPv6",(t,e)=>{wv.init(t,e),F.init(t,e)}),BT=g("ZodCIDRv4",(t,e)=>{bv.init(t,e),F.init(t,e)}),qT=g("ZodCIDRv6",(t,e)=>{vv.init(t,e),F.init(t,e)}),FT=g("ZodBase64",(t,e)=>{zv.init(t,e),F.init(t,e)}),YT=g("ZodBase64URL",(t,e)=>{Ov.init(t,e),F.init(t,e)}),HT=g("ZodE164",(t,e)=>{Sv.init(t,e),F.init(t,e)}),VT=g("ZodJWT",(t,e)=>{Nv.init(t,e),F.init(t,e)}),GT=g("ZodNumber",(t,e)=>{du.init(t,e),H.init(t,e),t._zod.processJSONSchema=(r,s,a)=>qz(t,r,s),t.gt=(r,s)=>t.check(ya(r,s)),t.gte=(r,s)=>t.check(xr(r,s)),t.min=(r,s)=>t.check(xr(r,s)),t.lt=(r,s)=>t.check(pa(r,s)),t.lte=(r,s)=>t.check(Zr(r,s)),t.max=(r,s)=>t.check(Zr(r,s)),t.int=r=>t.check(qn(r)),t.safe=r=>t.check(qn(r)),t.positive=r=>t.check(ya(0,r)),t.nonnegative=r=>t.check(xr(0,r)),t.negative=r=>t.check(pa(0,r)),t.nonpositive=r=>t.check(Zr(0,r)),t.multipleOf=(r,s)=>t.check(ma(r,s)),t.step=(r,s)=>t.check(ma(r,s)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null}),WT=g("ZodNumberFormat",(t,e)=>{$v.init(t,e),GT.init(t,e)});function qn(t){return zz(WT,t)}const JT=g("ZodBoolean",(t,e)=>{kv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>Fz(t,n,r)});function oi(t){return Tz(JT,t)}const KT=g("ZodUnknown",(t,e)=>{Av.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>Hz()});function wa(){return Oz(KT)}const XT=g("ZodNever",(t,e)=>{Iv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>Yz(t,n,r)});function QT(t){return Sz(XT,t)}const eO=g("ZodArray",(t,e)=>{Zv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>Kz(t,n,r,s),t.element=e.element,t.min=(n,r)=>t.check(Dn(n,r)),t.nonempty=n=>t.check(Dn(1,n)),t.max=(n,r)=>t.check(wu(n,r)),t.length=(n,r)=>t.check(bu(n,r)),t.unwrap=()=>t.element});function tO(t,e){return Rz(eO,t,e)}const nO=g("ZodObject",(t,e)=>{Cv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>Xz(t,n,r,s),U(t,"shape",()=>e.shape),t.keyof=()=>Eu(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:wa()}),t.loose=()=>t.clone({...t._zod.def,catchall:wa()}),t.strict=()=>t.clone({...t._zod.def,catchall:QT()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Qw(t,n),t.safeExtend=n=>eb(t,n),t.merge=n=>tb(t,n),t.pick=n=>Kw(t,n),t.omit=n=>Xw(t,n),t.partial=(...n)=>nb(Nu,t,n[0]),t.required=(...n)=>rb($u,t,n[0])});function se(t,e){const n={type:"object",shape:t??{},...$(e)};return new nO(n)}const rO=g("ZodUnion",(t,e)=>{_v.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>Qz(t,n,r,s),t.options=e.options});function ci(t,e){return new rO({type:"union",options:t,...$(e)})}const sO=g("ZodIntersection",(t,e)=>{Mv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>eT(t,n,r,s)});function iO(t,e){return new sO({type:"intersection",left:t,right:e})}const ps=g("ZodEnum",(t,e)=>{Rv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(r,s,a)=>Vz(t,r,s),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,s)=>{const a={};for(const o of r)if(n.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new ps({...e,checks:[],...$(s),entries:a})},t.exclude=(r,s)=>{const a={...e.entries};for(const o of r)if(n.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new ps({...e,checks:[],...$(s),entries:a})}});function Eu(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new ps({type:"enum",entries:n,...$(e)})}const aO=g("ZodLiteral",(t,e)=>{jv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>Gz(t,n,r),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function oO(t,e){return new aO({type:"literal",values:Array.isArray(t)?t:[t],...$(e)})}const cO=g("ZodTransform",(t,e)=>{Uv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>Jz(t,n),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Kc(t.constructor.name);n.addIssue=a=>{if(typeof a=="string")n.issues.push(rn(a,n.value,e));else{const o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),n.issues.push(rn(o))}};const s=e.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function uO(t){return new cO({type:"transform",transform:t})}const Nu=g("ZodOptional",(t,e)=>{mu.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>Ou(t,n,r,s),t.unwrap=()=>t._zod.def.innerType});function ba(t){return new Nu({type:"optional",innerType:t})}const lO=g("ZodExactOptional",(t,e)=>{Pv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>Ou(t,n,r,s),t.unwrap=()=>t._zod.def.innerType});function hO(t){return new lO({type:"optional",innerType:t})}const fO=g("ZodNullable",(t,e)=>{Lv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>tT(t,n,r,s),t.unwrap=()=>t._zod.def.innerType});function va(t){return new fO({type:"nullable",innerType:t})}const dO=g("ZodDefault",(t,e)=>{Dv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>rT(t,n,r,s),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function pO(t,e){return new dO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():tu(e)}})}const yO=g("ZodPrefault",(t,e)=>{Bv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>sT(t,n,r,s),t.unwrap=()=>t._zod.def.innerType});function mO(t,e){return new yO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():tu(e)}})}const $u=g("ZodNonOptional",(t,e)=>{qv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>nT(t,n,r,s),t.unwrap=()=>t._zod.def.innerType});function gO(t,e){return new $u({type:"nonoptional",innerType:t,...$(e)})}const wO=g("ZodCatch",(t,e)=>{Fv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>iT(t,n,r,s),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function bO(t,e){return new wO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const vO=g("ZodPipe",(t,e)=>{Yv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>aT(t,n,r,s),t.in=e.in,t.out=e.out});function za(t,e){return new vO({type:"pipe",in:t,out:e})}const zO=g("ZodReadonly",(t,e)=>{Hv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>oT(t,n,r,s),t.unwrap=()=>t._zod.def.innerType});function TO(t){return new zO({type:"readonly",innerType:t})}const OO=g("ZodCustom",(t,e)=>{Vv.init(t,e),H.init(t,e),t._zod.processJSONSchema=(n,r,s)=>Wz(t,n)});function SO(t,e={}){return jz(OO,t,e)}function EO(t){return Uz(t)}const Ze=t=>t?JSON.parse(t):{},ui=se({key:ye(),type:ye(),config:oe.unknownZ.or(ye().transform(Ze))}),ku=ui.extend({position:Ps.xy}),ys=se({param:ye(),node:ye()}),li=se({source:ys,target:ys}),NO=se({nodes:ui.array(),edges:li.array()}),Au=se({nodes:ku.array(),edges:li.array()}),Iu=se({raw:ye()}),yn=ZT(),Zu=Eu(["graph","text"]).or(oO("").transform(()=>"graph")),sr=se({key:yn,name:ye(),graph:Au,text:Iu,version:ye(),mode:Zu}),xu=sr.partial({key:!0,mode:!0}),$O="arc",Cu=J("arc"),kO=Cu(""),AO=(t,e,{convertNumericStrings:n=!0}={})=>{const r=!Array.isArray(t);let s=E.toArray(t);const a=s[0],o=typeof a;let c;return o==="string"&&n&&!isNaN(parseInt(a))&&"number"in e?(c=e.number,s=s.map(u=>parseInt(u))):c=e[o],{single:r,variant:c,normalized:s,actual:t}},ue=(t,e,n,r)=>{if(r){if(n.length===0)throw new en(`${t} not found matching ${JSON.stringify(e)}`);if(n.length>1)throw new tn(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${n.length}`)}},IO="sy_arc_set",ZO="sy_arc_delete",xO=se({keys:yn.array().optional(),names:ye().array().optional(),searchTerm:ye().optional(),limit:qn().optional(),offset:qn().optional(),includeStatus:oi().optional()}),CO=se({arcs:xu.array()}),_O=se({keys:yn.array()}),MO=se({arcs:E.nullableZ(sr)}),RO=se({arcs:sr.array()}),jO=se({}),ms=se({content:ye()}),UO=se({key:yn,includeStatus:oi().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),PO=se({name:ye(),includeStatus:oi().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),_u=ci([UO,PO]),LO=ci([_u,xO]);let Mu=class{client;streamClient;constructor(e,n){this.client=e,this.streamClient=n}async create(e){const n=Array.isArray(e),r=await T(this.client,"/arc/create",{arcs:E.toArray(e)},CO,RO);return n?r.arcs:r.arcs[0]}async retrieve(e){const n="key"in e||"name"in e,r=await T(this.client,"/arc/retrieve",e,LO,MO);return ue("Arc",e,r.arcs,n),n?r.arcs[0]:r.arcs}async delete(e){await T(this.client,"/arc/delete",{keys:E.toArray(e)},_O,jO)}async openLSP(){return await this.streamClient.stream("/arc/lsp",ms,ms)}};const DO=Object.freeze(Object.defineProperty({__proto__:null,Client:Mu,DELETE_CHANNEL_NAME:ZO,ONTOLOGY_TYPE:$O,SET_CHANNEL_NAME:IO,TYPE_ONTOLOGY_ID:kO,arcZ:sr,edgeZ:li,graphNodeZ:ku,graphZ:Au,handleZ:ys,irNodeZ:ui,irZ:NO,keyZ:yn,lspMessageZ:ms,modeZ:Zu,newZ:xu,ontologyID:Cu,singleRetrieveArgsZ:_u,textZ:Iu},Symbol.toStringTag,{value:"Module"})),Ta="Channel key must be a valid uint32.",L=i.z.uint32().or(i.z.string().refine(t=>!isNaN(Number(t)),{message:Ta}).transform(Number).refine(t=>t<Xr.MAX_UINT32,{message:Ta})),Pe=i.z.string().min(1,"Name must not be empty"),Ru=["min","max","avg","none"],ju=i.z.enum(Ru),hi=i.z.object({type:ju,resetChannel:L.optional(),duration:w.z.optional()}),Uu=Qe.statusZ(),Pu=i.z.object({channel:L}),BO=Qe.statusZ(Pu),qO=t=>ke(ir(t)),_t=i.z.object({name:i.z.string(),key:L,dataType:p.z,leaseholder:be.uint12,index:L,isIndex:i.z.boolean(),internal:i.z.boolean(),virtual:i.z.boolean(),alias:i.z.string().optional(),expression:i.z.string().default(""),status:Uu.optional(),operations:E.nullableZ(hi)}),Lu=_t.extend({key:L.optional(),name:Pe,leaseholder:be.uint12.optional(),index:L.optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().default(!1),virtual:i.z.boolean().default(!1),expression:i.z.string().default(""),operations:E.nullableZ(hi).optional()}),mt=i.z.union([be.toArray(L),be.toArray(Pe),be.toArray(_t).transform(t=>t.map(e=>e.key))]),ir=J("channel"),FO=ir(0),YO=/[a-zA-Z0-9_]/,HO=/^[a-zA-Z_][a-zA-Z0-9_]*$/,VO=(t,e=!1)=>{if(t==="")return e?"_":"";if(t.match(HO))return t;let n="";for(const r of t)r.match(YO)?n+=r:n+="_";return n[0].match(/^\d/)&&(n=`_${n}`),n},GO=new Error("request for lock canceled");var WO=function(t,e,n,r){function s(a){return a instanceof n?a:new n(function(o){o(a)})}return new(n||(n=Promise))(function(a,o){function c(h){try{l(r.next(h))}catch(d){o(d)}}function u(h){try{l(r.throw(h))}catch(d){o(d)}}function l(h){h.done?a(h.value):s(h.value).then(c,u)}l((r=r.apply(t,e||[])).next())})};class JO{constructor(e,n=GO){this._value=e,this._cancelError=n,this._queue=[],this._weightedWaiters=[]}acquire(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,s)=>{const a={resolve:r,reject:s,weight:e,priority:n},o=Du(this._queue,c=>n<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return WO(this,arguments,void 0,function*(n,r=1,s=0){const[a,o]=yield this.acquire(r,s);try{return yield n(a)}finally{o()}})}waitForUnlock(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,n)?Promise.resolve():new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),KO(this._weightedWaiters[e-1],{resolve:r,priority:n})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const n=this._value;this._value-=e.weight,e.resolve([n,this._newReleaser(e.weight)])}_newReleaser(e){let n=!1;return()=>{n||(n=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const n=this._weightedWaiters[e-1];n&&(n.forEach(r=>r.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let n=this._value;n>0;n--){const r=this._weightedWaiters[n-1];if(!r)continue;const s=r.findIndex(a=>a.priority<=e);(s===-1?r:r.splice(0,s)).forEach((a=>a.resolve()))}}}_couldLockImmediately(e,n){return(this._queue.length===0||this._queue[0].priority<n)&&e<=this._value}}function KO(t,e){const n=Du(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function Du(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var XO=function(t,e,n,r){function s(a){return a instanceof n?a:new n(function(o){o(a)})}return new(n||(n=Promise))(function(a,o){function c(h){try{l(r.next(h))}catch(d){o(d)}}function u(h){try{l(r.throw(h))}catch(d){o(d)}}function l(h){h.done?a(h.value):s(h.value).then(c,u)}l((r=r.apply(t,e||[])).next())})};class QO{constructor(e){this._semaphore=new JO(1,e)}acquire(){return XO(this,arguments,void 0,function*(e=0){const[,n]=yield this._semaphore.acquire(1,e);return n})}runExclusive(e,n=0){return this._semaphore.runExclusive(()=>e(),1,n)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const nt=Nc.keyZ,mn=Nc.labelZ,eS="labeled_by",tS="sy_label_set",nS="sy_label_delete",Bu=mn.extend({key:nt.optional()}),rS=i.object({labels:Bu.array()}),sS=i.object({labels:mn.array()}),iS=i.object({keys:nt.array()}),qu=i.object({id:B,labels:nt.array(),replace:i.boolean().optional()}),aS=qu.omit({replace:!0}),Cr=i.object({}),oS=i.object({keys:nt.array().optional(),names:i.string().array().optional(),for:B.optional(),searchTerm:i.string().optional(),offset:i.int().optional(),limit:i.int().optional()}),cS=i.object({key:nt}).transform(({key:t})=>({keys:[t]})),uS=i.union([cS,oS]),lS=i.object({labels:E.nullableZ(mn)});let Fu=class{type="label";client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await T(this.client,"/label/retrieve",e,uS,lS);return ue("Label",e,r.labels,n),n?r.labels[0]:r.labels}async label(e,n,r={}){await T(this.client,"/label/set",{id:e,labels:n,replace:r.replace},qu,Cr)}async remove(e,n){await T(this.client,"/label/remove",{id:e,labels:n},aS,Cr)}async create(e){const n=Array.isArray(e),r=await T(this.client,"/label/create",{labels:E.toArray(e)},rS,sS);return n?r.labels:r.labels[0]}async delete(e){await T(this.client,"/label/delete",{keys:E.toArray(e)},iS,Cr)}};const Yu=J("label"),hS=Yu(""),fS=Object.freeze(Object.defineProperty({__proto__:null,Client:Fu,DELETE_CHANNEL_NAME:nS,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:eS,SET_CHANNEL_NAME:tS,TYPE_ONTOLOGY_ID:hS,keyZ:nt,labelZ:mn,newZ:Bu,ontologyID:Yu},Symbol.toStringTag,{value:"Module"})),X=i.z.uuid(),fi=i.z.string().min(1),gn=i.z.object({key:X,name:fi,timeRange:x.z.refine(({isValid:t})=>t,{error:"Time range start time must be before or equal to time range end time"}).refine(({end:t})=>t.valueOf()<=Xr.MAX_INT64,{error:"Time range end time must be less than or equal to the maximum value of an int64"}).refine(({start:t})=>t.valueOf()>=Xr.MIN_INT64,{error:"Time range start time must be greater than or equal to the minimum value of an int64"}),color:yc.colorZ.optional(),labels:mn.array().or(i.z.null().transform(()=>{})).optional(),get parent(){return gn.optional().nullable().transform(t=>t===void 0?null:t)}}),Hu=gn.omit({parent:!0,labels:!0}).partial({key:!0}),dS=i.z.object({nodeKey:be.uint12.optional(),keys:L.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),rangeKey:X.optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),dataTypes:p.z.array().optional(),notDataTypes:p.z.array().optional(),virtual:i.z.boolean().optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional(),legacyCalculated:i.z.boolean().optional()}),pS=i.z.object({channels:E.nullableZ(_t)}),ve=t=>(Array.isArray(t)&&t.length>0&&typeof t[0]=="object"?t=t.map(e=>e.key):typeof t=="object"&&"key"in t&&(t=[t.key]),AO(t,{number:"keys",string:"names"}));class di{client;constructor(e){this.client=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const r=ve(e),{variant:s}=r;let{normalized:a}=r;return s==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[s]:a,...n})}async execute(e){return(await T(this.client,"/channel/retrieve",e,dS,pS)).channels}}class pi{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:r}=ve(e),s=[],a=[];if(r.forEach(c=>{const u=this.get(c);u!=null?s.push(...u):a.push(c)}),a.length===0)return s;const o=await this.wrapped.retrieve(a,n);return this.set(o),s.concat(o)}delete(e){const{variant:n,normalized:r}=ve(e);n==="names"?r.forEach(s=>{const a=this.namesToKeys.get(s);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(s))}):r.forEach(s=>{const a=this.cache.get(s);a!=null&&(this.cache.delete(s),this.namesToKeys.delete(a.name))})}rename(e,n){e.forEach((r,s)=>{const a=n[s],o=this.cache.get(r);if(o==null)return;this.cache.delete(r);const c=this.namesToKeys.get(o.name);c!=null&&(c.delete(r),c.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(r,o);const u=this.namesToKeys.get(a);u==null?this.namesToKeys.set(a,new Set([r])):u.add(r)})}set(e){e.forEach(n=>{this.cache.set(n.key,n);const r=this.namesToKeys.get(n.name);r==null?this.namesToKeys.set(n.name,new Set([n.key])):r.add(n.key)})}get(e){if(typeof e=="number"){const s=this.cache.get(e);return s==null?void 0:[s]}const n=this.namesToKeys.get(e);if(n==null)return;const r=[];if(n.forEach(s=>{const a=this.cache.get(s);a!=null&&r.push(a)}),r.length!==0)return r}}class Vu{mu=new QO;requests=new Map;wrapped;debouncedRun;constructor(e,n){this.wrapped=e,this.debouncedRun=Zm(()=>{this.run()},n)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n,variant:r}=ve(e);return r==="names"?await this.wrapped.retrieve(n):await new Promise((a,o)=>{this.mu.runExclusive(()=>{this.requests.set(n,{resolve:a,reject:o}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((n,r)=>r.forEach(s=>e.add(s)));try{const n=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((r,s)=>r.resolve(n.filter(a=>s.includes(a.key))))}catch(n){this.requests.forEach(r=>r.reject(n))}finally{this.requests.clear()}})}}const Gu=async(t,e)=>{const{normalized:n}=ve(e),r=await t.retrieve(n),s=[];if(n.forEach(a=>{r.find(o=>o.name===a||o.key===a)==null&&s.push(a)}),s.length>0)throw new Ke(`Could not find channels: ${JSON.stringify(s)}`);return r},wn=i.z.uuid(),Wu=i.z.string(),ar=i.z.object({key:wn,name:Wu}),yS=J("group"),mS="sy_group_set",gS="sy_group_delete",wS=i.object({group:ar}),bS=i.object({parent:B,key:wn.optional(),name:i.string()}),vS=i.object({key:wn,name:i.string()}),zS=i.object({keys:i.array(wn)});let Ju=class{client;constructor(e){this.client=e}async create(e){return(await T(this.client,"/ontology/create-group",e,bS,wS)).group}async rename(e,n){await T(this.client,"/ontology/rename-group",{key:e,name:n},vS,i.object({}))}async delete(e){await T(this.client,"/ontology/delete-group",{keys:E.toArray(e)},zS,i.object({}))}};const TS=Object.freeze(Object.defineProperty({__proto__:null,Client:Ju,DELETE_CHANNEL_NAME:gS,SET_CHANNEL_NAME:mS,groupZ:ar,keyZ:wn,nameZ:Wu,ontologyID:yS},Symbol.toStringTag,{value:"Module"})),OS="sy_channel_set",SS="sy_channel_delete";class Fn{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;operations;status;constructor({dataType:e,name:n,leaseholder:r=0,key:s=0,isIndex:a=!1,index:o=0,internal:c=!1,virtual:u=!1,frameClient:l,alias:h,status:d,expression:f="",operations:b=[]}){this.key=L.parse(s),this.name=n,this.dataType=new p(e),this.leaseholder=r,this.index=L.parse(o),this.isIndex=a,this.internal=c,this.alias=h,this.virtual=u,this.expression=f,this.operations=b,d!=null&&(this.status=Qe.create(d)),this._frameClient=l??null}get framer(){if(this._frameClient==null)throw new W("cannot read from a channel that has not been created");return this._frameClient}get payload(){return _t.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,expression:this.expression,status:this.status,operations:this.operations})}get isCalculated(){return yi(this.payload)}get ontologyID(){return ir(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,n){return await this.framer.write(e,this.key,n)}}const ES=i.z.object({}),NS=i.z.object({group:ar});let Ku=class{frameClient;client;retriever;writer;constructor(e,n,r,s){this.frameClient=e,this.retriever=n,this.client=r,this.writer=s}async create(e,n={}){const{retrieveIfNameExists:r=!1}=n,s=!Array.isArray(e);let a=E.toArray(e),o=[];if(r){const c=await this.retriever.retrieve(a.map(l=>l.name)),u=new Set(c.map(l=>l.name));a=a.filter(l=>!u.has(l.name)),o=this.sugar(c)}return o=o.concat(this.sugar(await this.writer.create(a))),s?o[0]:o}async retrieve(e,n){if(typeof e=="object"&&!Array.isArray(e))return this.sugar(await this.retriever.retrieve(e));const r=!Array.isArray(e),s=this.sugar(await this.retriever.retrieve(e,n));return ue("channel",e,s,r),r?s[0]:s}async delete(e){const{normalized:n,variant:r}=ve(e);return r==="keys"?await this.writer.delete({keys:n}):await this.writer.delete({names:n})}async rename(e,n){return await this.writer.rename(E.toArray(e),E.toArray(n))}createDebouncedBatchRetriever(e=10){return new pi(new Vu(new di(this.client),e))}sugar(e){const{frameClient:n}=this;return Array.isArray(e)?e.map(r=>new Fn({...r,frameClient:n})):new Fn({...e,frameClient:n})}async retrieveGroup(){return(await T(this.client,"/channel/retrieve-group",{},ES,NS)).group}};const yi=({virtual:t,expression:e})=>t&&e!=="",$S=i.z.object({channels:Lu.array()}),kS=i.z.object({channels:_t.array()}),AS=i.z.object({keys:L.array().optional(),names:Pe.array().optional()}),IS=i.z.object({}),ZS=i.z.object({keys:L.array(),names:Pe.array()}),xS=i.z.object({});let Xu=class{client;cache;constructor(e,n){this.client=e,this.cache=n}async create(e){const{channels:n}=await T(this.client,"/channel/create",{channels:e.map(r=>({...r,dataType:r.dataType}))},$S,kS);return this.cache.set(n),n}async delete(e){const n=L.array().parse(e.keys??[]);await T(this.client,"/channel/delete",e,AS,IS),n.length>0&&this.cache.delete(n),e.names!=null&&this.cache.delete(e.names)}async rename(e,n){await T(this.client,"/channel/rename",{keys:e,names:n},ZS,xS),this.cache.rename(e,n)}};const CS=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:pi,Channel:Fn,Client:Ku,ClusterRetriever:di,DELETE_CHANNEL_NAME:SS,DebouncedBatchRetriever:Vu,OPERATION_TYPES:Ru,SET_CHANNEL_NAME:OS,TYPE_ONTOLOGY_ID:FO,Writer:Xu,analyzeParams:ve,calculationStatusDetailsZ:Pu,calculationStatusZ:BO,escapeInvalidName:VO,isCalculated:yi,keyZ:L,nameZ:Pe,newZ:Lu,ontologyID:ir,operationType:ju,operationZ:hi,paramsZ:mt,payloadZ:_t,retrieveRequired:Gu,statusKey:qO,statusZ:Uu},Symbol.toStringTag,{value:"Module"})),_S=i.z.object({username:i.z.string(),password:i.z.string()}),MS=i.z.object({token:i.z.string(),user:pn}),Oa="/auth/login",RS=3,jS=i.z.object({username:i.z.string(),password:i.z.string(),newPassword:i.z.string().min(1)}),US=i.z.object({}),PS=[cs,us];let LS=class{client;credentials;authState={authenticated:!1};authenticating;retryCount;constructor(e,n){this.client=e,this.credentials=n,this.retryCount=0}get authenticated(){return this.authState.authenticated}get user(){return this.authState.authenticated?this.authState.user:void 0}get token(){return this.authState.authenticated?this.authState.token:void 0}async retrieveUser(){this.authState.authenticated||await this.authenticating;const{authState:e}=this;if(!e.authenticated)throw new Error("Authentication failed: user not available");return e.user}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await T(this.client,"/auth/change-password",{username:this.credentials.username,password:this.credentials.password,newPassword:e},jS,US),this.credentials.password=e}middleware(){const e=async(n,r)=>{if(!this.authenticated&&!n.target.endsWith(Oa)){this.authenticating??=new Promise((c,u)=>{this.client.send(Oa,this.credentials,_S,MS).then(([l,h])=>{if(h!=null)return c(h);if(l==null)return c(new Error("No response from login"));this.authState={authenticated:!0,user:l.user,token:l.token},c(null)}).catch(u)});const o=await this.authenticating;if(o!=null)return[n,o]}n.params.Authorization=`Bearer ${this.token}`;const[s,a]=await r(n);return PS.some(o=>o.matches(a))&&this.retryCount<RS?(this.authState={authenticated:!1},this.authenticating=void 0,this.retryCount+=1,e(n,r)):(this.retryCount=0,[s,a])};return e}};const Qu=i.z.enum(["disconnected","connecting","connected","failed"]),el=i.z.object({status:Qu,error:i.z.instanceof(Error).optional(),message:i.z.string().optional(),clusterKey:i.z.string(),clientVersion:i.z.string(),clientServerCompatible:i.z.boolean(),nodeVersion:i.z.string().optional()}),DS=i.z.object({clusterKey:i.z.string(),nodeVersion:i.z.string().optional()}),BS=i.z.void(),Sa={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.53.0"},Ea=(t,e,n)=>{const r=n?"Core":"client";return`Synnax Core version ${t!=null?`${t} `:""}is too ${n?"old":"new"} for client version ${e}.
41
65
  This may cause compatibility issues. We recommend updating the ${r}. For more information, see
42
- https://docs.synnaxlabs.com/reference/client/resources/troubleshooting#old-${r}-version`};class _n{static DEFAULT=ca;_state;pollFrequency=m.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=Iu;versionWarned=!1;constructor(e,n=m.seconds(30),r,s){this._state={...ca},this.client=e,this.pollFrequency=n,this.clientVersion=r,this.name=s,this.check(),this.start()}stop(){this.interval!=null&&clearInterval(this.interval)}async check(){const e=this._state.status;try{const n=await z(this.client,"/connectivity/check",void 0,$O,AO),r=n.nodeVersion,s=this.clientVersion,a=this.versionWarned;r==null?(this._state.clientServerCompatible=!1,a||(console.warn(ua(null,s,!0)),this.versionWarned=!0)):Ri.versionsEqual(s,r,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,a||(console.warn(ua(r,s,Ri.semVerNewer(s,r))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}catch(n){this._state.status="failed",this._state.error=n,this._state.message=this.state.error?.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}start(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}}const IO=Object.freeze(Object.defineProperty({__proto__:null,Checker:_n,stateZ:Iu,statusZ:$u},Symbol.toStringTag,{value:"Module"})),ZO=i.z.object({keys:U.array().optional(),bounds:x.z,names:Re.array().optional()}),xO=i.z.object({});class CO{client;constructor(e){this.client=e}async delete(e){await z(this.client,"/frame/delete",e,ZO,xO)}}const la=t=>{const e=N.toArray(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},ha=(t,e)=>{const n=N.toArray(t);if(n.length===e.length)return;const r=la(t);throw la===null?new H("[Frame] - channel keys or names must be provided when constructing a frame."):new H(`[Frame] - ${r}s and series must be the same length.
43
- Got ${n.length} ${r}s and ${e.length} series.`)};class F{columns=[];series=[];constructor(e=[],n=[]){if(e instanceof F){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((s,a)=>this.push(a,...N.toArray(s)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const s=e;s.series??=[],s.keys??=[];const a=s.series.map(o=>Zu(o));ha(s.keys,a),s.keys.forEach((o,c)=>this.push(o,a[c]))}else Object.entries(e).forEach(([s,a])=>{const o=parseInt(s);if(!isNaN(o))return this.push(o,...N.toArray(a));this.push(s,...N.toArray(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const s=N.toArray(n),a=N.toArray(e);ha(a,s),s.forEach((o,c)=>this.push(a[c],o));return}throw new H(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
66
+ https://docs.synnaxlabs.com/reference/client/resources/troubleshooting#old-${r}-version`};class Yn{static DEFAULT=Sa;_state;pollFrequency=w.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=el;versionWarned=!1;constructor(e,n=w.seconds(30),r,s){this._state={...Sa},this.client=e,this.pollFrequency=n,this.clientVersion=r,this.name=s,this.check(),this.start()}stop(){this.interval!=null&&clearInterval(this.interval)}async check(){const e=this._state.status;try{const n=await T(this.client,"/connectivity/check",void 0,BS,DS),r=n.nodeVersion,s=this.clientVersion,a=this.versionWarned;r==null?(this._state.clientServerCompatible=!1,a||(console.warn(Ea(null,s,!0)),this.versionWarned=!0)):Ki.versionsEqual(s,r,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,a||(console.warn(Ea(r,s,Ki.semVerNewer(s,r))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}catch(n){this._state.status="failed",this._state.error=n,this._state.message=this.state.error?.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}start(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}}const qS=Object.freeze(Object.defineProperty({__proto__:null,Checker:Yn,stateZ:el,statusZ:Qu},Symbol.toStringTag,{value:"Module"})),FS=i.z.object({keys:L.array().optional(),bounds:x.z,names:Pe.array().optional()}),YS=i.z.object({});class HS{client;constructor(e){this.client=e}async delete(e){await T(this.client,"/frame/delete",e,FS,YS)}}const Na=t=>{const e=E.toArray(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},$a=(t,e)=>{const n=E.toArray(t);if(n.length===e.length)return;const r=Na(t);throw Na===null?new W("[Frame] - channel keys or names must be provided when constructing a frame."):new W(`[Frame] - ${r}s and series must be the same length.
67
+ Got ${n.length} ${r}s and ${e.length} series.`)};class V{columns=[];series=[];constructor(e=[],n=[]){if(e instanceof V){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((s,a)=>this.push(a,...E.toArray(s)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const s=e;s.series??=[],s.keys??=[];const a=s.series.map(o=>tl(o));$a(s.keys,a),s.keys.forEach((o,c)=>this.push(o,a[c]))}else Object.entries(e).forEach(([s,a])=>{const o=parseInt(s);if(!isNaN(o))return this.push(o,...E.toArray(a));this.push(s,...E.toArray(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const s=E.toArray(n),a=E.toArray(e);$a(a,s),s.forEach((o,c)=>this.push(a[c],o));return}throw new W(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
44
68
  payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
45
- name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new st("colType is not key");return this.columns??[]}get uniqueKeys(){return ki.unique(this.keys)}get names(){if(this.colType==="key")throw new st("colType is not name");return this.columns??[]}get uniqueNames(){return ki.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>xu(e)),keys:[...this.keys]}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(n=>n.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return x.ZERO;const r=w.min(...this.series.map(a=>a.timeRange.start)),s=w.max(...this.series.map(a=>a.timeRange.end));return new x(r,s)}const n=this.get(e);return n==null?x.ZERO:n.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(n=>e.includes(n)):new Ho(this.series.filter((n,r)=>this.columns[r]===e))}push(e,...n){if(e instanceof F){if(e.colType!=null&&this.colType!==null&&e.colType!==this.colType)throw new H("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...n),typeof e=="string"&&this.colType==="key")throw new H("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new H("keyVariant must match");this.columns.push(...Array.from({length:n.length},()=>e))}}concat(e){return new F([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const n=new F;return this.forEach((r,s,a)=>n.push(...e(r,s,a))),n}mapFilter(e){const n=new F;return this.forEach((r,s,a)=>{const[o,c,l]=e(r,s,a);l&&n.push(o,c)}),n}forEach(e){this.columns.forEach((n,r)=>{const s=this.series[r];e(n,s,r)})}forEachUnique(e){this.uniqueColumns.forEach((n,r)=>e(n,this.get(n),r))}at(e,n=!1){const r={};return this.uniqueColumns.forEach(s=>{r[s]=this.get(s).at(e,n)}),r}filter(e){const n=new F;return this.columns.forEach((r,s)=>{const a=this.series[s];e(r,a,s)&&n.push(r,a)}),n}get byteLength(){return new $(this.series.reduce((e,n)=>e.add(n.byteLength),$.ZERO))}get digest(){const e={};return this.keys.forEach((n,r)=>{const s=this.series[r].digest;n in e?e[n].push(s):e[n]=[s]}),e}get length(){return this.series.reduce((e,n)=>e+n.length,0)}toString(){let e=`Frame{
69
+ 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 ct("colType is not key");return this.columns??[]}get uniqueKeys(){return Li.unique(this.keys)}get names(){if(this.colType==="key")throw new ct("colType is not name");return this.columns??[]}get uniqueNames(){return Li.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>nl(e)),keys:[...this.keys]}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(n=>n.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return x.ZERO;const r=m.min(...this.series.map(a=>a.timeRange.start)),s=m.max(...this.series.map(a=>a.timeRange.end));return new x(r,s)}const n=this.get(e);return n==null?x.ZERO:n.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(n=>e.includes(n)):new uc(this.series.filter((n,r)=>this.columns[r]===e))}push(e,...n){if(e instanceof V){if(e.colType!=null&&this.colType!==null&&e.colType!==this.colType)throw new W("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...n),typeof e=="string"&&this.colType==="key")throw new W("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new W("keyVariant must match");this.columns.push(...Array.from({length:n.length},()=>e))}}concat(e){return new V([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const n=new V;return this.forEach((r,s,a)=>n.push(...e(r,s,a))),n}mapFilter(e){const n=new V;return this.forEach((r,s,a)=>{const[o,c,u]=e(r,s,a);u&&n.push(o,c)}),n}forEach(e){this.columns.forEach((n,r)=>{const s=this.series[r];e(n,s,r)})}forEachUnique(e){this.uniqueColumns.forEach((n,r)=>e(n,this.get(n),r))}at(e,n=!1){const r={};return this.uniqueColumns.forEach(s=>{r[s]=this.get(s).at(e,n)}),r}filter(e){const n=new V;return this.columns.forEach((r,s)=>{const a=this.series[s];e(r,a,s)&&n.push(r,a)}),n}get byteLength(){return new I(this.series.reduce((e,n)=>e.add(n.byteLength),I.ZERO))}get digest(){const e={};return this.keys.forEach((n,r)=>{const s=this.series[r].digest;n in e?e[n].push(s):e[n]=[s]}),e}get length(){return this.series.reduce((e,n)=>e+n.length,0)}toString(){let e=`Frame{
46
70
  `;return this.uniqueColumns.forEach(n=>{e+=` ${n}: ${this.get(n).series.map(r=>r.toString()).join(",")}
47
- `}),e+="}",e}}const Hn=i.z.object({keys:i.z.union([i.z.null().transform(()=>[]),i.z.number().array().default([])]),series:i.z.union([i.z.null().transform(()=>[]),Q.crudeZ.array().default([])])}),Zu=t=>{const{dataType:e,data:n,timeRange:r,alignment:s}=t;return new Q({data:n,dataType:e,timeRange:r,glBufferUsage:"static",alignment:s})},xu=t=>({timeRange:t.timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});var Ee=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.SetAuthority=3]="SetAuthority",t))(Ee||{});const fa=t=>t.data.byteLength/t.dataType.density.valueOf(),_O=t=>{const{keys:e,series:n}=t;e.forEach((r,s)=>{n[s].key=r}),n.sort((r,s)=>r.key-s.key),e.sort((r,s)=>r-s),n.forEach(r=>delete r.key)},da=5,ya=4,pa=3,ma=2,ga=1,wa=0,ve=y.TIMESTAMP.density.valueOf(),Le=8,Pe=4,br=4,vr=4,RO=1;class Cu{contentType="application/sy-framer";states=new Map;currState;seqNum=0;constructor(e=[],n=[]){(e.length>0||n.length>0)&&this.update(e,n)}update(e,n){this.seqNum++;const r={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((s,a)=>{const o=n[a];r.keyDataTypes.set(s,o),o.isVariable&&(r.hasVariableDataTypes=!0)}),r.keys.sort(),this.states.set(this.seqNum,r),this.currState=r}throwIfNotUpdated(e){if(this.seqNum<1)throw new H(`
71
+ `}),e+="}",e}}const or=i.z.object({keys:i.z.union([i.z.null().transform(()=>[]),i.z.number().array().default([])]),series:i.z.union([i.z.null().transform(()=>[]),te.crudeZ.array().default([])])}),tl=t=>{const{dataType:e,data:n,timeRange:r,alignment:s}=t;return new te({data:n,dataType:e,timeRange:r,glBufferUsage:"static",alignment:s})},nl=t=>({timeRange:t.timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});var $e=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.SetAuthority=3]="SetAuthority",t))($e||{});const ka=t=>t.data.byteLength/t.dataType.density.valueOf(),VS=t=>{const{keys:e,series:n}=t;e.forEach((r,s)=>{n[s].key=r}),n.sort((r,s)=>r.key-s.key),e.sort((r,s)=>r-s),n.forEach(r=>delete r.key)},Aa=5,Ia=4,Za=3,xa=2,Ca=1,_a=0,Oe=p.TIMESTAMP.density.valueOf(),Fe=8,Ye=4,_r=4,Mr=4,GS=1;class rl{contentType="application/sy-framer";states=new Map;currState;seqNum=0;constructor(e=[],n=[]){(e.length>0||n.length>0)&&this.update(e,n)}update(e,n){this.seqNum++;const r={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((s,a)=>{const o=n[a];r.keyDataTypes.set(s,o),o.isVariable&&(r.hasVariableDataTypes=!0)}),r.keys.sort(),this.states.set(this.seqNum,r),this.currState=r}throwIfNotUpdated(e){if(this.seqNum<1)throw new W(`
48
72
  The codec has not been updated with a list of channels and data types.
49
73
  Please call the update method before calling ${e}.
50
- `)}encode(e,n=0){this.throwIfNotUpdated("encode");let r=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(r=e.toPayload()),_O(r);let s=-1,a,o,c,l=n+RO+vr,u=!this.currState?.hasVariableDataTypes,h=!0,d=!0,f=!0,O=!0,S=!0;r.keys.length!==this.currState?.keys.length&&(f=!1,l+=r.keys.length*br),r.series.forEach((A,D)=>{const _=fa(A),j=r.keys[D],ae=this.currState?.keyDataTypes.get(j);if(ae==null)throw new H(`Channel ${j} was not provided in the list of channels when opening the writer`);if(!ae.equals(A.dataType))throw new H(`Series data type of ${A.dataType.toString()} does not match the data type of ${ae.toString()} for channel ${j}`);if(l+=A.data.byteLength,s===-1){s=_,a=A.timeRange?.start,o=A.timeRange?.end,c=BigInt(A.alignment??0n);return}s!==_&&(u=!1),(a?.valueOf()!==A.timeRange?.start.valueOf()||o?.valueOf()!==A.timeRange?.end.valueOf())&&(h=!1),c!==BigInt(A.alignment??0)&&(O=!1)}),d=h&&a==null&&o==null,S=O&&(c===void 0||c===0n),u?l+=Pe:l+=r.keys.length*Pe,d||(h?l+=ve*2:l+=r.keys.length*ve*2),S||(O?l+=Le:l+=r.keys.length*Le);const Z=new Uint8Array(l),T=new DataView(Z.buffer);let E=n;return Z[E]=Number(S)<<da|Number(O)<<ya|Number(u)<<pa|Number(h)<<ma|Number(d)<<ga|Number(f)<<wa,E++,T.setUint32(E,this.seqNum,!0),E+=vr,u&&(T.setUint32(E,s,!0),E+=Pe),h&&!d&&(T.setBigUint64(E,a?.valueOf()??0n,!0),T.setBigUint64(E,o?.valueOf()??0n,!0),E+=ve*2),O&&!S&&(T.setBigUint64(E,c??0n,!0),E+=Le),r.series.forEach((A,D)=>{if(f||(T.setUint32(E,r.keys[D],!0),E+=br),!u){let _=A.data.byteLength;A.dataType.isVariable||(_=fa(A)),T.setUint32(E,_,!0),E+=Pe}Z.set(new Uint8Array(A.data),E),E+=A.data.byteLength,!h&&!d&&(T.setBigUint64(E,A.timeRange?.start.valueOf()??0n,!0),T.setBigUint64(E,A.timeRange?.end.valueOf()??0n,!0),E+=ve*2),!O&&!S&&(T.setBigUint64(E,A.alignment??0n,!0),E+=Le)}),Z}decode(e,n=0){this.throwIfNotUpdated("decode");const r=e instanceof Uint8Array?e:new Uint8Array(e),s={keys:[],series:[]};let a=n,o=0,c=0,l,u,h;const d=new DataView(r.buffer,r.byteOffset,r.byteLength),f=!!(r[a]>>da&1),O=!!(r[a]>>ya&1),S=!!(r[a]>>pa&1),Z=!!(r[a]>>ma&1),T=!!(r[a]>>ga&1),E=!!(r[a]>>wa&1);a++;const A=d.getUint32(a,!0);a+=vr;const D=this.states.get(A);if(D==null)return s;if(S){if(a+Pe>d.byteLength)return s;o=d.getUint32(a,!0),a+=Pe}if(Z&&!T){if(a+ve>d.byteLength)return s;l=new w(d.getBigUint64(a,!0)),a+=ve,u=new w(d.getBigUint64(a,!0)),a+=ve}if(O&&!f){if(a+Le>d.byteLength)return s;h=d.getBigUint64(a,!0),a+=Le}return E&&(s.keys=[...D.keys]),D.keys.forEach((_,j)=>{if(!E){if(a>=d.byteLength||d.getUint32(a,!0)!==_)return;a+=br,s.keys.push(_)}const ae=D.keyDataTypes.get(_);if(c=0,S)c=o;else{if(a+Pe>d.byteLength)return;c=d.getUint32(a,!0),a+=Pe}let oe=c;if(ae.isVariable||(oe*=ae.density.valueOf()),a+oe>d.byteLength){s.keys.splice(j,1);return}const ye={dataType:ae,data:r.slice(a,a+oe).buffer};if(a+=oe,!Z&&!T){if(a+ve*2>d.byteLength)return;const pi=d.getBigUint64(a,!0);a+=ve;const ch=d.getBigUint64(a,!0);a+=ve,ye.timeRange=new x({start:pi,end:ch})}else T?ye.timeRange=new x({start:0n,end:0n}):ye.timeRange=new x({start:l?.valueOf()??0n,end:u?.valueOf()??0n});if(!O&&!f){if(a+Le>d.byteLength)return;h=d.getBigUint64(a,!0),a+=Le,ye.alignment=h}else f?ye.alignment=0n:ye.alignment=h;s.series.push(ye)}),s}}const ni=254,jO=new Uint8Array([ni]),MO=255,UO=new Uint8Array([MO]),_u="application/sy-framer";class DO{contentType=_u;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=ut.JSON_CODEC}encode(e){const n=e;if(n.type=="close"||n.payload?.command!=Ee.Write){const s=this.lowPerfCodec.encode(n),a=new Uint8Array({length:s.byteLength+1});return a.set(jO,0),a.set(new Uint8Array(s),1),a}const r=this.base.encode(n.payload?.frame,1);return r.set(UO,0),r}decode(e,n){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===ni)return this.lowPerfCodec.decode(e.slice(1),n);const a={type:"data"},o=this.base.decode(e,1);return a.payload={command:Ee.Write,frame:o},a}}class LO{contentType=_u;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=ut.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,n){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===ni?this.lowPerfCodec.decode(e.slice(1),n):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class Vn{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=new Set,this.codec=new Cu}static async open(e,n){const r=new Vn(e);return await r.update(n),r}async update(e){const{variant:n,normalized:r}=ge(e),s=await this.retriever.retrieve(r),a=s.map(c=>c.key);if(Ai.uniqueUnorderedPrimitiveArrays(Array.from(this.keys),a)===Ai.EQUAL)return!1;if(this.codec.update(a,s.map(c=>c.dataType)),n==="keys")return this.adapter=null,this.keys=new Set(r),!0;const o=new Map;return this.adapter=o,r.forEach(c=>{const l=s.find(u=>u.name===c);if(l==null)throw new Error(`Channel ${c} not found`);o.set(l.key,l.name)}),this.keys=new Set(this.adapter.keys()),!0}adapt(e){if(this.adapter==null){let r=!1;return e.forEach(s=>{this.keys.has(s)||(r=!0)}),r?e.filter(s=>this.keys.has(s)):e}const n=this.adapter;return e.mapFilter((r,s)=>{if(typeof r=="number"){const a=n.get(r);return a==null?[r,s,!1]:[a,s,!0]}return[r,s,!0]})}}class ri{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new Cu}static async open(e,n){const r=new ri(e);return await r.update(n),r}async adaptParams(e){const n=yt.parse(e);return await Promise.all(n.map(async s=>await this.adaptToKey(s)))}async update(e){const n=await Su(this.retriever,e),r=n.map(u=>u.key),s=new Set(this.keys),a=new Set(r),o=!a.isSubsetOf(s),c=!s.isSubsetOf(a);return o||c?(this.adapter=new Map(n.map(u=>[u.name,u.key])),this.keys=r,this.codec.update(this.keys,n.map(u=>u.dataType)),!0):!1}async fetchChannel(e){const n=await this.retriever.retrieve(e);if(n.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return n[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}encode(e){return this.codec.encode(e.toPayload())}async adapt(e,n){if(typeof e=="string"||typeof e=="number"){if(n==null)throw new H(`
74
+ `)}encode(e,n=0){this.throwIfNotUpdated("encode");let r=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(r=e.toPayload()),VS(r);let s=-1,a,o,c,u=n+GS+Mr,l=!this.currState?.hasVariableDataTypes,h=!0,d=!0,f=!0,b=!0,N=!0;r.keys.length!==this.currState?.keys.length&&(f=!1,u+=r.keys.length*_r),r.series.forEach((A,D)=>{const C=ka(A),_=r.keys[D],le=this.currState?.keyDataTypes.get(_);if(le==null)throw new W(`Channel ${_} was not provided in the list of channels when opening the writer`);if(!le.equals(A.dataType))throw new W(`Series data type of ${A.dataType.toString()} does not match the data type of ${le.toString()} for channel ${_}`);if(u+=A.data.byteLength,s===-1){s=C,a=A.timeRange?.start,o=A.timeRange?.end,c=BigInt(A.alignment??0n);return}s!==C&&(l=!1),(a?.valueOf()!==A.timeRange?.start.valueOf()||o?.valueOf()!==A.timeRange?.end.valueOf())&&(h=!1),c!==BigInt(A.alignment??0)&&(b=!1)}),d=h&&a==null&&o==null,N=b&&(c===void 0||c===0n),l?u+=Ye:u+=r.keys.length*Ye,d||(h?u+=Oe*2:u+=r.keys.length*Oe*2),N||(b?u+=Fe:u+=r.keys.length*Fe);const k=new Uint8Array(u),O=new DataView(k.buffer);let S=n;return k[S]=Number(N)<<Aa|Number(b)<<Ia|Number(l)<<Za|Number(h)<<xa|Number(d)<<Ca|Number(f)<<_a,S++,O.setUint32(S,this.seqNum,!0),S+=Mr,l&&(O.setUint32(S,s,!0),S+=Ye),h&&!d&&(O.setBigUint64(S,a?.valueOf()??0n,!0),O.setBigUint64(S,o?.valueOf()??0n,!0),S+=Oe*2),b&&!N&&(O.setBigUint64(S,c??0n,!0),S+=Fe),r.series.forEach((A,D)=>{if(f||(O.setUint32(S,r.keys[D],!0),S+=_r),!l){let C=A.data.byteLength;A.dataType.isVariable||(C=ka(A)),O.setUint32(S,C,!0),S+=Ye}k.set(new Uint8Array(A.data),S),S+=A.data.byteLength,!h&&!d&&(O.setBigUint64(S,A.timeRange?.start.valueOf()??0n,!0),O.setBigUint64(S,A.timeRange?.end.valueOf()??0n,!0),S+=Oe*2),!b&&!N&&(O.setBigUint64(S,A.alignment??0n,!0),S+=Fe)}),k}decode(e,n=0){this.throwIfNotUpdated("decode");const r=e instanceof Uint8Array?e:new Uint8Array(e),s={keys:[],series:[]};let a=n,o=0,c=0,u,l,h;const d=new DataView(r.buffer,r.byteOffset,r.byteLength),f=!!(r[a]>>Aa&1),b=!!(r[a]>>Ia&1),N=!!(r[a]>>Za&1),k=!!(r[a]>>xa&1),O=!!(r[a]>>Ca&1),S=!!(r[a]>>_a&1);a++;const A=d.getUint32(a,!0);a+=Mr;const D=this.states.get(A);if(D==null)return s;if(N){if(a+Ye>d.byteLength)return s;o=d.getUint32(a,!0),a+=Ye}if(k&&!O){if(a+Oe>d.byteLength)return s;u=new m(d.getBigUint64(a,!0)),a+=Oe,l=new m(d.getBigUint64(a,!0)),a+=Oe}if(b&&!f){if(a+Fe>d.byteLength)return s;h=d.getBigUint64(a,!0),a+=Fe}return S&&(s.keys=[...D.keys]),D.keys.forEach((C,_)=>{if(!S){if(a>=d.byteLength||d.getUint32(a,!0)!==C)return;a+=_r,s.keys.push(C)}const le=D.keyDataTypes.get(C);if(c=0,N)c=o;else{if(a+Ye>d.byteLength)return;c=d.getUint32(a,!0),a+=Ye}let ae=c;if(le.isVariable||(ae*=le.density.valueOf()),a+ae>d.byteLength){s.keys.splice(_,1);return}const ge={dataType:le,data:r.slice(a,a+ae).buffer};if(a+=ae,!k&&!O){if(a+Oe*2>d.byteLength)return;const ki=d.getBigUint64(a,!0);a+=Oe;const Uh=d.getBigUint64(a,!0);a+=Oe,ge.timeRange=new x({start:ki,end:Uh})}else O?ge.timeRange=new x({start:0n,end:0n}):ge.timeRange=new x({start:u?.valueOf()??0n,end:l?.valueOf()??0n});if(!b&&!f){if(a+Fe>d.byteLength)return;h=d.getBigUint64(a,!0),a+=Fe,ge.alignment=h}else f?ge.alignment=0n:ge.alignment=h;s.series.push(ge)}),s}}const mi=254,WS=new Uint8Array([mi]),JS=255,KS=new Uint8Array([JS]),sl="application/sy-framer";class XS{contentType=sl;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=Jn.JSON_CODEC}encode(e){const n=e;if(n.type=="close"||n.payload?.command!=$e.Write){const s=this.lowPerfCodec.encode(n),a=new Uint8Array({length:s.byteLength+1});return a.set(WS,0),a.set(new Uint8Array(s),1),a}const r=this.base.encode(n.payload?.frame,1);return r.set(KS,0),r}decode(e,n){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===mi)return this.lowPerfCodec.decode(e.slice(1),n);const a={type:"data"},o=this.base.decode(e,1);return a.payload={command:$e.Write,frame:o},a}}class QS{contentType=sl;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=Jn.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,n){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===mi?this.lowPerfCodec.decode(e.slice(1),n):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class cr{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=new Set,this.codec=new rl}static async open(e,n){const r=new cr(e);return await r.update(n),r}async update(e){const{variant:n,normalized:r}=ve(e),s=await this.retriever.retrieve(r),a=s.map(c=>c.key);if(Di.uniqueUnorderedPrimitiveArrays(Array.from(this.keys),a)===Di.EQUAL)return!1;if(this.codec.update(a,s.map(c=>c.dataType)),n==="keys")return this.adapter=null,this.keys=new Set(r),!0;const o=new Map;return this.adapter=o,r.forEach(c=>{const u=s.find(l=>l.name===c);if(u==null)throw new Error(`Channel ${c} not found`);o.set(u.key,u.name)}),this.keys=new Set(this.adapter.keys()),!0}adapt(e){if(this.adapter==null){let r=!1;return e.forEach(s=>{this.keys.has(s)||(r=!0)}),r?e.filter(s=>this.keys.has(s)):e}const n=this.adapter;return e.mapFilter((r,s)=>{if(typeof r=="number"){const a=n.get(r);return a==null?[r,s,!1]:[a,s,!0]}return[r,s,!0]})}}class gi{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new rl}static async open(e,n){const r=new gi(e);return await r.update(n),r}async adaptParams(e){const n=mt.parse(e);return await Promise.all(n.map(async s=>await this.adaptToKey(s)))}async update(e){const n=await Gu(this.retriever,e),r=n.map(l=>l.key),s=new Set(this.keys),a=new Set(r),o=!a.isSubsetOf(s),c=!s.isSubsetOf(a);return o||c?(this.adapter=new Map(n.map(l=>[l.name,l.key])),this.keys=r,this.codec.update(this.keys,n.map(l=>l.dataType)),!0):!1}async fetchChannel(e){const n=await this.retriever.retrieve(e);if(n.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return n[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}encode(e){return this.codec.encode(e.toPayload())}async adapt(e,n){if(typeof e=="string"||typeof e=="number"){if(n==null)throw new W(`
51
75
  Received a single channel name or key but no series.
52
- `);if(Array.isArray(n)){if(n.some(l=>l instanceof Q||Array.isArray(l)))throw new H(`
76
+ `);if(Array.isArray(n)){if(n.some(u=>u instanceof te||Array.isArray(u)))throw new W(`
53
77
  Received a single channel name or key but multiple series.
54
- `);n=n}const o=await this.fetchChannel(e),c=new Q({data:n,dataType:o.dataType});return new F(o.key,c)}if(Array.isArray(e)){if(n==null)throw new H(`
78
+ `);n=n}const o=await this.fetchChannel(e),c=new te({data:n,dataType:o.dataType});return new V(o.key,c)}if(Array.isArray(e)){if(n==null)throw new W(`
55
79
  Received an array of channel names or keys but no series.
56
- `);if(!Array.isArray(n))throw new H(`
80
+ `);if(!Array.isArray(n))throw new W(`
57
81
  Received an array of channel names or keys but no array of series.
58
- `);const o=[],c=[];for(let l=0;l<e.length;l++){const u=await this.fetchChannel(e[l]);if(l>=n.length)throw new H(`
82
+ `);const o=[],c=[];for(let u=0;u<e.length;u++){const l=await this.fetchChannel(e[u]);if(u>=n.length)throw new W(`
59
83
  Received an array of channel names or keys but not enough series.
60
- `);const h=new Q({data:n[l],dataType:u.dataType});o.push(u.key),c.push(h)}return new F(o,c)}if(e instanceof F||e instanceof Map){const o=new F(e);if(this.adapter==null)return o;const c=o.columns.map(l=>{const u=typeof l=="string"?this.adapter?.get(l):l;if(u==null)throw new H(`
61
- Channel ${l} was not provided in the list of channels when opening the writer
62
- `);return u});return new F(c,o.series)}const r=[],s=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[c,l]=a[o],u=await this.fetchChannel(c),h=new Q({data:l,dataType:u.dataType});r.push(u.key),s.push(h)}return new F(r,s)}}class Ru{name;stream;constructor(e,n){this.stream=n,this.name=e}async receive(){const[e,n]=await this.stream.receive();if(n!=null)throw n;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,n]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on ${JSON.stringify(e)} closure.
63
- Please report this error to the Synnax team.`),n!=null){if(we.matches(n))return;throw n}}}closeSend(){this.stream.closeSend()}send(e){const n=this.stream.send(e);if(n!=null)throw n}}const Rn=new m(-1);var si=(t=>(t[t.Open=0]="Open",t[t.Next=1]="Next",t[t.Prev=2]="Prev",t[t.SeekFirst=3]="SeekFirst",t[t.SeekLast=4]="SeekLast",t[t.SeekLE=5]="SeekLE",t[t.SeekGE=6]="SeekGE",t[t.Valid=7]="Valid",t[t.Error=8]="Error",t))(si||{}),ju=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(ju||{});const PO=i.z.object({command:i.z.enum(si),span:m.z.optional(),bounds:x.z.optional(),stamp:w.z.optional(),keys:U.array().optional(),chunkSize:i.z.number().optional(),downsampleFactor:i.z.int().optional()}),BO=i.z.object({variant:i.z.enum(ju),ack:i.z.boolean(),command:i.z.enum(si),error:je.payloadZ.optional().nullable(),frame:Hn.optional()});class fn{stream;adapter;value;constructor(e,n){this.stream=new Ru("Iterator",e),this.value=new F,this.adapter=n}static async _open(e,n,r,s,a={}){const o=await Vn.open(r,n),c=await s.stream("/frame/iterate",PO,BO),l=new fn(c,o);return await l.execute({command:0,keys:Array.from(o.keys),bounds:new x(e),chunkSize:a.chunkSize??1e5,downsampleFactor:a.downsampleFactor??1}),l}async next(e=Rn){return await this.execute({command:1,span:new m(e)})}async prev(e=Rn){return await this.execute({command:2,span:new m(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new w(e)})}async seekGE(e){return await this.execute({command:6,stamp:new w(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new qO(this)}async execute(e){for(this.stream.send(e),this.value=new F;;){const n=await this.stream.receive();if(n.variant===1)return n.ack;this.value.push(this.adapter.adapt(new F(n.frame)))}}}class qO{iter;open=!1;constructor(e){this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}class Mu{retriever;streamClient;constructor(e,n){this.retriever=e,this.streamClient=n}async read(e){const{channels:n,timeRange:r,channelNames:s,iteratorConfig:a}=e,o=await this.retriever.retrieve(n),c=new Set;o.forEach(h=>{c.add(h.key),h.index!==0&&c.add(h.index)});const l=Array.from(c).filter(h=>!o.some(d=>d.key===h));if(l.length>0){const h=await this.retriever.retrieve(l);o.push(...h)}const u=await fn._open(r,Array.from(c),this.retriever,this.streamClient,a);return FO({iterator:u,channelPayloads:o,headers:s})}}const FO=({iterator:t,channelPayloads:e,headers:n})=>{const r=Om.getOS()==="Windows"?`\r
84
+ `);const h=new te({data:n[u],dataType:l.dataType});o.push(l.key),c.push(h)}return new V(o,c)}if(e instanceof V||e instanceof Map){const o=new V(e);if(this.adapter==null)return o;const c=o.columns.map(u=>{const l=typeof u=="string"?this.adapter?.get(u):u;if(l==null)throw new W(`
85
+ Channel ${u} was not provided in the list of channels when opening the writer
86
+ `);return l});return new V(c,o.series)}const r=[],s=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[c,u]=a[o],l=await this.fetchChannel(c),h=new te({data:u,dataType:l.dataType});r.push(l.key),s.push(h)}return new V(r,s)}}class il{name;stream;constructor(e,n){this.stream=n,this.name=e}async receive(){const[e,n]=await this.stream.receive();if(n!=null)throw n;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,n]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on ${JSON.stringify(e)} closure.
87
+ Please report this error to the Synnax team.`),n!=null){if(ze.matches(n))return;throw n}}}closeSend(){this.stream.closeSend()}send(e){const n=this.stream.send(e);if(n!=null)throw n}}const Hn=new w(-1);var wi=(t=>(t[t.Open=0]="Open",t[t.Next=1]="Next",t[t.Prev=2]="Prev",t[t.SeekFirst=3]="SeekFirst",t[t.SeekLast=4]="SeekLast",t[t.SeekLE=5]="SeekLE",t[t.SeekGE=6]="SeekGE",t[t.Valid=7]="Valid",t[t.Error=8]="Error",t))(wi||{}),al=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(al||{});const e0=i.z.object({command:i.z.enum(wi),span:w.z.optional(),bounds:x.z.optional(),stamp:m.z.optional(),keys:L.array().optional(),chunkSize:i.z.number().optional(),downsampleFactor:i.z.int().optional()}),t0=i.z.object({variant:i.z.enum(al),ack:i.z.boolean(),command:i.z.enum(wi),error:Le.payloadZ.optional().nullable(),frame:or.optional()});class bn{stream;adapter;value;constructor(e,n){this.stream=new il("Iterator",e),this.value=new V,this.adapter=n}static async _open(e,n,r,s,a={}){const o=await cr.open(r,n),c=await s.stream("/frame/iterate",e0,t0),u=new bn(c,o);return await u.execute({command:0,keys:Array.from(o.keys),bounds:new x(e),chunkSize:a.chunkSize??1e5,downsampleFactor:a.downsampleFactor??1}),u}async next(e=Hn){return await this.execute({command:1,span:new w(e)})}async prev(e=Hn){return await this.execute({command:2,span:new w(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new m(e)})}async seekGE(e){return await this.execute({command:6,stamp:new m(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new n0(this)}async execute(e){for(this.stream.send(e),this.value=new V;;){const n=await this.stream.receive();if(n.variant===1)return n.ack;this.value.push(this.adapter.adapt(new V(n.frame)))}}}class n0{iter;open=!1;constructor(e){this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}class ol{retriever;streamClient;constructor(e,n){this.retriever=e,this.streamClient=n}async read(e){const{channels:n,timeRange:r,channelNames:s,iteratorConfig:a}=e,o=await this.retriever.retrieve(n),c=new Set;o.forEach(h=>{c.add(h.key),h.index!==0&&c.add(h.index)});const u=Array.from(c).filter(h=>!o.some(d=>d.key===h));if(u.length>0){const h=await this.retriever.retrieve(u);o.push(...h)}const l=await bn._open(r,Array.from(c),this.retriever,this.streamClient,a);return r0({iterator:l,channelPayloads:o,headers:s})}}const r0=({iterator:t,channelPayloads:e,headers:n})=>{const r=lg.getOS()==="Windows"?`\r
64
88
  `:`
65
- `,s=new TextEncoder;let a=!1,o=!1;const c=YO(e),{columns:l,columnsByIndexKey:u,emptyGroupStrings:h}=GO(e,c,n);let d=[],f=0,O=[];const S=T=>{for(const[E]of c){const A=T.get(E);if(A.length===0)continue;const _=(u.get(E)??[]).map(j=>T.get(j.key));for(let j=0;j<A.length;j++){const ae=A.at(j,!0),oe=_.map(ye=>_i.formatValue(ye.at(j,!0)));O.push({time:ae,values:oe,indexKey:E})}}},Z=(T,E=!1)=>{O.length>0&&(O.sort((_,j)=>Number(_.time-j.time)),f>0&&(d=d.slice(f),f=0),d=HO(d,O),O=[]);const A=[],D=d.length;for(;f<D&&A.length<T;){const _=d[f].time;if(!E&&d[D-1].time===_)break;const j=new Map;for(;f<D&&d[f].time===_;){const oe=d[f++];j.set(oe.indexKey,oe)}const ae=[];for(const[oe]of c){const ye=j.get(oe);ae.push(ye?.values.join(",")??h.get(oe)??"")}A.push(ae.join(","))}return A};return new ReadableStream({async pull(T){try{if(o||(await t.seekFirst(),o=!0),!a){const _=l.map(j=>_i.formatValue(j.header)).join(",");T.enqueue(s.encode(`${_}${r}`)),a=!0}d.length-f+O.length<ba&&await t.next()&&S(t.value);const A=Z(ba);if(A.length>0&&T.enqueue(s.encode(`${A.join(r)}${r}`)),d.length-f===0||O.length===0){if(!await t.next()){const j=Z(1/0,!0);j.length>0&&T.enqueue(s.encode(`${j.join(r)}${r}`)),await t.close(),T.close();return}S(t.value)}}catch(E){await t.close(),T.error(E)}},async cancel(){await t.close()}})},YO=t=>{const e=new Map;for(const n of t){if(n.index===0)continue;let r=e.get(n.index);r==null&&(r=[n.index],e.set(n.index,r)),!n.isIndex&&!r.includes(n.key)&&r.push(n.key)}return e},GO=(t,e,n)=>{const r=new Map(t.map(c=>[c.key,c])),s=[],a=new Map,o=new Map;for(const[c,l]of e){const u=[];for(const h of l){const d=r.get(h);if(d==null)throw new st(`Channel ${h} not found`);const f={key:h,header:n?.[h]??n?.[d.name]??d.name};s.push(f),u.push(f)}a.set(c,u),o.set(c,",".repeat(u.length-1))}return{columns:s,columnsByIndexKey:a,emptyGroupStrings:o}},HO=(t,e)=>{const n=[];let r=0,s=0;for(;r<t.length&&s<e.length;)t[r].time<=e[s].time?n.push(t[r++]):n.push(e[s++]);return n.push(...t.slice(r),...e.slice(s)),n},ba=1e3,VO=i.z.object({keys:i.z.number().array(),downsampleFactor:i.z.int(),throttleRate:G.z.optional()}),WO=i.z.object({frame:Hn}),va=i.z.object({channels:yt,downsampleFactor:i.z.int().default(1),throttleRate:G.z.default(new G(0)),useHighPerformanceCodec:i.z.boolean().default(!0)}),ii=va.or(yt.transform(t=>va.parse({channels:t}))),Uu=(t,e)=>async n=>{const r=ii.parse(n),s=await Vn.open(t,r.channels);r.useHighPerformanceCodec&&(e=e.withCodec(new LO(s.codec)));const a=await e.stream("/frame/stream",VO,WO),o=new KO(a,s,r.downsampleFactor,r.throttleRate);a.send({keys:Array.from(s.keys),downsampleFactor:r.downsampleFactor,throttleRate:r.throttleRate});const[,c]=await a.receive();if(c!=null)throw c;return o},Du=async(t,e,n)=>await Uu(t,e)(n);class KO{stream;adapter;downsampleFactor;throttleRate;constructor(e,n,r=1,s=new G(0)){this.stream=new Ru("Streamer",e),this.adapter=n,this.downsampleFactor=r,this.throttleRate=s}get keys(){return Array.from(this.adapter.keys)}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(we.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new F((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e)&&this.stream.send({keys:Array.from(this.adapter.keys),downsampleFactor:this.downsampleFactor,throttleRate:this.throttleRate})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class Wn{wrapped_=null;breaker;opener;config;constructor(e,n,r={}){this.opener=e,this.config=ii.parse(n);const{maxRetries:s=5e3,baseInterval:a=m.seconds(1),scale:o=1}=r??{};this.breaker=new $s.Breaker({maxRetries:s,baseInterval:a,scale:o})}static async open(e,n,r){const s=new Wn(e,n,r);return await s.runStreamer(),s}async runStreamer(){for(;;)try{this.wrapped_!=null&&this.wrapped_.close(),this.wrapped_=await this.opener(this.config),this.breaker.reset();return}catch(e){if(this.wrapped_=null,!await this.breaker.wait())throw e;console.error("failed to open streamer",e);continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=yt.parse(e);try{await this.wrapped.update(e)}catch{return await this.runStreamer(),await this.update(e)}}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(we.matches(e))return{done:!0,value:void 0};throw e}}async read(){try{const e=await this.wrapped.read();return this.breaker.reset(),e}catch(e){if(we.matches(e))throw e;return await this.runStreamer(),await this.read()}}close(){this.wrapped.close()}get keys(){return this.wrapped.keys}[Symbol.asyncIterator](){return this}}class Lu extends fm.Observer{streamer;closePromise;constructor(e,n){super(n),this.streamer=e,this.closePromise=this.stream()}async update(e){await this.streamer.update(e)}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}}var Xt=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(Xt||{});const JO=new m(-1);class rs extends ke.sub("writer_closed"){constructor(){super("WriterClosed")}}const XO=i.z.enum(Xt).or(i.z.enum(["persist","stream","persistStream"]).transform(t=>{switch(t){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),Pu=i.z.object({start:w.z.optional(),controlSubject:le.subjectZ.optional(),authorities:i.z.union([le.authorityZ.transform(t=>[t]),le.authorityZ.array()]).default([le.ABSOLUTE_AUTHORITY]),mode:XO.default(1),errOnUnauthorized:i.z.boolean().default(!1),enableAutoCommit:i.z.boolean().default(!0),autoIndexPersistInterval:m.z.default(m.SECOND),useHighPerformanceCodec:i.z.boolean().default(!0)}),QO=Pu.extend({keys:U.array().optional()}),za=Pu.extend({channels:yt}),Bu=za.or(yt.transform(t=>za.parse({channels:t,start:w.now()}))),eE=i.z.object({command:i.z.enum(Ee),config:QO.optional(),frame:Hn.optional(),buffer:i.z.instanceof(Uint8Array).optional()}),tE=i.z.object({command:i.z.enum(Ee),end:w.z,err:je.payloadZ.optional()}),nE=i.z.tuple([i.z.union([i.z.record(U.or(Re),le.authorityZ),U.or(Re),le.authorityZ]),le.authorityZ.optional()]).transform(([t,e])=>{if(le.authorityZ.safeParse(t).success)return{keys:[],authorities:[t]};if(U.or(Re).safeParse(t).success){if(e==null)throw new Error("authority is required when setting authority for a single channel");return{keys:[t],authorities:[e]}}const n=t;return{keys:Object.keys(n),authorities:Object.values(n)}});let qu=class Fu{stream;adapter;closeErr=null;constructor(e,n){this.stream=e,this.adapter=n}static async _open(e,n,r){const s=Bu.parse(r),a=await ri.open(e,s.channels);s.useHighPerformanceCodec&&(n=n.withCodec(new DO(a.codec)));const o=await n.stream("/frame/write",eE,tE),c=new Fu(o,a);return await c.execute({command:Ee.Open,config:{...s,keys:a.keys}}),c}async write(e,n){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const r=await this.adapter.adapt(e,n);this.stream.send({command:Ee.Write,frame:r.toPayload()})}async setAuthority(e,n){if(this.closeErr!=null)throw this.closeErr;const r=nE.parse([e,n]),s={keys:await this.adapter.adaptParams(r.keys),authorities:r.authorities};await this.execute({command:Ee.SetAuthority,config:s})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),w.ZERO):(await this.execute({command:Ee.Commit})).end}async close(){await this.closeInternal(null)}async closeInternal(e){if(this.closeErr!=null)throw this.closeErr;for(this.closeErr=e,this.stream.closeSend();;){if(this.closeErr!=null){if(rs.matches(this.closeErr))return null;throw this.closeErr}const[n,r]=await this.stream.receive();r!=null?this.closeErr=we.matches(r)?new rs:r:this.closeErr=je.decode(n?.err)}}async execute(e){const n=this.stream.send(e);for(n!=null&&await this.closeInternal(n);;){const[r,s]=await this.stream.receive();s!=null&&await this.closeInternal(s);const a=je.decode(r?.err);if(a!=null&&await this.closeInternal(a),r?.command==e.command)return r}}};const Yu=V("framer"),rE=Yu("");let Gu=class{streamClient;retriever;deleter;reader;constructor(e,n,r){this.streamClient=e,this.retriever=r,this.deleter=new CO(n),this.reader=new Mu(r,e)}async openIterator(e,n,r){return await fn._open(e,n,this.retriever,this.streamClient,r)}async openWriter(e){return await qu._open(this.retriever,this.streamClient,e)}async openStreamer(e){return await Du(this.retriever,this.streamClient,e)}async write(e,n,r){if(r==null){const a=n,o=await this.openWriter({start:e,channels:Object.keys(a),mode:Xt.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:m.MAX});return await o.write(a),await o.close()}const s=await this.openWriter({start:e,channels:n,mode:Xt.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:m.MAX});await s.write(n,r),await s.close()}async read(e,n){if(!("start"in e))return this.reader.read(e);const{single:r}=ge(n),s=await this.readFrame(e,n);return r?s.get(n):s}async readFrame(e,n){const r=await this.openIterator(e,n),s=new F;try{for await(const a of r)s.push(a)}finally{await r.close()}return s}async readLatest(e,n=1){const{single:r}=ge(e),s=await this.readLatestNFrame(e,n);return r?s.get(e):s}async readLatestNFrame(e,n){const r=await this.openIterator(x.MAX,e,{chunkSize:n}),s=new F;if(n>0)try{await r.seekLast(),await r.prev(Rn),s.push(r.value)}finally{await r.close()}return s}async delete(e,n){const{normalized:r,variant:s}=ge(e),a=new x(n);return s==="keys"?await this.deleter.delete({keys:r,bounds:a}):await this.deleter.delete({names:r,bounds:a})}};const sE=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:JO,AUTO_SPAN:Rn,Client:Gu,Frame:F,HardenedStreamer:Wn,Iterator:fn,ObservableStreamer:Lu,Reader:Mu,TYPE_ONTOLOGY_ID:rE,Writer:qu,WriterClosedError:rs,WriterCommand:Ee,WriterMode:Xt,createStreamOpener:Uu,frameZ:Hn,ontologyID:Yu,openStreamer:Du,seriesFromPayload:Zu,seriesToPayload:xu,streamerConfigZ:ii,writerConfigZ:Bu},Symbol.toStringTag,{value:"Module"})),iE=le.ABSOLUTE_AUTHORITY,aE=le.ZERO_AUTHORITY,oE=le.stateZ(i.z.number()),cE=t=>t.to==null?`${t.from?.resource} - ${t.from?.subject.name} -> released`:t.from==null?`${t.to.resource} - released -> ${t.to.subject.name} (${t.to.authority.toString()})`:`${t.to.resource} - ${t.from.subject.name} -> ${t.to.subject.name} (${t.to.authority.toString()})`,uE=i.z.object({transfers:i.z.array(le.transferZ(U))});class Hu extends Lu{states;codec;constructor(e){super(e,n=>{const r=this.codec.decode(n.series[0].buffer,uE);return this.merge(r),[r.transfers,!0]}),this.states=new Map,this.codec=new ut.JSONCodec}subjects(){const e=new Map;return this.states.forEach(n=>e.set(n.subject.key,n.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const Vu="sy_node_1_control";let Wu=class{framer;constructor(e){this.framer=e}async openStateTracker(){const e=await Wn.open(async n=>await this.framer.openStreamer(n),Vu);return new Hu(e)}};const lE=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:iE,CONTROL_STATE_CHANNEL_NAME:Vu,Client:Wu,StateTracker:Hu,ZERO_AUTHORITY:aE,stateZ:oE,transferString:cE},Symbol.toStringTag,{value:"Module"})),be=i.z.uint32(),Ku=i.z.object({rack:be}),Ju=We.statusZ(Ku),Kn=i.z.object({key:be,name:i.z.string(),status:Ne.nullToUndefined(Ju)}),Xu=Kn.partial({key:!0}),Qu=t=>t?ut.JSON_CODEC.decodeString(t,fe.unknownZ):{},_t=i.z.string(),el=i.z.object({rack:be,device:_t}),tl=We.statusZ(el),Jn=i.z.object({key:_t,rack:be.min(1,"Must select a location to connect from"),name:i.z.string().min(1,"Name is required"),make:i.z.string().min(1,"Make is required"),model:i.z.string().min(1,"Model is required"),location:i.z.string().min(1,"Location is required"),configured:i.z.boolean().optional(),properties:fe.unknownZ.or(i.z.string().transform(Qu)),status:Ne.nullToUndefined(tl)}),nl=Jn.extend({properties:i.z.unknown().transform(t=>ut.JSON_CODEC.encodeString(t))}),hE="sy_device_set",fE="sy_device_delete",dE=i.z.object({devices:nl.array()}),yE=i.z.object({devices:Jn.array()}),pE=i.z.object({keys:_t.array()}),mE=i.z.object({}),gE=i.z.object({keys:_t.array().optional(),names:i.z.string().array().optional(),makes:i.z.string().array().optional(),models:i.z.string().array().optional(),locations:i.z.string().array().optional(),racks:be.array().optional(),searchTerm:i.z.string().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeStatus:i.z.boolean().optional()}),wE=i.z.object({devices:N.nullableZ(Jn)}),bE=i.z.object({key:_t,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),vE=i.z.union([bE,gE]);let rl=class{client;constructor(e){this.client=e}async retrieve(e){const n=typeof e=="object"&&"key"in e,r=await z(this.client,"/device/retrieve",e,vE,wE);se("Device",e,r.devices,n);const s=r.devices;return n?s[0]:s}async create(e){const n=!Array.isArray(e),s=(await z(this.client,"/device/create",{devices:N.toArray(e)},dE,yE)).devices;return n?s[0]:s}async delete(e){await z(this.client,"/device/delete",{keys:N.toArray(e)},pE,mE)}};const ai=V("device"),zE=ai(""),TE=t=>Se(ai(t)),OE=Object.freeze(Object.defineProperty({__proto__:null,Client:rl,DELETE_CHANNEL_NAME:fE,SET_CHANNEL_NAME:hE,TYPE_ONTOLOGY_ID:zE,deviceZ:Jn,keyZ:_t,newZ:nl,ontologyID:ai,statusDetailsZ:el,statusKey:TE,statusZ:tl},Symbol.toStringTag,{value:"Module"})),EE="sy_rack_set",NE="sy_rack_delete",SE=i.z.object({keys:be.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),embedded:i.z.boolean().optional(),hostIsNode:i.z.boolean().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeStatus:i.z.boolean().optional()}),kE=i.z.object({racks:N.nullableZ(Kn)}),AE=i.z.union([i.z.object({key:be,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),i.z.object({name:i.z.string(),includeStatus:i.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e}))]),$E=SE,IE=i.z.union([AE,$E]),ZE=i.z.object({racks:Xu.array()}),xE=i.z.object({racks:Kn.array()}),CE=i.z.object({keys:be.array()}),_E=i.z.object({});let sl=class{client;tasks;constructor(e,n){this.client=e,this.tasks=n}async delete(e){await z(this.client,"/rack/delete",{keys:N.toArray(e)},CE,_E)}async create(e){const n=!Array.isArray(e),r=await z(this.client,"/rack/create",{racks:N.toArray(e)},ZE,xE),s=this.sugar(r.racks);return n?s[0]:s}async retrieve(e){const n="key"in e||"name"in e,r=await z(this.client,"/rack/retrieve",e,IE,kE),s=this.sugar(r.racks);return se("Rack",e,s,n),n?s[0]:s}sugar(e){const n=!Array.isArray(e),r=N.toArray(e).map(({key:s,name:a,status:o})=>new il(s,a,this.tasks,o));return n?r[0]:r}};class il{key;name;status;tasks;constructor(e,n,r,s){this.key=e,this.name=n,this.tasks=r,this.status=s}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,n){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e,n)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status}}}const oi=V("rack"),RE=oi(0),jE=t=>Se(oi(t)),ME=Object.freeze(Object.defineProperty({__proto__:null,Client:sl,DELETE_CHANNEL_NAME:NE,Rack:il,SET_CHANNEL_NAME:EE,TYPE_ONTOLOGY_ID:RE,keyZ:be,newZ:Xu,ontologyID:oi,rackZ:Kn,statusDetailsZ:Ku,statusKey:jE,statusZ:Ju},Symbol.toStringTag,{value:"Module"})),UE="sy_range_alias_set",DE="sy_range_alias_delete",LE=i.z.object({range:K,aliases:i.z.string().array()}),PE=i.z.object({aliases:i.z.record(i.z.string(),U)}),BE=i.z.object({range:K,aliases:i.z.record(U,i.z.string())}),qE=i.z.unknown(),FE=i.z.object({range:K,channels:U.array()}),YE=i.z.unknown(),GE=i.z.object({range:K}),HE=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())}),VE=i.z.object({range:K,channels:U.array()}),WE=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())});class Qe{cache=new Map;client;rangeKey;constructor(e,n){this.rangeKey=e,this.cache=new Map,this.client=n}async resolve(e){const n=[],r=typeof e=="string",s={};if(r){const o=this.cache.get(e);if(o!=null)return o;n.push(e)}else e.forEach(o=>{const c=this.cache.get(o);c!=null?s[o]=c:n.push(o)});if(n.length===0)return s;const a=await z(this.client,"/range/alias/resolve",{range:this.rangeKey,aliases:n},LE,PE);return Object.entries(a.aliases).forEach(([o,c])=>this.cache.set(o,c)),r?a.aliases[n[0]]:{...s,...a.aliases}}async set(e){await z(this.client,"/range/alias/set",{range:this.rangeKey,aliases:e},BE,qE)}async list(){return(await z(this.client,"/range/alias/list",{range:this.rangeKey},GE,HE)).aliases}async retrieve(e){const n=typeof e=="number",r=await z(this.client,"/range/alias/retrieve",{range:this.rangeKey,channels:N.toArray(e)},VE,WE);return n?r.aliases[e]:r.aliases}async delete(e){await z(this.client,"/range/alias/delete",{range:this.rangeKey,channels:N.toArray(e)},FE,YE)}}const KE=i.z.object({alias:i.z.string().optional(),channel:U,range:K}),al="---",JE=t=>`${t.range}${al}${t.channel}`,XE=t=>{const[e,n]=t.split(al);return{range:e,channel:Number(n)}},QE="sy_range_kv_set",eN="sy_range_kv_delete",ci=i.z.object({range:K,key:i.z.string(),value:i.z.string()}),tN=({range:t,key:e})=>`${t}<--->${e}`,nN=i.z.object({range:K,keys:i.z.string().array()}),rN=i.z.object({pairs:N.nullableZ(ci)}),sN=i.z.object({range:K,pairs:ci.array()}),iN=i.z.object({range:K,keys:i.z.string().array()});class ss{rangeKey;client;constructor(e,n){this.rangeKey=e,this.client=n}async get(e){const n=await z(this.client,"/range/kv/get",{range:this.rangeKey,keys:N.toArray(e)},nN,rN);return typeof e=="string"?n.pairs[0].value:Object.fromEntries(n.pairs.map(r=>[r.key,r.value]))}async list(){return this.get([])}async set(e,n=""){let r;typeof e=="string"?r=[{range:this.rangeKey,key:e,value:n}]:r=Object.entries(e).map(([s,a])=>({range:this.rangeKey,key:s,value:a})),await z(this.client,"/range/kv/set",{range:this.rangeKey,pairs:r},sN,i.z.unknown())}async delete(e){await z(this.client,"/range/kv/delete",{range:this.rangeKey,keys:N.toArray(e)},iN,i.z.unknown())}}const aN="sy_range_set",oN="sy_range_delete";class ol{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:n=x.ZERO,key:r,color:s,parent:a,labels:o},{frameClient:c,kv:l,aliaser:u,channels:h,labelClient:d,ontologyClient:f,rangeClient:O}){this.key=r,this.name=e,this.timeRange=n,this.parent=a,this.labels=o,this.frameClient=c,this.color=s,this.kv=l,this.aliaser=u,this.channels=h,this.labelClient=d,this.ontologyClient=f,this.rangeClient=O}get ontologyID(){return et(this.key)}get payload(){let e=null;return this.parent!=null&&("payload"in this.parent?e=this.parent.payload:e=this.parent),{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels,parent:e}}async setAlias(e,n){const r=await this.channels.retrieve(e);if(r.length===0)throw new He(`Channel ${e} does not exist`);await this.aliaser.set({[r[0].key]:n})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(n=>n.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async retrieveLabels(){return await this.labelClient.retrieve({for:et(this.key)})}async addLabel(...e){await this.labelClient.label(et(this.key),e)}async removeLabel(...e){await this.labelClient.remove(et(this.key),e)}static sort(e,n){return x.sort(e.timeRange,n.timeRange)}}const cN=i.z.object({keys:K.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),overlapsWith:x.z.optional(),hasLabels:Je.array().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeLabels:i.z.boolean().optional(),includeParent:i.z.boolean().optional()}),uN=cN.or(K.array().transform(t=>({keys:t}))).or(K.transform(t=>({keys:[t]}))).or(i.z.string().transform(t=>({names:[t]}))).or(i.z.string().array().transform(t=>({names:t}))).or(x.z.transform(t=>({overlapsWith:t}))),lN=i.z.object({ranges:N.nullableZ(hn)});let cl=class{type="range";frameClient;writer;unaryClient;channels;labelClient;ontologyClient;constructor(e,n,r,s,a,o){this.frameClient=e,this.writer=n,this.unaryClient=r,this.channels=s,this.labelClient=a,this.ontologyClient=o}async create(e,n){const r=!Array.isArray(e),s=this.sugarMany(await this.writer.create(N.toArray(e),n));return r?s[0]:s}async rename(e,n){await this.writer.rename(e,n)}async delete(e){await this.writer.delete(N.toArray(e))}async retrieve(e){const n=typeof e=="string",{ranges:r}=await z(this.unaryClient,"/range/retrieve",e,uN,lN);return se("Range",e,r,n),n?this.sugarMany(r)[0]:this.sugarMany(r)}getKV(e){return new ss(e,this.unaryClient)}async retrieveParent(e){const n=await this.ontologyClient.retrieveParents(et(e));if(n.length===0)return null;const r=n[0];return r.id.type!=="range"?null:await this.retrieve(r.id.key)}sugarOntologyResource(e){return this.sugarOne(ul(e))}async retrieveAlias(e,n){return await new Qe(e,this.unaryClient).retrieve(n)}async retrieveAliases(e,n){return await new Qe(e,this.unaryClient).retrieve(n)}async listAliases(e){return await new Qe(e,this.unaryClient).list()}async setAlias(e,n,r){await new Qe(e,this.unaryClient).set({[n]:r})}async deleteAlias(e,n){await new Qe(e,this.unaryClient).delete(n)}sugarOne(e){return new ol(e,{frameClient:this.frameClient,kv:new ss(e.key,this.unaryClient),aliaser:new Qe(e.key,this.unaryClient),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(e){return e.map(n=>this.sugarOne(n))}resourceToRange(e){return this.sugarOne({key:e.id.key,name:e.data?.name,timeRange:new x(e.data?.timeRange),color:e.data?.color,labels:[],parent:null})}};const et=V("range"),hN=et(""),fN=t=>({type:"range-alias",key:t}),ul=({data:t,id:{key:e},name:n})=>{const r=x.z.parse(t?.timeRange);return{key:e,name:n,timeRange:r,color:typeof t?.color=="string"?t.color:void 0,labels:[],parent:null}},dN=i.z.object({ranges:hn.array()}),yN=i.z.object({parent:L.optional(),ranges:Eu.array()}),pN=i.z.object({keys:K.array()}),mN=i.z.object({}),gN=i.z.object({key:K,name:Xs}),wN=i.z.object({});class ll{client;constructor(e){this.client=e}async rename(e,n){await z(this.client,"/range/rename",{key:e,name:n},gN,wN)}async create(e,n){return(await z(this.client,"/range/create",{ranges:e,...n},yN,dN)).ranges}async delete(e){await z(this.client,"/range/delete",{keys:e},pN,mN)}}const bN=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:Qe,Client:cl,DELETE_ALIAS_CHANNEL_NAME:DE,DELETE_CHANNEL_NAME:oN,KV:ss,KV_DELETE_CHANNEL:eN,KV_SET_CHANNEL:QE,Range:ol,SET_ALIAS_CHANNEL_NAME:UE,SET_CHANNEL_NAME:aN,TYPE_ONTOLOGY_ID:hN,Writer:ll,aliasKey:JE,aliasOntologyID:fN,aliasZ:KE,convertOntologyResourceToPayload:ul,decodeDeleteAliasChange:XE,keyZ:K,kvPairKey:tN,kvPairZ:ci,nameZ:Xs,newZ:Eu,ontologyID:et,payloadZ:hn},Symbol.toStringTag,{value:"Module"})),Xn=i.z.string(),Qn=t=>We.statusZ(t),hl=t=>Qn(t).omit({labels:!0}).partial({key:!0}),is="sy_status_set",vN="sy_status_delete",fl=V("status"),zN=fl(""),TN=t=>i.object({parent:L.optional(),statuses:hl(t).array()}),ON=t=>i.object({statuses:Qn(t).array()}),EN=i.object({keys:Xn.array()}),NN=i.object({}),SN=i.object({keys:Xn.array().optional(),searchTerm:i.string().optional(),offset:i.int().optional(),limit:i.int().optional(),includeLabels:i.boolean().optional(),hasLabels:Je.array().optional()}),kN=i.object({key:Xn,includeLabels:i.boolean().optional()}).transform(({key:t,includeLabels:e})=>({keys:[t],includeLabels:e})),AN=i.union([kN,SN]),$N=t=>i.object({statuses:N.nullableZ(Qn(t))});let dl=class{type="status";client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await z(this.client,"/status/retrieve",e,AN,$N(e.detailsSchema));se("Status",e,r.statuses,n);const s=r.statuses;return n?s[0]:s}async set(e,n={}){const r=Array.isArray(e),a=(await z(this.client,"/status/set",{statuses:N.toArray(e),parent:n.parent},TN(n.detailsSchema),ON(n.detailsSchema))).statuses;return r?a:a[0]}async delete(e){await z(this.client,"/status/delete",{keys:N.toArray(e)},EN,NN)}};const IN=Object.freeze(Object.defineProperty({__proto__:null,Client:dl,DELETE_CHANNEL_NAME:vN,SET_CHANNEL_NAME:is,TYPE_ONTOLOGY_ID:zN,keyZ:Xn,newZ:hl,ontologyID:fl,statusZ:Qn},Symbol.toStringTag,{value:"Module"})),Me=i.z.union([i.z.string(),i.z.bigint().transform(t=>t.toString()),i.z.number().transform(t=>t.toString())]),ui=t=>i.z.object({task:Me,running:i.z.boolean(),data:t,cmd:i.z.string().optional()}),li=t=>We.statusZ(ui(t)),ZN=t=>ui(t).partial({task:!0}),yl=t=>We.statusZ(ZN(t)).partial({key:!0,name:!0}),dn=(t={typeSchema:i.z.string(),configSchema:i.z.unknown(),statusDataSchema:i.z.unknown()})=>i.z.object({key:Me,name:i.z.string(),type:t.typeSchema,internal:i.z.boolean().optional(),config:i.z.string().transform(Qu).or(t.configSchema),status:li(t.statusDataSchema).optional().nullable(),snapshot:i.z.boolean().optional()}),pl=t=>dn(t).omit({key:!0,status:!0}).extend({key:Me.transform(e=>e.toString()).optional(),config:i.z.unknown().transform(e=>ut.JSON_CODEC.encodeString(e)),status:yl(t?.statusDataSchema??i.z.unknown()).optional().nullable()}),xN=i.z.object({task:Me,type:i.z.string(),key:i.z.string(),args:fe.unknownZ.or(i.z.string().transform($e)).or(i.z.array(i.z.unknown())).or(i.z.null()).optional()}),CN=t=>Number(BigInt(t)>>32n),_N=(t,e=0)=>((BigInt(t)<<32n)+BigInt(e)).toString(),as="sy_task_cmd",RN="sy_task_set",jN="sy_task_delete",tt=new Error("Task not created"),ml=async(t,e)=>{const n=await e.retrieveParents(yn(t));return n.length===0?null:n[0]};class gl{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw tt;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw tt;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw tt;return this.rangeClient_}constructor({key:e,type:n,name:r,config:s,internal:a=!1,snapshot:o=!1,status:c},l,u,h,d){this.key=e,this.name=r,this.type=n,this.config=s,this.schemas=l??{typeSchema:i.z.string(),configSchema:i.z.unknown(),statusDataSchema:i.z.unknown()},this.internal=a,this.snapshot=o,this.status=c,this.frameClient_=u,this.ontologyClient_=h,this.rangeClient_=d}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return yn(this.key)}async executeCommand(e){return await vl({...e,frameClient:this.frameClient,task:this.key})}async executeCommandSync(e){return await zl({...e,frameClient:this.frameClient,task:this.key,name:this.name,statusDataZ:this.schemas?.statusDataSchema})}async start(){await this.executeCommand({type:"start"})}async stop(){await this.executeCommand({type:"stop"})}async run(e){await this.start();try{return await e()}finally{await this.stop()}}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw tt;return this.snapshot?await ml(this.key,this.ontologyClient):null}}const MN=i.z.object({rack:be.optional(),keys:Me.array().optional(),names:i.z.string().array().optional(),types:i.z.string().array().optional(),includeStatus:i.z.boolean().optional(),internal:i.z.boolean().optional(),snapshot:i.z.boolean().optional(),searchTerm:i.z.string().optional(),offset:i.z.int().optional(),limit:i.z.int().optional()}),wl=i.z.union([i.z.object({key:Me,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),i.z.object({name:i.z.string(),includeStatus:i.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),i.z.object({type:i.z.string(),rack:be.optional()}).transform(({type:t,rack:e})=>({types:[t],rack:e}))]),UN=MN,DN=i.z.union([wl,UN]),LN=t=>i.z.object({tasks:N.nullableZ(dn(t))}),PN=t=>i.z.object({tasks:pl(t).array()}),BN=t=>i.z.object({tasks:dn(t).array()}),qN=i.z.object({keys:Me.array()}),FN=i.z.object({}),YN=i.z.object({key:Me,name:i.z.string(),snapshot:i.z.boolean()}),GN=t=>i.z.object({task:dn(t)});let bl=class{type="task";client;frameClient;ontologyClient;rangeClient;constructor(e,n,r,s){this.client=e,this.frameClient=n,this.ontologyClient=r,this.rangeClient=s}async create(e,n){const r=!Array.isArray(e),s=PN(n),a=BN(n),o=await z(this.client,"/task/create",{tasks:N.toArray(e)},s,a),c=this.sugar(o.tasks,n);return r?c[0]:c}async delete(e){await z(this.client,"/task/delete",{keys:N.toArray(e)},qN,FN)}async retrieve({schemas:e,...n}){const r=wl.safeParse(n).success,a=(await z(this.client,"/task/retrieve",n,DN,LN(e))).tasks,o=this.sugar(a,e);return se("Task",n,o,r),r?o[0]:o}async copy(e,n,r){const s=GN(),a=await z(this.client,"/task/copy",{key:e,name:n,snapshot:r},YN,s);return this.sugar(a.task)}async list(e){const n={internal:!1};return e!==void 0&&(n.rack=e),await this.retrieve(n)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw tt;return await ml(e,this.ontologyClient)}sugar(e,n){const r=!Array.isArray(e),s=N.toArray(e).map(({key:a,name:o,type:c,config:l,status:u,internal:h,snapshot:d})=>new gl({key:a,name:o,type:c,config:l,internal:h,snapshot:d,status:u},n,this.frameClient,this.ontologyClient,this.rangeClient));return r?s[0]:s}async executeCommand(e){return"commands"in e?await hi({...e,frameClient:this.frameClient}):await vl({...e,frameClient:this.frameClient})}async executeCommandSync(e){if("commands"in e){const r=async()=>{const{commands:s}=e;return(await this.retrieve({keys:s.map(o=>o.task)})).map(o=>o.name)};return await Tl({...e,frameClient:this.frameClient,name:r})}const n=async()=>{const{task:r}=e;return(await this.retrieve({key:r})).name};return await zl({frameClient:this.frameClient,name:n,...e})}};const yn=V("task"),HN=yn(""),VN=t=>Se(yn(t)),vl=async({frameClient:t,task:e,type:n,args:r})=>(await hi({frameClient:t,commands:[{args:r,task:e,type:n}]}))[0],hi=async({frameClient:t,commands:e})=>{if(t==null)throw tt;const n=await t.openWriter(as),r=e.map(s=>({...s,key:po.create()}));return await n.write(as,r),await n.close(),r.map(s=>s.key)},zl=async({frameClient:t,task:e,type:n,timeout:r,name:s,statusDataZ:a,args:o})=>(await Tl({frameClient:t,commands:[{args:o,task:e,type:n}],timeout:r,statusDataZ:a,name:s}))[0],Tl=async({frameClient:t,commands:e,timeout:n=m.seconds(10),statusDataZ:r,name:s})=>{if(t==null)throw tt;const a=await t.openStreamer(is),o=await hi({frameClient:t,commands:e}),c=new m(n);let l=[],u;const h=new Promise((d,f)=>{u=setTimeout(()=>{(async()=>{const O=e.map(S=>S.task);f(await WN("command",s,c,O))})()},c.milliseconds)});try{for(;;){const d=await Promise.race([a.read(),h]),f=li(r).safeParse(d.at(-1)[is]);if(!f.success)continue;const O=f.data;if(!(O.details.cmd==null||!o.includes(O.details.cmd))&&(l=[...l.filter(S=>S.key!==O.key),O],l.length===o.length))return l}}finally{clearTimeout(u),a.close()}},WN=async(t,e,n,r)=>{const s=zd.capitalize(t),a=n.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=N.toArray(await e());const c=Hr.naturalLanguageJoin(o);return new Error(`${s} command to ${c} timed out after ${a}`)}catch(o){return console.error("Failed to retrieve task name for timeout error:",o),new Error(`${s} command to task with key ${Hr.naturalLanguageJoin(r)} timed out after ${a}`)}},KN=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:as,Client:bl,DELETE_CHANNEL_NAME:jN,SET_CHANNEL_NAME:RN,TYPE_ONTOLOGY_ID:HN,Task:gl,commandZ:xN,keyZ:Me,newKey:_N,newStatusZ:yl,newZ:pl,ontologyID:yn,rackKey:CN,statusDetailsZ:ui,statusKey:VN,statusZ:li,taskZ:dn},Symbol.toStringTag,{value:"Module"}));class Ol{url;unary;stream;secure;constructor(e,n={},r=!1){this.secure=r,this.url=e.child("/api/v1/");const s=new ut.JSONCodec;this.unary=sd(new rd(this.url,s,this.secure),n),this.stream=new ud(this.url,s,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Rt=i.uuid(),er=i.object({key:Rt,name:i.string(),type:i.string(),query:fe.unknownZ}),El=er.extend({key:Rt.optional()}),JN="sy_view_set",XN="sy_view_delete",QN=i.z.object({views:El.array()}),eS=i.z.object({views:er.array()}),tS=i.z.object({keys:Rt.array()}),nS=i.z.object({}),rS=i.z.object({keys:Rt.array().optional(),types:i.z.string().array().optional(),searchTerm:i.z.string().optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),sS=i.z.object({key:Rt}).transform(({key:t})=>({keys:[t]})),iS=i.z.union([sS,rS]),aS=i.z.object({views:N.nullableZ(er)});let Nl=class{client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await z(this.client,"/view/retrieve",e,iS,aS);return se("View",e,r.views,n),n?r.views[0]:r.views}async create(e){const n=Array.isArray(e),r=await z(this.client,"/view/create",{views:N.toArray(e)},QN,eS);return n?r.views:r.views[0]}async delete(e){await z(this.client,"/view/delete",{keys:N.toArray(e)},tS,nS)}};const Sl=t=>({type:"view",key:t}),oS=Sl(""),cS=Object.freeze(Object.defineProperty({__proto__:null,Client:Nl,DELETE_CHANNEL_NAME:XN,SET_CHANNEL_NAME:JN,TYPE_ONTOLOGY_ID:oS,keyZ:Rt,newZ:El,ontologyID:Sl,viewZ:er},Symbol.toStringTag,{value:"Module"})),pt=i.z.uuid(),tr=i.z.object({key:pt,name:i.z.string(),data:fe.unknownZ.or(i.z.string().transform($e))}),kl=tr.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Ie=i.z.uuid(),nr=i.z.object({key:Ie,name:i.z.string().min(1,"Name is required"),layout:fe.unknownZ.or(i.z.string().transform($e))}),Al=nr.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),$l=nr.omit({layout:!0}).extend({layout:i.z.string().transform($e)}),uS=i.z.object({key:pt,name:i.z.string()}),lS=i.z.object({key:pt,data:i.z.string()}),hS=i.z.object({keys:pt.array()}),fS=i.z.object({keys:pt.array()}),Il=i.z.object({key:pt}).transform(({key:t})=>({keys:[t]})),Zl=i.z.union([Il,fS]),dS=i.z.object({linePlots:N.nullableZ(tr)}),yS=i.z.object({workspace:Ie,linePlots:kl.array()}),pS=i.z.object({linePlots:tr.array()}),zr=i.z.object({});let xl=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await z(this.client,"/workspace/lineplot/create",{workspace:e,linePlots:N.toArray(n)},yS,pS);return r?s.linePlots:s.linePlots[0]}async rename(e,n){await z(this.client,"/workspace/lineplot/rename",{key:e,name:n},uS,zr)}async setData(e,n){await z(this.client,"/workspace/lineplot/set-data",{key:e,data:JSON.stringify(n)},lS,zr)}async retrieve(e){const n=Il.safeParse(e).success,r=await z(this.client,"/workspace/lineplot/retrieve",e,Zl,dS);return se("LinePlot",e,r.linePlots,n),n?r.linePlots[0]:r.linePlots}async delete(e){await z(this.client,"/workspace/lineplot/delete",{keys:N.toArray(e)},hS,zr)}};const Cl=V("lineplot"),mS=Cl(""),gS=Object.freeze(Object.defineProperty({__proto__:null,Client:xl,TYPE_ONTOLOGY_ID:mS,keyZ:pt,linePlotZ:tr,newZ:kl,ontologyID:Cl,retrieveArgsZ:Zl},Symbol.toStringTag,{value:"Module"})),mt=i.z.uuid(),rr=i.z.object({key:mt,name:i.z.string(),data:fe.unknownZ.or(i.z.string().transform($e))}),_l=rr.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),wS=i.z.object({key:mt,name:i.z.string()}),bS=i.z.object({key:mt,data:i.z.string()}),vS=i.z.object({keys:mt.array()}),zS=i.z.object({keys:mt.array()}),Rl=i.z.object({key:mt}).transform(({key:t})=>({keys:[t]})),jl=i.z.union([Rl,zS]),TS=i.z.object({logs:N.nullableZ(rr)}),OS=i.z.object({workspace:Ie,logs:_l.array()}),ES=i.z.object({logs:rr.array()}),Tr=i.z.object({});let Ml=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await z(this.client,"/workspace/log/create",{workspace:e,logs:N.toArray(n)},OS,ES);return r?s.logs:s.logs[0]}async rename(e,n){await z(this.client,"/workspace/log/rename",{key:e,name:n},wS,Tr)}async setData(e,n){await z(this.client,"/workspace/log/set-data",{key:e,data:JSON.stringify(n)},bS,Tr)}async retrieve(e){const n=Rl.safeParse(e).success,r=await z(this.client,"/workspace/log/retrieve",e,jl,TS);return se("Log",e,r.logs,n),n?r.logs[0]:r.logs}async delete(e){await z(this.client,"/workspace/log/delete",{keys:N.toArray(e)},vS,Tr)}};const Ul=V("log"),NS=Ul(""),SS=Object.freeze(Object.defineProperty({__proto__:null,Client:Ml,TYPE_ONTOLOGY_ID:NS,keyZ:mt,logZ:rr,newZ:_l,ontologyID:Ul,retrieveArgsZ:jl},Symbol.toStringTag,{value:"Module"})),Xe=i.z.uuid(),sr=i.z.object({key:Xe,name:i.z.string(),data:fe.unknownZ.or(i.z.string().transform($e)),snapshot:i.z.boolean()}),Dl=sr.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),fi=sr.extend({data:i.z.string().transform($e)}),jt=i.z.uuid(),Ll=i.z.object({key:i.z.string(),name:i.z.string(),selectors:i.z.string().array().default([]),strokeColor:i.z.string().optional(),fillColor:i.z.string().optional()}),Pl=i.z.object({key:i.z.string(),name:i.z.string(),regions:Ll.array()}),Bl=i.z.object({key:i.z.string(),position:Ss.xy,orientation:xy.outer}),kS=i.z.object({zoom:i.z.number().positive().default(1),position:Ss.xy}),ql=i.z.object({svg:i.z.string().min(1,"SVG is required"),states:Pl.array(),variant:i.z.string().min(1,"Variant is required"),handles:Bl.array(),scale:i.z.number().positive().default(1),scaleStroke:i.z.boolean().default(!1),previewViewport:kS.default({zoom:1,position:{x:0,y:0}})}),ir=i.z.object({key:jt,version:i.z.literal(1).default(1),name:i.z.string().min(1,"Name is required"),data:ql}),Fl=ir.partial({key:!0}),AS=i.z.object({symbols:Fl.array(),parent:L}),$S=i.z.object({key:jt,name:i.z.string()}),IS=i.z.object({keys:jt.array()}),ZS=i.z.object({keys:jt.array().optional(),searchTerm:i.z.string().optional()}),xS=i.z.object({key:jt}).transform(({key:t})=>({keys:[t]})),CS=i.z.union([xS,ZS]),_S=i.z.object({symbols:N.nullableZ(ir)}),RS=i.z.object({symbols:ir.array()}),Ta=i.z.object({}),jS=i.z.object({}),MS=i.z.object({group:Ln}),US="sy_schematic_symbol_set",DS="sy_schematic_symbol_delete";let Yl=class{client;constructor(e){this.client=e}async create(e){const n="symbols"in e,r=n?e.symbols:[e],s=await z(this.client,"/workspace/schematic/symbol/create",{symbols:r,parent:e.parent},AS,RS);return n?s.symbols:s.symbols[0]}async rename(e,n){await z(this.client,"/workspace/schematic/symbol/rename",{key:e,name:n},$S,Ta)}async retrieve(e){const n="key"in e,r=await z(this.client,"/workspace/schematic/symbol/retrieve",e,CS,_S);return se("Schematic Symbol",e,r.symbols,n),n?r.symbols[0]:r.symbols}async delete(e){await z(this.client,"/workspace/schematic/symbol/delete",{keys:N.toArray(e)},IS,Ta)}async retrieveGroup(){return(await z(this.client,"/workspace/schematic/symbol/retrieve_group",{},jS,MS)).group}};const LS=V("schematic_symbol"),PS=Object.freeze(Object.defineProperty({__proto__:null,Client:Yl,DELETE_CHANNEL_NAME:DS,SET_CHANNEL_NAME:US,handleZ:Bl,keyZ:jt,newZ:Fl,ontologyID:LS,regionZ:Ll,specZ:ql,stateZ:Pl,symbolZ:ir},Symbol.toStringTag,{value:"Module"})),BS=i.z.object({key:Xe,name:i.z.string()}),qS=i.z.object({key:Xe,data:i.z.string()}),FS=i.z.object({keys:Xe.array()}),YS=i.z.object({key:Xe,name:i.z.string(),snapshot:i.z.boolean()}),GS=i.z.object({keys:Xe.array()}),Gl=i.z.object({key:Xe}).transform(({key:t})=>({keys:[t]})),Hl=i.z.union([Gl,GS]),HS=i.z.object({schematics:N.nullableZ(fi)}),VS=i.z.object({workspace:Ie,schematics:Dl.array()}),WS=i.z.object({schematics:fi.array()}),KS=i.z.object({schematic:sr}),Or=i.z.object({});let Vl=class{symbols;client;constructor(e){this.client=e,this.symbols=new Yl(e)}async create(e,n){const r=Array.isArray(n),s=await z(this.client,"/workspace/schematic/create",{workspace:e,schematics:N.toArray(n)},VS,WS);return r?s.schematics:s.schematics[0]}async rename(e,n){await z(this.client,"/workspace/schematic/rename",{key:e,name:n},BS,Or)}async setData(e,n){await z(this.client,"/workspace/schematic/set-data",{key:e,data:JSON.stringify(n)},qS,Or)}async retrieve(e){const n=Gl.safeParse(e).success,r=await z(this.client,"/workspace/schematic/retrieve",e,Hl,HS);return se("Schematic",e,r.schematics,n),n?r.schematics[0]:r.schematics}async delete(e){await z(this.client,"/workspace/schematic/delete",{keys:N.toArray(e)},FS,Or)}async copy(e){return(await z(this.client,"/workspace/schematic/copy",e,YS,KS)).schematic}};const Wl=V("schematic"),JS=Wl(""),XS=Object.freeze(Object.defineProperty({__proto__:null,Client:Vl,TYPE_ONTOLOGY_ID:JS,keyZ:Xe,newZ:Dl,ontologyID:Wl,remoteZ:fi,retrieveArgsZ:Hl,schematicZ:sr,symbol:PS},Symbol.toStringTag,{value:"Module"})),gt=i.z.uuid(),di=i.z.object({key:gt,name:i.z.string(),data:fe.unknownZ.or(i.z.string().transform($e))}),Kl=di.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),yi=di.extend({data:i.z.string().transform($e)}),QS=i.z.object({key:gt,name:i.z.string()}),ek=i.z.object({key:gt,data:i.z.string()}),tk=i.z.object({keys:gt.array()}),nk=i.z.object({keys:gt.array()}),Jl=i.z.object({key:gt}).transform(({key:t})=>({keys:[t]})),Xl=i.z.union([Jl,nk]),rk=i.z.object({tables:N.nullableZ(yi)}),sk=i.z.object({workspace:Ie,tables:Kl.array()}),ik=i.z.object({tables:yi.array()}),Er=i.z.object({});let Ql=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await z(this.client,"/workspace/table/create",{workspace:e,tables:N.toArray(n)},sk,ik);return r?s.tables:s.tables[0]}async rename(e,n){await z(this.client,"/workspace/table/rename",{key:e,name:n},QS,Er)}async setData(e,n){await z(this.client,"/workspace/table/set-data",{key:e,data:JSON.stringify(n)},ek,Er)}async retrieve(e){const n=Jl.safeParse(e).success,r=await z(this.client,"/workspace/table/retrieve",e,Xl,rk);return se("Table",e,r.tables,n),n?r.tables[0]:r.tables}async delete(e){await z(this.client,"/workspace/table/delete",{keys:N.toArray(e)},tk,Er)}};const eh=V("table"),ak=eh(""),ok=Object.freeze(Object.defineProperty({__proto__:null,Client:Ql,TYPE_ONTOLOGY_ID:ak,keyZ:gt,newZ:Kl,ontologyID:eh,remoteZ:yi,retrieveArgsZ:Xl,tableZ:di},Symbol.toStringTag,{value:"Module"})),ck=i.z.object({keys:Ie.array().optional(),searchTerm:i.z.string().optional(),author:Ae.optional(),offset:i.z.int().optional(),limit:i.z.int().optional()}),uk=i.z.object({workspaces:Al.array()}),lk=i.z.object({key:Ie,name:i.z.string()}),hk=i.z.object({key:Ie,layout:fe.unknownZ.transform(t=>JSON.stringify(t))}),fk=i.z.object({keys:Ie.array()}),dk=i.z.object({workspaces:N.nullableZ(nr)}),yk=i.z.object({workspaces:$l.array()}),Nr=i.z.object({}),pk="sy_workspace_set",mk="sy_workspace_delete";class th{schematics;lineplots;logs;tables;client;constructor(e){this.client=e,this.schematics=new Vl(e),this.lineplots=new xl(e),this.logs=new Ml(e),this.tables=new Ql(e)}async create(e){const n=Array.isArray(e),r=await z(this.client,"/workspace/create",{workspaces:N.toArray(e)},uk,yk);return n?r.workspaces:r.workspaces[0]}async rename(e,n){await z(this.client,"/workspace/rename",{key:e,name:n},lk,Nr)}async setLayout(e,n){await z(this.client,"/workspace/set-layout",{key:e,layout:n},hk,Nr)}async retrieve(e){let n;const r=typeof e!="string";typeof e=="string"||Array.isArray(e)?n={keys:N.toArray(e)}:n=e;const s=await z(this.client,"/workspace/retrieve",n,ck,dk);return r?s.workspaces:s.workspaces[0]}async delete(e){await z(this.client,"/workspace/delete",{keys:N.toArray(e)},fk,Nr)}}const nh=V("workspace"),gk=nh(""),wk=Object.freeze(Object.defineProperty({__proto__:null,Client:th,DELETE_CHANNEL_NAME:mk,SET_CHANNEL_NAME:pk,TYPE_ONTOLOGY_ID:gk,keyZ:Ie,newZ:Al,ontologyID:nh,remoteZ:$l,workspaceZ:nr},Symbol.toStringTag,{value:"Module"})),rh=i.z.object({host:i.z.string({error:"Host is required"}).min(1,"Host is required"),port:i.z.number({error:"Port is required"}).or(i.z.string({error:"Port is required"})),username:i.z.string().min(1,"Username is required"),password:i.z.string().min(1,"Password is required"),connectivityPollFrequency:m.z.default(m.seconds(30)),secure:i.z.boolean().default(!1),name:i.z.string().optional(),retry:$s.breakerConfigZ.optional()});class sh extends Gu{createdAt;params;ranges;channels;auth;users;access;connectivity;ontology;workspaces;labels;statuses;tasks;racks;devices;control;arcs;views;static connectivity=_n;transport;clientVersion="0.50.0";constructor(e){const n=rh.parse(e),{host:r,port:s,username:a,password:o,connectivityPollFrequency:c,secure:l,retry:u}=n,h=new Ol(new Ot({host:r,port:Number(s)}),u,l);h.use(Ym);const d=new ei(new Qs(h.unary));super(h.stream,h.unary,d),this.auth=new kO(h.unary,{username:a,password:o}),h.use(this.auth.middleware());const f=new Au(h.unary,d);this.createdAt=w.now(),this.params=n,this.transport=h,this.channels=new ku(this,d,h.unary,f),this.connectivity=new _n(h.unary,c,this.clientVersion,n.name),this.control=new Wu(this),this.ontology=new Tc(h.unary,this);const O=new ll(this.transport.unary);this.labels=new Tu(this.transport.unary),this.statuses=new dl(this.transport.unary),this.ranges=new cl(this,O,this.transport.unary,d,this.labels,this.ontology),this.access=new Cc(this.transport.unary),this.users=new kc(this.transport.unary),this.workspaces=new th(this.transport.unary),this.tasks=new bl(this.transport.unary,this,this.ontology,this.ranges),this.racks=new sl(this.transport.unary,this.tasks),this.devices=new rl(this.transport.unary),this.arcs=new fu(this.transport.unary,this.transport.stream),this.views=new Nl(this.transport.unary)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stop()}}const bk=async t=>await ih(t).check(),ih=t=>{const{host:e,port:n,secure:r,name:s,retry:a}=t,o=$s.breakerConfigZ.optional().parse(a),c=new Ot({host:e,port:Number(n)}),l=new Ol(c,o,r);return new _n(l.unary,void 0,"0.50.0",s)},ah={host:"localhost",port:9090,username:"synnax",password:"seldon",retry:{maxRetries:4,baseInterval:m.seconds(1),scale:1.5}},oh=t=>new sh({...ah,...t}),vk=async(t,e)=>{const n=po.create(),r=await t.users.create({username:n,password:"test",firstName:"test",lastName:"test"}),s=await t.access.policies.create(e),a=await t.access.roles.create({name:"test",description:"test"});return await t.ontology.addChildren(Ds(a.key),Ms(s.key)),await t.access.roles.assign({user:r.key,role:a.key}),oh({username:n,password:"test"})};exports.AuthError=kt;exports.Channel=Cn;exports.ContiguityError=Bm;exports.DataType=y;exports.Density=C;exports.DisconnectedError=Pm;exports.Frame=F;exports.MultiSeries=Ho;exports.MultipleFoundError=Wt;exports.NotFoundError=Vt;exports.QueryError=He;exports.Rate=G;exports.RouteError=Kr;exports.Series=Q;exports.Synnax=sh;exports.TEST_CLIENT_PARAMS=ah;exports.TimeRange=x;exports.TimeSpan=m;exports.TimeStamp=w;exports.UnexpectedError=st;exports.ValidationError=H;exports.access=uw;exports.arc=MT;exports.channel=vO;exports.checkConnection=bk;exports.connection=IO;exports.control=lE;exports.createTestClient=oh;exports.createTestClientWithPolicy=vk;exports.device=OE;exports.framer=sE;exports.group=ag;exports.isCalculated=ti;exports.label=oO;exports.lineplot=gS;exports.log=SS;exports.newConnectionChecker=ih;exports.ontology=pg;exports.rack=ME;exports.ranger=bN;exports.schematic=XS;exports.status=IN;exports.synnaxParamsZ=rh;exports.table=ok;exports.task=KN;exports.user=Hg;exports.view=cS;exports.workspace=wk;
89
+ `,s=new TextEncoder;let a=!1,o=!1;const c=s0(e),{columns:u,columnsByIndexKey:l,emptyGroupStrings:h}=i0(e,c,n);let d=[],f=0,b=[];const N=O=>{for(const[S]of c){const A=O.get(S);if(A.length===0)continue;const C=(l.get(S)??[]).map(_=>O.get(_.key));for(let _=0;_<A.length;_++){const le=A.at(_,!0),ae=C.map(ge=>Ji.formatValue(ge.at(_,!0)));b.push({time:le,values:ae,indexKey:S})}}},k=(O,S=!1)=>{b.length>0&&(b.sort((C,_)=>Number(C.time-_.time)),f>0&&(d=d.slice(f),f=0),d=a0(d,b),b=[]);const A=[],D=d.length;for(;f<D&&A.length<O;){const C=d[f].time;if(!S&&d[D-1].time===C)break;const _=new Map;for(;f<D&&d[f].time===C;){const ae=d[f++];_.set(ae.indexKey,ae)}const le=[];for(const[ae]of c){const ge=_.get(ae);le.push(ge?.values.join(",")??h.get(ae)??"")}A.push(le.join(","))}return A};return new ReadableStream({async pull(O){try{if(o||(await t.seekFirst(),o=!0),!a){const C=u.map(_=>Ji.formatValue(_.header)).join(",");O.enqueue(s.encode(`${C}${r}`)),a=!0}d.length-f+b.length<Ma&&await t.next()&&N(t.value);const A=k(Ma);if(A.length>0&&O.enqueue(s.encode(`${A.join(r)}${r}`)),d.length-f===0||b.length===0){if(!await t.next()){const _=k(1/0,!0);_.length>0&&O.enqueue(s.encode(`${_.join(r)}${r}`)),await t.close(),O.close();return}N(t.value)}}catch(S){await t.close(),O.error(S)}},async cancel(){await t.close()}})},s0=t=>{const e=new Map;for(const n of t){if(n.index===0)continue;let r=e.get(n.index);r==null&&(r=[n.index],e.set(n.index,r)),!n.isIndex&&!r.includes(n.key)&&r.push(n.key)}return e},i0=(t,e,n)=>{const r=new Map(t.map(c=>[c.key,c])),s=[],a=new Map,o=new Map;for(const[c,u]of e){const l=[];for(const h of u){const d=r.get(h);if(d==null)throw new ct(`Channel ${h} not found`);const f={key:h,header:n?.[h]??n?.[d.name]??d.name};s.push(f),l.push(f)}a.set(c,l),o.set(c,",".repeat(l.length-1))}return{columns:s,columnsByIndexKey:a,emptyGroupStrings:o}},a0=(t,e)=>{const n=[];let r=0,s=0;for(;r<t.length&&s<e.length;)t[r].time<=e[s].time?n.push(t[r++]):n.push(e[s++]);return n.push(...t.slice(r),...e.slice(s)),n},Ma=1e3,o0=i.z.object({keys:i.z.number().array(),downsampleFactor:i.z.int(),throttleRate:G.z.optional()}),c0=i.z.object({frame:or}),Ra=i.z.object({channels:mt,downsampleFactor:i.z.int().default(1),throttleRate:G.z.default(new G(0)),useHighPerformanceCodec:i.z.boolean().default(!0)}),bi=Ra.or(mt.transform(t=>Ra.parse({channels:t}))),cl=(t,e)=>async n=>{const r=bi.parse(n),s=await cr.open(t,r.channels);r.useHighPerformanceCodec&&(e=e.withCodec(new QS(s.codec)));const a=await e.stream("/frame/stream",o0,c0),o=new u0(a,s,r.downsampleFactor,r.throttleRate);a.send({keys:Array.from(s.keys),downsampleFactor:r.downsampleFactor,throttleRate:r.throttleRate});const[,c]=await a.receive();if(c!=null)throw c;return o},ul=async(t,e,n)=>await cl(t,e)(n);class u0{stream;adapter;downsampleFactor;throttleRate;constructor(e,n,r=1,s=new G(0)){this.stream=new il("Streamer",e),this.adapter=n,this.downsampleFactor=r,this.throttleRate=s}get keys(){return Array.from(this.adapter.keys)}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ze.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new V((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e)&&this.stream.send({keys:Array.from(this.adapter.keys),downsampleFactor:this.downsampleFactor,throttleRate:this.throttleRate})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class ur{wrapped_=null;breaker;opener;config;constructor(e,n,r={}){this.opener=e,this.config=bi.parse(n);const{maxRetries:s=5e3,baseInterval:a=w.seconds(1),scale:o=1}=r??{};this.breaker=new Bs.Breaker({maxRetries:s,baseInterval:a,scale:o})}static async open(e,n,r){const s=new ur(e,n,r);return await s.runStreamer(),s}async runStreamer(){for(;;)try{this.wrapped_!=null&&this.wrapped_.close(),this.wrapped_=await this.opener(this.config),this.breaker.reset();return}catch(e){if(this.wrapped_=null,!await this.breaker.wait())throw e;console.error("failed to open streamer",e);continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=mt.parse(e);try{await this.wrapped.update(e)}catch{return await this.runStreamer(),await this.update(e)}}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ze.matches(e))return{done:!0,value:void 0};throw e}}async read(){try{const e=await this.wrapped.read();return this.breaker.reset(),e}catch(e){if(ze.matches(e))throw e;return await this.runStreamer(),await this.read()}}close(){this.wrapped.close()}get keys(){return this.wrapped.keys}[Symbol.asyncIterator](){return this}}class ll extends Qm.Observer{streamer;closePromise;constructor(e,n){super(n),this.streamer=e,this.closePromise=this.stream()}async update(e){await this.streamer.update(e)}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}}var sn=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(sn||{});const l0=new w(-1);class gs extends Ae.sub("writer_closed"){constructor(){super("WriterClosed")}}const h0=i.z.enum(sn).or(i.z.enum(["persist","stream","persistStream"]).transform(t=>{switch(t){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),hl=i.z.object({start:m.z.optional(),controlSubject:pe.subjectZ.optional(),authorities:i.z.union([pe.authorityZ.transform(t=>[t]),pe.authorityZ.array()]).default([pe.ABSOLUTE_AUTHORITY]),mode:h0.default(1),errOnUnauthorized:i.z.boolean().default(!1),enableAutoCommit:i.z.boolean().default(!0),autoIndexPersistInterval:w.z.default(w.SECOND),useHighPerformanceCodec:i.z.boolean().default(!0)}),f0=hl.extend({keys:L.array().optional()}),ja=hl.extend({channels:mt}),fl=ja.or(mt.transform(t=>ja.parse({channels:t,start:m.now()}))),d0=i.z.object({command:i.z.enum($e),config:f0.optional(),frame:or.optional(),buffer:i.z.instanceof(Uint8Array).optional()}),p0=i.z.object({command:i.z.enum($e),end:m.z,err:Le.payloadZ.optional()}),y0=i.z.tuple([i.z.union([i.z.record(L.or(Pe),pe.authorityZ),L.or(Pe),pe.authorityZ]),pe.authorityZ.optional()]).transform(([t,e])=>{if(pe.authorityZ.safeParse(t).success)return{keys:[],authorities:[t]};if(L.or(Pe).safeParse(t).success){if(e==null)throw new Error("authority is required when setting authority for a single channel");return{keys:[t],authorities:[e]}}const n=t;return{keys:Object.keys(n),authorities:Object.values(n)}});let dl=class pl{stream;adapter;closeErr=null;constructor(e,n){this.stream=e,this.adapter=n}static async _open(e,n,r){const s=fl.parse(r),a=await gi.open(e,s.channels);s.useHighPerformanceCodec&&(n=n.withCodec(new XS(a.codec)));const o=await n.stream("/frame/write",d0,p0),c=new pl(o,a);return await c.execute({command:$e.Open,config:{...s,keys:a.keys}}),c}async write(e,n){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const r=await this.adapter.adapt(e,n);this.stream.send({command:$e.Write,frame:r.toPayload()})}async setAuthority(e,n){if(this.closeErr!=null)throw this.closeErr;const r=y0.parse([e,n]),s={keys:await this.adapter.adaptParams(r.keys),authorities:r.authorities};await this.execute({command:$e.SetAuthority,config:s})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),m.ZERO):(await this.execute({command:$e.Commit})).end}async close(){await this.closeInternal(null)}async closeInternal(e){if(this.closeErr!=null)throw this.closeErr;for(this.closeErr=e,this.stream.closeSend();;){if(this.closeErr!=null){if(gs.matches(this.closeErr))return null;throw this.closeErr}const[n,r]=await this.stream.receive();r!=null?this.closeErr=ze.matches(r)?new gs:r:this.closeErr=Le.decode(n?.err)}}async execute(e){const n=this.stream.send(e);for(n!=null&&await this.closeInternal(n);;){const[r,s]=await this.stream.receive();s!=null&&await this.closeInternal(s);const a=Le.decode(r?.err);if(a!=null&&await this.closeInternal(a),r?.command==e.command)return r}}};const yl=J("framer"),m0=yl("");let ml=class{streamClient;retriever;deleter;reader;constructor(e,n,r){this.streamClient=e,this.retriever=r,this.deleter=new HS(n),this.reader=new ol(r,e)}async openIterator(e,n,r){return await bn._open(e,n,this.retriever,this.streamClient,r)}async openWriter(e){return await dl._open(this.retriever,this.streamClient,e)}async openStreamer(e){return await ul(this.retriever,this.streamClient,e)}async write(e,n,r){if(r==null){const a=n,o=await this.openWriter({start:e,channels:Object.keys(a),mode:sn.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:w.MAX});return await o.write(a),await o.close()}const s=await this.openWriter({start:e,channels:n,mode:sn.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:w.MAX});await s.write(n,r),await s.close()}async read(e,n){if(!("start"in e))return this.reader.read(e);const{single:r}=ve(n),s=await this.readFrame(e,n);return r?s.get(n):s}async readFrame(e,n){const r=await this.openIterator(e,n),s=new V;try{for await(const a of r)s.push(a)}finally{await r.close()}return s}async readLatest(e,n=1){const{single:r}=ve(e),s=await this.readLatestNFrame(e,n);return r?s.get(e):s}async readLatestNFrame(e,n){const r=await this.openIterator(x.MAX,e,{chunkSize:n}),s=new V;if(n>0)try{await r.seekLast(),await r.prev(Hn),s.push(r.value)}finally{await r.close()}return s}async delete(e,n){const{normalized:r,variant:s}=ve(e),a=new x(n);return s==="keys"?await this.deleter.delete({keys:r,bounds:a}):await this.deleter.delete({names:r,bounds:a})}};const g0=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:l0,AUTO_SPAN:Hn,Client:ml,Frame:V,HardenedStreamer:ur,Iterator:bn,ObservableStreamer:ll,Reader:ol,TYPE_ONTOLOGY_ID:m0,Writer:dl,WriterClosedError:gs,WriterCommand:$e,WriterMode:sn,createStreamOpener:cl,frameZ:or,ontologyID:yl,openStreamer:ul,seriesFromPayload:tl,seriesToPayload:nl,streamerConfigZ:bi,writerConfigZ:fl},Symbol.toStringTag,{value:"Module"})),w0=pe.ABSOLUTE_AUTHORITY,b0=pe.ZERO_AUTHORITY,v0=pe.stateZ(i.z.number()),z0=t=>t.to==null?`${t.from?.resource} - ${t.from?.subject.name} -> released`:t.from==null?`${t.to.resource} - released -> ${t.to.subject.name} (${t.to.authority.toString()})`:`${t.to.resource} - ${t.from.subject.name} -> ${t.to.subject.name} (${t.to.authority.toString()})`,T0=i.z.object({transfers:i.z.array(pe.transferZ(L))});class gl extends ll{states;codec;constructor(e){super(e,n=>{const r=this.codec.decode(n.series[0].buffer,T0);return this.merge(r),[r.transfers,!0]}),this.states=new Map,this.codec=new Jn.JSONCodec}subjects(){const e=new Map;return this.states.forEach(n=>e.set(n.subject.key,n.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const wl="sy_node_1_control";let bl=class{framer;constructor(e){this.framer=e}async openStateTracker(){const e=await ur.open(async n=>await this.framer.openStreamer(n),wl);return new gl(e)}};const O0=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:w0,CONTROL_STATE_CHANNEL_NAME:wl,Client:bl,StateTracker:gl,ZERO_AUTHORITY:b0,stateZ:v0,transferString:z0},Symbol.toStringTag,{value:"Module"})),Te=i.z.uint32(),vl=i.z.object({rack:Te}),zl=Qe.statusZ(vl),lr=i.z.object({key:Te,name:i.z.string(),status:be.nullToUndefined(zl)}),Tl=lr.partial({key:!0}),Mt=i.z.string(),Ol=i.z.object({rack:Te,device:Mt}),Sl=Qe.statusZ(Ol),hr=({properties:t,make:e,model:n}={})=>i.z.object({key:Mt,rack:Te.min(1,"Must select a location to connect from"),name:i.z.string().min(1,"Name is required"),make:e??i.z.string().min(1,"Make is required"),model:n??i.z.string().min(1,"Model is required"),location:i.z.string().min(1,"Location is required"),configured:i.z.boolean().optional(),properties:t??oe.nullishToEmpty(),status:be.nullToUndefined(Sl)}),El=(t={})=>hr(t).extend({properties:t?.properties??oe.nullishToEmpty()}),S0="sy_device_set",E0="sy_device_delete",N0=t=>i.z.object({devices:be.toArray(El(t))}),$0=t=>i.z.object({devices:hr(t).array()}),k0=i.z.object({keys:Mt.array()}),A0=i.z.object({}),I0=i.z.object({keys:Mt.array().optional(),names:i.z.string().array().optional(),makes:i.z.string().array().optional(),models:i.z.string().array().optional(),locations:i.z.string().array().optional(),racks:Te.array().optional(),searchTerm:i.z.string().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeStatus:i.z.boolean().optional()}),Z0=t=>i.z.object({devices:E.nullableZ(hr(t))}),x0=i.z.object({key:Mt,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),C0=i.z.union([x0,I0]);let Nl=class{client;constructor(e){this.client=e}async retrieve(e){const{schemas:n,...r}=e,s=typeof r=="object"&&"key"in r,a=await T(this.client,"/device/retrieve",r,C0,Z0(n));return ue("Device",r,a.devices,s),s?a.devices[0]:a.devices}async create(e,n){const r=!Array.isArray(e),s=await T(this.client,"/device/create",{devices:E.toArray(e)},N0(n),$0(n));return r?s.devices[0]:s.devices}async delete(e){await T(this.client,"/device/delete",{keys:E.toArray(e)},k0,A0)}};const vi=J("device"),_0=vi(""),M0=t=>ke(vi(t)),R0=Object.freeze(Object.defineProperty({__proto__:null,Client:Nl,DELETE_CHANNEL_NAME:E0,SET_CHANNEL_NAME:S0,TYPE_ONTOLOGY_ID:_0,deviceZ:hr,keyZ:Mt,newZ:El,ontologyID:vi,statusDetailsZ:Ol,statusKey:M0,statusZ:Sl},Symbol.toStringTag,{value:"Module"})),gt=i.z.uuid(),fr=i.z.object({key:gt,name:i.z.string(),data:oe.unknownZ.or(i.z.string().transform(Ze))}),$l=fr.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),xe=i.z.uuid(),dr=i.z.object({key:xe,name:i.z.string().min(1,"Name is required"),layout:oe.unknownZ.or(i.z.string().transform(Ze))}),kl=dr.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),Al=dr.omit({layout:!0}).extend({layout:i.z.string().transform(Ze)}),j0=i.z.object({keys:xe.array().optional(),searchTerm:i.z.string().optional(),author:Ie.optional(),offset:i.z.int().optional(),limit:i.z.int().optional()}),U0=i.z.object({workspaces:kl.array()}),P0=i.z.object({key:xe,name:i.z.string()}),L0=i.z.object({key:xe,layout:oe.unknownZ.transform(t=>JSON.stringify(t))}),D0=i.z.object({keys:xe.array()}),B0=i.z.object({workspaces:E.nullableZ(dr)}),q0=i.z.object({workspaces:Al.array()}),Rr=i.z.object({}),F0="sy_workspace_set",Y0="sy_workspace_delete";let Il=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await T(this.client,"/workspace/create",{workspaces:E.toArray(e)},U0,q0);return n?r.workspaces:r.workspaces[0]}async rename(e,n){await T(this.client,"/workspace/rename",{key:e,name:n},P0,Rr)}async setLayout(e,n){await T(this.client,"/workspace/set-layout",{key:e,layout:n},L0,Rr)}async retrieve(e){let n;const r=typeof e!="string";typeof e=="string"||Array.isArray(e)?n={keys:E.toArray(e)}:n=e;const s=await T(this.client,"/workspace/retrieve",n,j0,B0);return r?s.workspaces:s.workspaces[0]}async delete(e){await T(this.client,"/workspace/delete",{keys:E.toArray(e)},D0,Rr)}};const Zl=J("workspace"),H0=Zl(""),V0=Object.freeze(Object.defineProperty({__proto__:null,Client:Il,DELETE_CHANNEL_NAME:Y0,SET_CHANNEL_NAME:F0,TYPE_ONTOLOGY_ID:H0,keyZ:xe,newZ:kl,ontologyID:Zl,remoteZ:Al,workspaceZ:dr},Symbol.toStringTag,{value:"Module"})),G0=i.z.object({key:gt,name:i.z.string()}),W0=i.z.object({key:gt,data:i.z.string()}),J0=i.z.object({keys:gt.array()}),K0=i.z.object({keys:gt.array()}),xl=i.z.object({key:gt}).transform(({key:t})=>({keys:[t]})),Cl=i.z.union([xl,K0]),X0=i.z.object({linePlots:E.nullableZ(fr)}),Q0=i.z.object({workspace:xe,linePlots:$l.array()}),eE=i.z.object({linePlots:fr.array()}),jr=i.z.object({});let _l=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/lineplot/create",{workspace:e,linePlots:E.toArray(n)},Q0,eE);return r?s.linePlots:s.linePlots[0]}async rename(e,n){await T(this.client,"/lineplot/rename",{key:e,name:n},G0,jr)}async setData(e,n){await T(this.client,"/lineplot/set-data",{key:e,data:JSON.stringify(n)},W0,jr)}async retrieve(e){const n=xl.safeParse(e).success,r=await T(this.client,"/lineplot/retrieve",e,Cl,X0);return ue("LinePlot",e,r.linePlots,n),n?r.linePlots[0]:r.linePlots}async delete(e){await T(this.client,"/lineplot/delete",{keys:E.toArray(e)},J0,jr)}};const Ml=J("lineplot"),tE=Ml(""),nE=Object.freeze(Object.defineProperty({__proto__:null,Client:_l,TYPE_ONTOLOGY_ID:tE,keyZ:gt,linePlotZ:fr,newZ:$l,ontologyID:Ml,retrieveArgsZ:Cl},Symbol.toStringTag,{value:"Module"})),wt=i.z.uuid(),pr=i.z.object({key:wt,name:i.z.string(),data:oe.unknownZ.or(i.z.string().transform(Ze))}),Rl=pr.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),rE=i.z.object({key:wt,name:i.z.string()}),sE=i.z.object({key:wt,data:i.z.string()}),iE=i.z.object({keys:wt.array()}),aE=i.z.object({keys:wt.array()}),jl=i.z.object({key:wt}).transform(({key:t})=>({keys:[t]})),Ul=i.z.union([jl,aE]),oE=i.z.object({logs:E.nullableZ(pr)}),cE=i.z.object({workspace:xe,logs:Rl.array()}),uE=i.z.object({logs:pr.array()}),Ur=i.z.object({});let Pl=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/log/create",{workspace:e,logs:E.toArray(n)},cE,uE);return r?s.logs:s.logs[0]}async rename(e,n){await T(this.client,"/log/rename",{key:e,name:n},rE,Ur)}async setData(e,n){await T(this.client,"/log/set-data",{key:e,data:JSON.stringify(n)},sE,Ur)}async retrieve(e){const n=jl.safeParse(e).success,r=await T(this.client,"/log/retrieve",e,Ul,oE);return ue("Log",e,r.logs,n),n?r.logs[0]:r.logs}async delete(e){await T(this.client,"/log/delete",{keys:E.toArray(e)},iE,Ur)}};const Ll=J("log"),lE=Ll(""),hE=Object.freeze(Object.defineProperty({__proto__:null,Client:Pl,TYPE_ONTOLOGY_ID:lE,keyZ:wt,logZ:pr,newZ:Rl,ontologyID:Ll,retrieveArgsZ:Ul},Symbol.toStringTag,{value:"Module"})),fE="sy_rack_set",dE="sy_rack_delete",pE=i.z.object({keys:Te.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),embedded:i.z.boolean().optional(),hostIsNode:i.z.boolean().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeStatus:i.z.boolean().optional()}),yE=i.z.object({racks:E.nullableZ(lr)}),mE=i.z.union([i.z.object({key:Te,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),i.z.object({name:i.z.string(),includeStatus:i.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e}))]),gE=pE,wE=i.z.union([mE,gE]),bE=i.z.object({racks:Tl.array()}),vE=i.z.object({racks:lr.array()}),zE=i.z.object({keys:Te.array()}),TE=i.z.object({});let Dl=class{client;tasks;constructor(e,n){this.client=e,this.tasks=n}async delete(e){await T(this.client,"/rack/delete",{keys:E.toArray(e)},zE,TE)}async create(e){const n=!Array.isArray(e),r=await T(this.client,"/rack/create",{racks:E.toArray(e)},bE,vE),s=this.sugar(r.racks);return n?s[0]:s}async retrieve(e){const n="key"in e||"name"in e,r=await T(this.client,"/rack/retrieve",e,wE,yE),s=this.sugar(r.racks);return ue("Rack",e,s,n),n?s[0]:s}sugar(e){const n=!Array.isArray(e),r=E.toArray(e).map(({key:s,name:a,status:o})=>new Bl(s,a,this.tasks,o));return n?r[0]:r}};class Bl{key;name;status;tasks;constructor(e,n,r,s){this.key=e,this.name=n,this.tasks=r,this.status=s}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,n){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e,n)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status}}}const zi=J("rack"),OE=zi(0),SE=t=>ke(zi(t)),EE=Object.freeze(Object.defineProperty({__proto__:null,Client:Dl,DELETE_CHANNEL_NAME:dE,Rack:Bl,SET_CHANNEL_NAME:fE,TYPE_ONTOLOGY_ID:OE,keyZ:Te,newZ:Tl,ontologyID:zi,rackZ:lr,statusDetailsZ:vl,statusKey:SE,statusZ:zl},Symbol.toStringTag,{value:"Module"})),ql="sy_range_alias_set",Fl="sy_range_alias_delete",NE=i.z.object({alias:i.z.string().optional(),channel:L,range:X}),Yl="---",Hl=t=>`${t.range}${Yl}${t.channel}`,Vl=t=>{const[e,n]=t.split(Yl);return{range:e,channel:Number(n)}},$E=Object.freeze(Object.defineProperty({__proto__:null,DELETE_CHANNEL_NAME:Fl,SET_CHANNEL_NAME:ql,aliasZ:NE,createKey:Hl,decodeDeleteChange:Vl},Symbol.toStringTag,{value:"Module"})),kE=i.z.object({range:X,aliases:i.z.string().array()}),AE=i.z.object({aliases:i.z.record(i.z.string(),L)}),IE=i.z.object({range:X,aliases:i.z.record(L,i.z.string())}),ZE=i.z.unknown(),xE=i.z.object({range:X,channels:L.array()}),CE=i.z.unknown(),_E=i.z.object({range:X}),ME=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())}),RE=i.z.object({range:X,channels:L.array()}),jE=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())});let vt=class{cache=new Map;client;rangeKey;constructor(e,n){this.rangeKey=e,this.cache=new Map,this.client=n}async resolve(e){const n=[],r=typeof e=="string",s={};if(r){const o=this.cache.get(e);if(o!=null)return o;n.push(e)}else e.forEach(o=>{const c=this.cache.get(o);c!=null?s[o]=c:n.push(o)});if(n.length===0)return s;const a=await T(this.client,"/range/alias/resolve",{range:this.rangeKey,aliases:n},kE,AE);return Object.entries(a.aliases).forEach(([o,c])=>this.cache.set(o,c)),r?a.aliases[n[0]]:{...s,...a.aliases}}async set(e){await T(this.client,"/range/alias/set",{range:this.rangeKey,aliases:e},IE,ZE)}async list(){return(await T(this.client,"/range/alias/list",{range:this.rangeKey},_E,ME)).aliases}async retrieve(e){const n=typeof e=="number",r=await T(this.client,"/range/alias/retrieve",{range:this.rangeKey,channels:E.toArray(e)},RE,jE);return n?r.aliases[e]:r.aliases}async delete(e){await T(this.client,"/range/alias/delete",{range:this.rangeKey,channels:E.toArray(e)},xE,CE)}};const Gl="sy_range_kv_set",Wl="sy_range_kv_delete",yr=i.z.object({range:X,key:i.z.string(),value:i.z.string()}),Jl=({range:t,key:e})=>`${t}<--->${e}`,UE=i.z.object({range:X,keys:i.z.string().array()}),PE=i.z.object({pairs:E.nullableZ(yr)}),LE=i.z.object({range:X,pairs:yr.array()}),DE=i.z.object({range:X,keys:i.z.string().array()});let Ua=class{rangeKey;client;constructor(e,n){this.rangeKey=e,this.client=n}async get(e){const n=await T(this.client,"/range/kv/get",{range:this.rangeKey,keys:E.toArray(e)},UE,PE);return typeof e=="string"?n.pairs[0].value:Object.fromEntries(n.pairs.map(r=>[r.key,r.value]))}async list(){return this.get([])}async set(e,n=""){let r;typeof e=="string"?r=[{range:this.rangeKey,key:e,value:n}]:r=Object.entries(e).map(([s,a])=>({range:this.rangeKey,key:s,value:a})),await T(this.client,"/range/kv/set",{range:this.rangeKey,pairs:r},LE,i.z.unknown())}async delete(e){await T(this.client,"/range/kv/delete",{range:this.rangeKey,keys:E.toArray(e)},DE,i.z.unknown())}};const BE="sy_range_set",qE="sy_range_delete";class Kl{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:n=x.ZERO,key:r,color:s,parent:a,labels:o},{frameClient:c,kv:u,aliaser:l,channels:h,labelClient:d,ontologyClient:f,rangeClient:b}){this.key=r,this.name=e,this.timeRange=n,this.parent=a,this.labels=o,this.frameClient=c,this.color=s,this.kv=u,this.aliaser=l,this.channels=h,this.labelClient=d,this.ontologyClient=f,this.rangeClient=b}get ontologyID(){return st(this.key)}get payload(){let e=null;return this.parent!=null&&("payload"in this.parent?e=this.parent.payload:e=this.parent),{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels,parent:e}}async setAlias(e,n){const r=await this.channels.retrieve(e);if(r.length===0)throw new Ke(`Channel ${e} does not exist`);await this.aliaser.set({[r[0].key]:n})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(n=>n.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async retrieveLabels(){return await this.labelClient.retrieve({for:st(this.key)})}async addLabel(...e){await this.labelClient.label(st(this.key),e)}async removeLabel(...e){await this.labelClient.remove(st(this.key),e)}static sort(e,n){return x.sort(e.timeRange,n.timeRange)}}const FE=i.z.object({keys:X.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),overlapsWith:x.z.optional(),hasLabels:nt.array().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeLabels:i.z.boolean().optional(),includeParent:i.z.boolean().optional()}),YE=FE.or(X.array().transform(t=>({keys:t}))).or(X.transform(t=>({keys:[t]}))).or(i.z.string().transform(t=>({names:[t]}))).or(i.z.string().array().transform(t=>({names:t}))).or(x.z.transform(t=>({overlapsWith:t}))),HE=i.z.object({ranges:E.nullableZ(gn)});let Xl=class{type="range";frameClient;writer;unaryClient;channels;labelClient;ontologyClient;constructor(e,n,r,s,a,o){this.frameClient=e,this.writer=n,this.unaryClient=r,this.channels=s,this.labelClient=a,this.ontologyClient=o}async create(e,n){const r=!Array.isArray(e),s=this.sugarMany(await this.writer.create(E.toArray(e),n));return r?s[0]:s}async rename(e,n){await this.writer.rename(e,n)}async delete(e){await this.writer.delete(E.toArray(e))}async retrieve(e){const n=typeof e=="string",{ranges:r}=await T(this.unaryClient,"/range/retrieve",e,YE,HE);return ue("Range",e,r,n),n?this.sugarMany(r)[0]:this.sugarMany(r)}getKV(e){return new Ua(e,this.unaryClient)}async retrieveParent(e){const n=await this.ontologyClient.retrieveParents(st(e));if(n.length===0)return null;const r=n[0];return r.id.type!=="range"?null:await this.retrieve(r.id.key)}sugarOntologyResource(e){return this.sugarOne(Ql(e))}async retrieveAlias(e,n){return await new vt(e,this.unaryClient).retrieve(n)}async retrieveAliases(e,n){return await new vt(e,this.unaryClient).retrieve(n)}async listAliases(e){return await new vt(e,this.unaryClient).list()}async setAlias(e,n,r){await new vt(e,this.unaryClient).set({[n]:r})}async deleteAlias(e,n){await new vt(e,this.unaryClient).delete(n)}sugarOne(e){return new Kl(e,{frameClient:this.frameClient,kv:new Ua(e.key,this.unaryClient),aliaser:new vt(e.key,this.unaryClient),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(e){return e.map(n=>this.sugarOne(n))}resourceToRange(e){return this.sugarOne({key:e.id.key,name:e.data?.name,timeRange:new x(e.data?.timeRange),color:e.data?.color,labels:[],parent:null})}};const st=J("range"),VE=st(""),GE=t=>({type:"range-alias",key:t}),Ql=({data:t,id:{key:e},name:n})=>{const r=x.z.parse(t?.timeRange),s=yc.colorZ.safeParse(t?.color);return{key:e,name:n,timeRange:r,color:s.success?s.data:void 0,labels:[],parent:null}},WE=Object.freeze(Object.defineProperty({__proto__:null,DELETE_CHANNEL:Wl,SET_CHANNEL:Gl,createPairKey:Jl,pairZ:yr},Symbol.toStringTag,{value:"Module"})),JE=i.z.object({ranges:gn.array()}),KE=i.z.object({parent:B.optional(),ranges:Hu.array()}),XE=i.z.object({keys:X.array()}),QE=i.z.object({}),eN=i.z.object({key:X,name:fi}),tN=i.z.object({});class eh{client;constructor(e){this.client=e}async rename(e,n){await T(this.client,"/range/rename",{key:e,name:n},eN,tN)}async create(e,n){return(await T(this.client,"/range/create",{ranges:e,...n},KE,JE)).ranges}async delete(e){await T(this.client,"/range/delete",{keys:e},XE,QE)}}const nN=Object.freeze(Object.defineProperty({__proto__:null,Client:Xl,DELETE_ALIAS_CHANNEL_NAME:Fl,DELETE_CHANNEL_NAME:qE,KV_DELETE_CHANNEL:Wl,KV_SET_CHANNEL:Gl,Range:Kl,SET_ALIAS_CHANNEL_NAME:ql,SET_CHANNEL_NAME:BE,TYPE_ONTOLOGY_ID:VE,Writer:eh,alias:$E,aliasKey:Hl,aliasOntologyID:GE,convertOntologyResourceToPayload:Ql,decodeDeleteAliasChange:Vl,keyZ:X,kv:WE,kvPairKey:Jl,kvPairZ:yr,nameZ:fi,newZ:Hu,ontologyID:st,payloadZ:gn},Symbol.toStringTag,{value:"Module"})),rt=i.z.uuid(),mr=i.z.object({key:rt,name:i.z.string(),data:oe.unknownZ.or(i.z.string().transform(Ze)),snapshot:i.z.boolean()}),th=mr.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Ti=mr.extend({data:i.z.string().transform(Ze)}),Rt=i.z.uuid(),nh=i.z.object({key:i.z.string(),name:i.z.string(),selectors:i.z.string().array().default([]),strokeColor:i.z.string().optional(),fillColor:i.z.string().optional()}),rh=i.z.object({key:i.z.string(),name:i.z.string(),regions:nh.array()}),sh=i.z.object({key:i.z.string(),position:Ps.xy,orientation:iy.outer}),rN=i.z.object({zoom:i.z.number().positive().default(1),position:Ps.xy}),ih=i.z.object({svg:i.z.string().min(1,"SVG is required"),states:rh.array(),variant:i.z.string().min(1,"Variant is required"),handles:sh.array(),scale:i.z.number().positive().default(1),scaleStroke:i.z.boolean().default(!1),previewViewport:rN.default({zoom:1,position:{x:0,y:0}})}),gr=i.z.object({key:Rt,version:i.z.literal(1).default(1),name:i.z.string().min(1,"Name is required"),data:ih}),ah=gr.partial({key:!0}),sN=i.z.object({symbols:ah.array(),parent:B}),iN=i.z.object({key:Rt,name:i.z.string()}),aN=i.z.object({keys:Rt.array()}),oN=i.z.object({keys:Rt.array().optional(),searchTerm:i.z.string().optional()}),cN=i.z.object({key:Rt}).transform(({key:t})=>({keys:[t]})),uN=i.z.union([cN,oN]),lN=i.z.object({symbols:E.nullableZ(gr)}),hN=i.z.object({symbols:gr.array()}),Pa=i.z.object({}),fN=i.z.object({}),dN=i.z.object({group:ar}),pN="sy_schematic_symbol_set",yN="sy_schematic_symbol_delete";let oh=class{client;constructor(e){this.client=e}async create(e){const n="symbols"in e,r=n?e.symbols:[e],s=await T(this.client,"/schematic/symbol/create",{symbols:r,parent:e.parent},sN,hN);return n?s.symbols:s.symbols[0]}async rename(e,n){await T(this.client,"/schematic/symbol/rename",{key:e,name:n},iN,Pa)}async retrieve(e){const n="key"in e,r=await T(this.client,"/schematic/symbol/retrieve",e,uN,lN);return ue("Schematic Symbol",e,r.symbols,n),n?r.symbols[0]:r.symbols}async delete(e){await T(this.client,"/schematic/symbol/delete",{keys:E.toArray(e)},aN,Pa)}async retrieveGroup(){return(await T(this.client,"/schematic/symbol/retrieve-group",{},fN,dN)).group}};const mN=J("schematic_symbol"),gN=Object.freeze(Object.defineProperty({__proto__:null,Client:oh,DELETE_CHANNEL_NAME:yN,SET_CHANNEL_NAME:pN,handleZ:sh,keyZ:Rt,newZ:ah,ontologyID:mN,regionZ:nh,specZ:ih,stateZ:rh,symbolZ:gr},Symbol.toStringTag,{value:"Module"})),wN=i.z.object({key:rt,name:i.z.string()}),bN=i.z.object({key:rt,data:i.z.string()}),vN=i.z.object({keys:rt.array()}),zN=i.z.object({key:rt,name:i.z.string(),snapshot:i.z.boolean()}),TN=i.z.object({keys:rt.array()}),ch=i.z.object({key:rt}).transform(({key:t})=>({keys:[t]})),uh=i.z.union([ch,TN]),ON=i.z.object({schematics:E.nullableZ(Ti)}),SN=i.z.object({workspace:xe,schematics:th.array()}),EN=i.z.object({schematics:Ti.array()}),NN=i.z.object({schematic:mr}),Pr=i.z.object({});let lh=class{symbols;client;constructor(e){this.client=e,this.symbols=new oh(e)}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/schematic/create",{workspace:e,schematics:E.toArray(n)},SN,EN);return r?s.schematics:s.schematics[0]}async rename(e,n){await T(this.client,"/schematic/rename",{key:e,name:n},wN,Pr)}async setData(e,n){await T(this.client,"/schematic/set-data",{key:e,data:JSON.stringify(n)},bN,Pr)}async retrieve(e){const n=ch.safeParse(e).success,r=await T(this.client,"/schematic/retrieve",e,uh,ON);return ue("Schematic",e,r.schematics,n),n?r.schematics[0]:r.schematics}async delete(e){await T(this.client,"/schematic/delete",{keys:E.toArray(e)},vN,Pr)}async copy(e){return(await T(this.client,"/schematic/copy",e,zN,NN)).schematic}};const hh=J("schematic"),$N=hh(""),kN=Object.freeze(Object.defineProperty({__proto__:null,Client:lh,TYPE_ONTOLOGY_ID:$N,keyZ:rt,newZ:th,ontologyID:hh,remoteZ:Ti,retrieveArgsZ:uh,schematicZ:mr,symbol:gN},Symbol.toStringTag,{value:"Module"})),vn=i.z.string(),wr=t=>Qe.statusZ(t),fh=t=>wr(t).omit({labels:!0}).extend({key:vn.optional()}),ws="sy_status_set",AN="sy_status_delete",dh=J("status"),IN=dh(""),ZN=t=>i.object({parent:B.optional(),statuses:fh(t).array()}),xN=t=>i.object({statuses:wr(t).array()}),CN=i.object({keys:vn.array()}),_N=i.object({}),MN=i.object({keys:vn.array().optional(),searchTerm:i.string().optional(),offset:i.int().optional(),limit:i.int().optional(),includeLabels:i.boolean().optional(),hasLabels:nt.array().optional()}),RN=i.object({key:vn,includeLabels:i.boolean().optional()}).transform(({key:t,includeLabels:e})=>({keys:[t],includeLabels:e})),jN=i.union([RN,MN]),UN=t=>i.object({statuses:E.nullableZ(wr(t))});let ph=class{type="status";client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await T(this.client,"/status/retrieve",e,jN,UN(e.detailsSchema));ue("Status",e,r.statuses,n);const s=r.statuses;return n?s[0]:s}async set(e,n={}){const r=Array.isArray(e),a=(await T(this.client,"/status/set",{statuses:E.toArray(e),parent:n.parent},ZN(n.detailsSchema),xN(n.detailsSchema))).statuses;return r?a:a[0]}async delete(e){await T(this.client,"/status/delete",{keys:E.toArray(e)},CN,_N)}};const PN=Object.freeze(Object.defineProperty({__proto__:null,Client:ph,DELETE_CHANNEL_NAME:AN,SET_CHANNEL_NAME:ws,TYPE_ONTOLOGY_ID:IN,keyZ:vn,newZ:fh,ontologyID:dh,statusZ:wr},Symbol.toStringTag,{value:"Module"})),bt=i.z.uuid(),Oi=i.z.object({key:bt,name:i.z.string(),data:oe.unknownZ.or(i.z.string().transform(Ze))}),yh=Oi.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Si=Oi.extend({data:i.z.string().transform(Ze)}),LN=i.z.object({key:bt,name:i.z.string()}),DN=i.z.object({key:bt,data:i.z.string()}),BN=i.z.object({keys:bt.array()}),qN=i.z.object({keys:bt.array()}),mh=i.z.object({key:bt}).transform(({key:t})=>({keys:[t]})),gh=i.z.union([mh,qN]),FN=i.z.object({tables:E.nullableZ(Si)}),YN=i.z.object({workspace:xe,tables:yh.array()}),HN=i.z.object({tables:Si.array()}),Lr=i.z.object({});let wh=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/table/create",{workspace:e,tables:E.toArray(n)},YN,HN);return r?s.tables:s.tables[0]}async rename(e,n){await T(this.client,"/table/rename",{key:e,name:n},LN,Lr)}async setData(e,n){await T(this.client,"/table/set-data",{key:e,data:JSON.stringify(n)},DN,Lr)}async retrieve(e){const n=mh.safeParse(e).success,r=await T(this.client,"/table/retrieve",e,gh,FN);return ue("Table",e,r.tables,n),n?r.tables[0]:r.tables}async delete(e){await T(this.client,"/table/delete",{keys:E.toArray(e)},BN,Lr)}};const bh=J("table"),VN=bh(""),GN=Object.freeze(Object.defineProperty({__proto__:null,Client:wh,TYPE_ONTOLOGY_ID:VN,keyZ:bt,newZ:yh,ontologyID:bh,remoteZ:Si,retrieveArgsZ:gh,tableZ:Oi},Symbol.toStringTag,{value:"Module"})),De=i.z.union([i.z.string(),i.z.bigint().transform(t=>t.toString()),i.z.number().transform(t=>t.toString())]),Ei=t=>i.z.object({task:De,running:i.z.boolean(),data:t,cmd:i.z.string().optional()}),Ni=t=>Qe.statusZ(Ei(t)),WN=t=>Ei(t).partial({task:!0}),vh=t=>Qe.statusZ(WN(t)).partial({key:!0,name:!0}),zn=(t={type:i.z.string(),config:oe.nullishToEmpty(),statusData:i.z.unknown()})=>i.z.object({key:De,name:i.z.string(),type:t.type,internal:i.z.boolean().optional(),config:t.config,status:Ni(t.statusData).optional().nullable(),snapshot:i.z.boolean().optional()}),zh=t=>zn(t).omit({key:!0,status:!0}).extend({key:De.transform(e=>e.toString()).optional(),config:t?.config??oe.nullishToEmpty(),status:vh(t?.statusData??i.z.unknown()).optional().nullable()}),JN=i.z.object({task:De,type:i.z.string(),key:i.z.string(),args:oe.unknownZ.or(i.z.string().transform(Ze)).or(i.z.array(i.z.unknown())).or(i.z.null()).optional()}),KN=t=>Number(BigInt(t)>>32n),XN=(t,e=0)=>((BigInt(t)<<32n)+BigInt(e)).toString(),bs="sy_task_cmd",QN="sy_task_set",e$="sy_task_delete",it=new Error("Task not created"),Th=async(t,e)=>{const n=await e.retrieveParents(Tn(t));return n.length===0?null:n[0]};class Oh{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw it;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw it;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw it;return this.rangeClient_}constructor({key:e,type:n,name:r,config:s,internal:a=!1,snapshot:o=!1,status:c},u,l,h,d){this.key=e,this.name=r,this.type=n,this.config=s,this.schemas=u??{type:i.z.string(),config:i.z.unknown(),statusData:i.z.unknown()},this.internal=a,this.snapshot=o,this.status=c,this.frameClient_=l,this.ontologyClient_=h,this.rangeClient_=d}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return Tn(this.key)}async executeCommand(e){return await Nh({...e,frameClient:this.frameClient,task:this.key})}async executeCommandSync(e){return await $h({...e,frameClient:this.frameClient,task:this.key,name:this.name,statusDataZ:this.schemas.statusData})}async start(){await this.executeCommand({type:"start"})}async stop(){await this.executeCommand({type:"stop"})}async run(e){await this.start();try{return await e()}finally{await this.stop()}}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw it;return this.snapshot?await Th(this.key,this.ontologyClient):null}}const t$=i.z.object({rack:Te.optional(),keys:De.array().optional(),names:i.z.string().array().optional(),types:i.z.string().array().optional(),includeStatus:i.z.boolean().optional(),internal:i.z.boolean().optional(),snapshot:i.z.boolean().optional(),searchTerm:i.z.string().optional(),offset:i.z.int().optional(),limit:i.z.int().optional()}),Sh=i.z.union([i.z.object({key:De,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),i.z.object({name:i.z.string(),includeStatus:i.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),i.z.object({type:i.z.string(),rack:Te.optional()}).transform(({type:t,rack:e})=>({types:[t],rack:e}))]),n$=t$,r$=i.z.union([Sh,n$]),s$=t=>i.z.object({tasks:E.nullableZ(zn(t))}),i$=t=>i.z.object({tasks:zh(t).array()}),a$=t=>i.z.object({tasks:zn(t).array()}),o$=i.z.object({keys:De.array()}),c$=i.z.object({}),u$=i.z.object({key:De,name:i.z.string(),snapshot:i.z.boolean()}),l$=t=>i.z.object({task:zn(t)});let Eh=class{client;frameClient;ontologyClient;rangeClient;constructor(e,n,r,s){this.client=e,this.frameClient=n,this.ontologyClient=r,this.rangeClient=s}async create(e,n){const r=!Array.isArray(e),s=i$(n),a=a$(n),o=await T(this.client,"/task/create",{tasks:E.toArray(e)},s,a),c=this.sugar(o.tasks,n);return r?c[0]:c}async delete(e){await T(this.client,"/task/delete",{keys:E.toArray(e)},o$,c$)}async retrieve({schemas:e,...n}){const r=Sh.safeParse(n).success,a=(await T(this.client,"/task/retrieve",n,r$,s$(e))).tasks,o=this.sugar(a,e);return ue("Task",n,o,r),r?o[0]:o}async copy(e,n,r){const s=l$(),a=await T(this.client,"/task/copy",{key:e,name:n,snapshot:r},u$,s);return this.sugar(a.task)}async list(e){const n={internal:!1};return e!==void 0&&(n.rack=e),await this.retrieve(n)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw it;return await Th(e,this.ontologyClient)}sugar(e,n){const r=!Array.isArray(e),s=E.toArray(e).map(({key:a,name:o,type:c,config:u,status:l,internal:h,snapshot:d})=>new Oh({key:a,name:o,type:c,config:u,internal:h,snapshot:d,status:l},n,this.frameClient,this.ontologyClient,this.rangeClient));return r?s[0]:s}async executeCommand(e){return"commands"in e?await $i({...e,frameClient:this.frameClient}):await Nh({...e,frameClient:this.frameClient})}async executeCommandSync(e){if("commands"in e){const r=async()=>{const{commands:s}=e;return(await this.retrieve({keys:s.map(o=>o.task)})).map(o=>o.name)};return await kh({...e,frameClient:this.frameClient,name:r})}const n=async()=>{const{task:r}=e;return(await this.retrieve({key:r})).name};return await $h({frameClient:this.frameClient,name:n,...e})}};const Tn=J("task"),h$=Tn(""),f$=t=>ke(Tn(t)),Nh=async({frameClient:t,task:e,type:n,args:r})=>(await $i({frameClient:t,commands:[{args:r,task:e,type:n}]}))[0],$i=async({frameClient:t,commands:e})=>{if(t==null)throw it;const n=await t.openWriter(bs),r=e.map(s=>({...s,key:Co.create()}));return await n.write(bs,r),await n.close(),r.map(s=>s.key)},$h=async({frameClient:t,task:e,type:n,timeout:r,name:s,statusDataZ:a,args:o})=>(await kh({frameClient:t,commands:[{args:o,task:e,type:n}],timeout:r,statusDataZ:a,name:s}))[0],kh=async({frameClient:t,commands:e,timeout:n=w.seconds(10),statusDataZ:r,name:s})=>{if(t==null)throw it;const a=await t.openStreamer(ws),o=await $i({frameClient:t,commands:e}),c=new w(n);let u=[],l;const h=new Promise((d,f)=>{l=setTimeout(()=>{(async()=>{const b=e.map(N=>N.task);f(await d$("command",s,c,b))})()},c.milliseconds)});try{for(;;){const d=await Promise.race([a.read(),h]),f=Ni(r).safeParse(d.at(-1)[ws]);if(!f.success)continue;const b=f.data;if(!(b.details.cmd==null||!o.includes(b.details.cmd))&&(u=[...u.filter(N=>N.key!==b.key),b],u.length===o.length))return u}}finally{clearTimeout(l),a.close()}},d$=async(t,e,n,r)=>{const s=Gd.capitalize(t),a=n.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=E.toArray(await e());const c=os.naturalLanguageJoin(o);return new Error(`${s} command to ${c} timed out after ${a}`)}catch(o){return console.error("Failed to retrieve task name for timeout error:",o),new Error(`${s} command to task with key ${os.naturalLanguageJoin(r)} timed out after ${a}`)}},p$=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:bs,Client:Eh,DELETE_CHANNEL_NAME:e$,SET_CHANNEL_NAME:QN,TYPE_ONTOLOGY_ID:h$,Task:Oh,commandZ:JN,keyZ:De,newKey:XN,newStatusZ:vh,newZ:zh,ontologyID:Tn,rackKey:KN,statusDetailsZ:Ei,statusKey:f$,statusZ:Ni,taskZ:zn},Symbol.toStringTag,{value:"Module"}));class Ah{url;unary;stream;secure;constructor(e,n={},r=!1){this.secure=r,this.url=e.child("/api/v1/");const s=new Jn.JSONCodec;this.unary=Zd(new Id(this.url,s,this.secure),n),this.stream=new Rd(this.url,s,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const jt=i.uuid(),br=i.object({key:jt,name:i.string(),type:i.string(),query:oe.unknownZ}),Ih=br.extend({key:jt.optional()}),y$="sy_view_set",m$="sy_view_delete",g$=i.z.object({views:Ih.array()}),w$=i.z.object({views:br.array()}),b$=i.z.object({keys:jt.array()}),v$=i.z.object({}),z$=i.z.object({keys:jt.array().optional(),types:i.z.string().array().optional(),searchTerm:i.z.string().optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),T$=i.z.object({key:jt}).transform(({key:t})=>({keys:[t]})),O$=i.z.union([T$,z$]),S$=i.z.object({views:E.nullableZ(br)});class Zh{client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await T(this.client,"/view/retrieve",e,O$,S$);return ue("View",e,r.views,n),n?r.views[0]:r.views}async create(e){const n=Array.isArray(e),r=await T(this.client,"/view/create",{views:E.toArray(e)},g$,w$);return n?r.views:r.views[0]}async delete(e){await T(this.client,"/view/delete",{keys:E.toArray(e)},b$,v$)}}const xh=t=>({type:"view",key:t}),E$=xh(""),N$=Object.freeze(Object.defineProperty({__proto__:null,Client:Zh,DELETE_CHANNEL_NAME:m$,SET_CHANNEL_NAME:y$,TYPE_ONTOLOGY_ID:E$,keyZ:jt,newZ:Ih,ontologyID:xh,viewZ:br},Symbol.toStringTag,{value:"Module"})),Ch=i.z.object({host:i.z.string({error:"Host is required"}).min(1,"Host is required"),port:i.z.number({error:"Port is required"}).or(i.z.string({error:"Port is required"})),username:i.z.string().min(1,"Username is required"),password:i.z.string().min(1,"Password is required"),connectivityPollFrequency:w.z.default(w.seconds(30)),secure:i.z.boolean().default(!1),name:i.z.string().optional(),retry:Bs.breakerConfigZ.optional()});class _h extends ml{createdAt;params;ranges;channels;auth;users;access;connectivity;ontology;workspaces;labels;statuses;tasks;racks;devices;control;arcs;views;schematics;lineplots;logs;tables;groups;static connectivity=Yn;transport;clientVersion="0.53.0";constructor(e){const n=Ch.parse(e),{host:r,port:s,username:a,password:o,connectivityPollFrequency:c,secure:u,retry:l}=n,h=new Ah(new St({host:r,port:Number(s)}),l,u);h.use(_g);const d=new pi(new di(h.unary));super(h.stream,h.unary,d),this.auth=new LS(h.unary,{username:a,password:o}),h.use(this.auth.middleware());const f=new Xu(h.unary,d);this.createdAt=m.now(),this.params=n,this.transport=h,this.channels=new Ku(this,d,h.unary,f),this.connectivity=new Yn(h.unary,c,this.clientVersion,n.name),this.control=new bl(this),this.ontology=new Pc(this.transport.unary);const b=new eh(this.transport.unary);this.labels=new Fu(this.transport.unary),this.statuses=new ph(this.transport.unary),this.ranges=new Xl(this,b,this.transport.unary,d,this.labels,this.ontology),this.access=new Jc(this.transport.unary),this.users=new Fc(this.transport.unary),this.workspaces=new Il(this.transport.unary),this.tasks=new Eh(this.transport.unary,this,this.ontology,this.ranges),this.racks=new Dl(this.transport.unary,this.tasks),this.devices=new Nl(this.transport.unary),this.arcs=new Mu(this.transport.unary,this.transport.stream),this.views=new Zh(this.transport.unary),this.schematics=new lh(this.transport.unary),this.lineplots=new _l(this.transport.unary),this.logs=new Pl(this.transport.unary),this.tables=new wh(this.transport.unary),this.groups=new Ju(this.transport.unary)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stop()}}const $$=async t=>await Mh(t).check(),Mh=t=>{const{host:e,port:n,secure:r,name:s,retry:a}=t,o=Bs.breakerConfigZ.optional().parse(a),c=new St({host:e,port:Number(n)}),u=new Ah(c,o,r);return new Yn(u.unary,void 0,"0.53.0",s)},Rh={host:"localhost",port:9090,username:"synnax",password:"seldon",retry:{maxRetries:4,baseInterval:w.seconds(1),scale:1.5}},jh=t=>new _h({...Rh,...t}),k$=async(t,e)=>{const n=Co.create(),r=await t.users.create({username:n,password:"test",firstName:"test",lastName:"test"}),s=await t.access.policies.create(e),a=await t.access.roles.create({name:"test",description:"test"});return await t.ontology.addChildren(Qs(a.key),Ks(s.key)),await t.access.roles.assign({user:r.key,role:a.key}),jh({username:n,password:"test"})};exports.AuthError=kt;exports.Channel=Fn;exports.ContiguityError=Zg;exports.DataType=p;exports.Density=M;exports.DisconnectedError=Ig;exports.Frame=V;exports.MultiSeries=uc;exports.MultipleFoundError=tn;exports.NotFoundError=en;exports.QueryError=Ke;exports.Rate=G;exports.RouteError=ls;exports.Series=te;exports.Synnax=_h;exports.TEST_CLIENT_PARAMS=Rh;exports.TimeRange=x;exports.TimeSpan=w;exports.TimeStamp=m;exports.UnexpectedError=ct;exports.ValidationError=W;exports.access=Fw;exports.arc=DO;exports.channel=CS;exports.checkConnection=$$;exports.connection=qS;exports.control=O0;exports.createTestClient=jh;exports.createTestClientWithPolicy=k$;exports.device=R0;exports.framer=g0;exports.group=TS;exports.isCalculated=yi;exports.label=fS;exports.lineplot=nE;exports.log=hE;exports.newConnectionChecker=Mh;exports.ontology=Jg;exports.rack=EE;exports.ranger=nN;exports.schematic=kN;exports.status=PN;exports.synnaxParamsZ=Ch;exports.table=GN;exports.task=p$;exports.user=kw;exports.view=N$;exports.workspace=V0;