@synnaxlabs/client 0.48.0 → 0.49.2

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 (300) hide show
  1. package/.turbo/turbo-build.log +6 -6
  2. package/dist/client.cjs +33 -31
  3. package/dist/client.js +6522 -6167
  4. package/dist/src/access/client.d.ts +3 -1
  5. package/dist/src/access/client.d.ts.map +1 -1
  6. package/dist/src/access/enforce.d.ts +35 -0
  7. package/dist/src/access/enforce.d.ts.map +1 -0
  8. package/dist/src/access/enforce.spec.d.ts +2 -0
  9. package/dist/src/access/enforce.spec.d.ts.map +1 -0
  10. package/dist/src/access/external.d.ts +3 -0
  11. package/dist/src/access/external.d.ts.map +1 -1
  12. package/dist/src/access/payload.d.ts +0 -6
  13. package/dist/src/access/payload.d.ts.map +1 -1
  14. package/dist/src/access/policy/access.spec.d.ts +2 -0
  15. package/dist/src/access/policy/access.spec.d.ts.map +1 -0
  16. package/dist/src/access/policy/client.d.ts +485 -31
  17. package/dist/src/access/policy/client.d.ts.map +1 -1
  18. package/dist/src/access/policy/payload.d.ts +36 -113
  19. package/dist/src/access/policy/payload.d.ts.map +1 -1
  20. package/dist/src/access/role/client.d.ts +135 -0
  21. package/dist/src/access/role/client.d.ts.map +1 -0
  22. package/dist/src/access/role/external.d.ts.map +1 -0
  23. package/dist/src/access/role/index.d.ts +2 -0
  24. package/dist/src/access/role/index.d.ts.map +1 -0
  25. package/dist/src/access/role/payload.d.ts +27 -0
  26. package/dist/src/access/role/payload.d.ts.map +1 -0
  27. package/dist/src/access/role/role.spec.d.ts +2 -0
  28. package/dist/src/access/role/role.spec.d.ts.map +1 -0
  29. package/dist/src/arc/access.spec.d.ts +2 -0
  30. package/dist/src/arc/access.spec.d.ts.map +1 -0
  31. package/dist/src/arc/client.d.ts +5 -14
  32. package/dist/src/arc/client.d.ts.map +1 -1
  33. package/dist/src/arc/payload.d.ts +11 -2
  34. package/dist/src/arc/payload.d.ts.map +1 -1
  35. package/dist/src/auth/auth.d.ts +5 -3
  36. package/dist/src/auth/auth.d.ts.map +1 -1
  37. package/dist/src/channel/access.spec.d.ts +2 -0
  38. package/dist/src/channel/access.spec.d.ts.map +1 -0
  39. package/dist/src/channel/client.d.ts +0 -1
  40. package/dist/src/channel/client.d.ts.map +1 -1
  41. package/dist/src/channel/payload.d.ts +18 -8
  42. package/dist/src/channel/payload.d.ts.map +1 -1
  43. package/dist/src/channel/payload.spec.d.ts +2 -0
  44. package/dist/src/channel/payload.spec.d.ts.map +1 -0
  45. package/dist/src/channel/retriever.d.ts +4 -6
  46. package/dist/src/channel/retriever.d.ts.map +1 -1
  47. package/dist/src/channel/writer.d.ts.map +1 -1
  48. package/dist/src/client.d.ts +9 -5
  49. package/dist/src/client.d.ts.map +1 -1
  50. package/dist/src/device/access.spec.d.ts +2 -0
  51. package/dist/src/device/access.spec.d.ts.map +1 -0
  52. package/dist/src/{hardware/device → device}/client.d.ts +14 -7
  53. package/dist/src/device/client.d.ts.map +1 -0
  54. package/dist/src/device/device.spec.d.ts.map +1 -0
  55. package/dist/src/device/external.d.ts.map +1 -0
  56. package/dist/src/device/index.d.ts.map +1 -0
  57. package/dist/src/{hardware/device → device}/payload.d.ts +1 -1
  58. package/dist/src/device/payload.d.ts.map +1 -0
  59. package/dist/src/errors.d.ts +3 -0
  60. package/dist/src/errors.d.ts.map +1 -1
  61. package/dist/src/framer/client.d.ts +11 -1
  62. package/dist/src/framer/client.d.ts.map +1 -1
  63. package/dist/src/framer/frame.d.ts +10 -5
  64. package/dist/src/framer/frame.d.ts.map +1 -1
  65. package/dist/src/framer/iterator.d.ts +3 -3
  66. package/dist/src/framer/reader.d.ts +16 -0
  67. package/dist/src/framer/reader.d.ts.map +1 -0
  68. package/dist/src/framer/reader.spec.d.ts +2 -0
  69. package/dist/src/framer/reader.spec.d.ts.map +1 -0
  70. package/dist/src/framer/streamer.d.ts +24 -21
  71. package/dist/src/framer/streamer.d.ts.map +1 -1
  72. package/dist/src/framer/writer.d.ts +13 -13
  73. package/dist/src/index.d.ts +4 -5
  74. package/dist/src/index.d.ts.map +1 -1
  75. package/dist/src/label/access.spec.d.ts +2 -0
  76. package/dist/src/label/access.spec.d.ts.map +1 -0
  77. package/dist/src/label/client.d.ts +20 -11
  78. package/dist/src/label/client.d.ts.map +1 -1
  79. package/dist/src/ontology/client.d.ts +6 -6
  80. package/dist/src/ontology/client.d.ts.map +1 -1
  81. package/dist/src/ontology/group/access.spec.d.ts +2 -0
  82. package/dist/src/ontology/group/access.spec.d.ts.map +1 -0
  83. package/dist/src/ontology/group/client.d.ts +2 -2
  84. package/dist/src/ontology/group/client.d.ts.map +1 -1
  85. package/dist/src/ontology/group/payload.d.ts +1 -2
  86. package/dist/src/ontology/group/payload.d.ts.map +1 -1
  87. package/dist/src/ontology/payload.d.ts +23 -17
  88. package/dist/src/ontology/payload.d.ts.map +1 -1
  89. package/dist/src/ontology/writer.d.ts +10 -10
  90. package/dist/src/ontology/writer.d.ts.map +1 -1
  91. package/dist/src/rack/access.spec.d.ts +2 -0
  92. package/dist/src/rack/access.spec.d.ts.map +1 -0
  93. package/dist/src/{hardware/rack → rack}/client.d.ts +15 -8
  94. package/dist/src/rack/client.d.ts.map +1 -0
  95. package/dist/src/rack/external.d.ts.map +1 -0
  96. package/dist/src/rack/index.d.ts.map +1 -0
  97. package/dist/src/{hardware/rack → rack}/payload.d.ts +1 -1
  98. package/dist/src/rack/payload.d.ts.map +1 -0
  99. package/dist/src/rack/rack.spec.d.ts.map +1 -0
  100. package/dist/src/ranger/access.spec.d.ts +2 -0
  101. package/dist/src/ranger/access.spec.d.ts.map +1 -0
  102. package/dist/src/ranger/alias.d.ts +1 -8
  103. package/dist/src/ranger/alias.d.ts.map +1 -1
  104. package/dist/src/ranger/client.d.ts +12 -5
  105. package/dist/src/ranger/client.d.ts.map +1 -1
  106. package/dist/src/ranger/kv.d.ts +0 -3
  107. package/dist/src/ranger/kv.d.ts.map +1 -1
  108. package/dist/src/ranger/writer.d.ts +2 -2
  109. package/dist/src/ranger/writer.d.ts.map +1 -1
  110. package/dist/src/status/access.spec.d.ts +2 -0
  111. package/dist/src/status/access.spec.d.ts.map +1 -0
  112. package/dist/src/status/client.d.ts +4 -4
  113. package/dist/src/status/client.d.ts.map +1 -1
  114. package/dist/src/status/payload.d.ts +9 -2
  115. package/dist/src/status/payload.d.ts.map +1 -1
  116. package/dist/src/task/access.spec.d.ts +2 -0
  117. package/dist/src/task/access.spec.d.ts.map +1 -0
  118. package/dist/src/{hardware/task → task}/client.d.ts +26 -15
  119. package/dist/src/task/client.d.ts.map +1 -0
  120. package/dist/src/task/external.d.ts +3 -0
  121. package/dist/src/task/external.d.ts.map +1 -0
  122. package/dist/src/task/index.d.ts.map +1 -0
  123. package/dist/src/{hardware/task → task}/payload.d.ts +45 -6
  124. package/dist/src/task/payload.d.ts.map +1 -0
  125. package/dist/src/task/task.spec.d.ts.map +1 -0
  126. package/dist/src/testutil/access.d.ts +4 -0
  127. package/dist/src/testutil/access.d.ts.map +1 -0
  128. package/dist/src/transport.d.ts.map +1 -1
  129. package/dist/src/user/access.spec.d.ts +2 -0
  130. package/dist/src/user/access.spec.d.ts.map +1 -0
  131. package/dist/src/user/client.d.ts +10 -1
  132. package/dist/src/user/client.d.ts.map +1 -1
  133. package/dist/src/user/external.d.ts +1 -1
  134. package/dist/src/user/external.d.ts.map +1 -1
  135. package/dist/src/user/payload.d.ts.map +1 -1
  136. package/dist/src/workspace/access.spec.d.ts +2 -0
  137. package/dist/src/workspace/access.spec.d.ts.map +1 -0
  138. package/dist/src/workspace/client.d.ts +10 -5
  139. package/dist/src/workspace/client.d.ts.map +1 -1
  140. package/dist/src/workspace/lineplot/access.spec.d.ts +2 -0
  141. package/dist/src/workspace/lineplot/access.spec.d.ts.map +1 -0
  142. package/dist/src/workspace/lineplot/client.d.ts +8 -1
  143. package/dist/src/workspace/lineplot/client.d.ts.map +1 -1
  144. package/dist/src/workspace/log/access.spec.d.ts +2 -0
  145. package/dist/src/workspace/log/access.spec.d.ts.map +1 -0
  146. package/dist/src/workspace/log/client.d.ts +8 -1
  147. package/dist/src/workspace/log/client.d.ts.map +1 -1
  148. package/dist/src/workspace/schematic/access.spec.d.ts +2 -0
  149. package/dist/src/workspace/schematic/access.spec.d.ts.map +1 -0
  150. package/dist/src/workspace/schematic/client.d.ts +8 -1
  151. package/dist/src/workspace/schematic/client.d.ts.map +1 -1
  152. package/dist/src/workspace/schematic/symbol/access.spec.d.ts +2 -0
  153. package/dist/src/workspace/schematic/symbol/access.spec.d.ts.map +1 -0
  154. package/dist/src/workspace/schematic/symbol/client.d.ts +1 -5
  155. package/dist/src/workspace/schematic/symbol/client.d.ts.map +1 -1
  156. package/dist/src/workspace/schematic/symbol/payload.d.ts +2 -2
  157. package/dist/src/workspace/table/access.spec.d.ts +2 -0
  158. package/dist/src/workspace/table/access.spec.d.ts.map +1 -0
  159. package/dist/src/workspace/table/client.d.ts +8 -1
  160. package/dist/src/workspace/table/client.d.ts.map +1 -1
  161. package/package.json +3 -3
  162. package/src/access/client.ts +5 -2
  163. package/src/access/enforce.spec.ts +189 -0
  164. package/src/access/enforce.ts +84 -0
  165. package/src/access/external.ts +3 -0
  166. package/src/access/payload.ts +1 -13
  167. package/src/access/policy/access.spec.ts +147 -0
  168. package/src/access/policy/client.ts +21 -25
  169. package/src/access/policy/payload.ts +9 -5
  170. package/src/access/role/client.ts +135 -0
  171. package/src/access/role/external.ts +11 -0
  172. package/src/{hardware → access/role}/index.ts +1 -1
  173. package/src/access/role/payload.ts +32 -0
  174. package/src/access/role/role.spec.ts +95 -0
  175. package/src/arc/access.spec.ts +143 -0
  176. package/src/arc/client.ts +7 -31
  177. package/src/arc/payload.ts +4 -0
  178. package/src/auth/auth.ts +33 -11
  179. package/src/channel/access.spec.ts +116 -0
  180. package/src/channel/channel.spec.ts +63 -73
  181. package/src/channel/client.ts +2 -8
  182. package/src/channel/payload.spec.ts +171 -0
  183. package/src/channel/payload.ts +35 -7
  184. package/src/channel/retriever.ts +10 -11
  185. package/src/channel/writer.ts +3 -7
  186. package/src/client.ts +14 -18
  187. package/src/device/access.spec.ts +159 -0
  188. package/src/{hardware/device → device}/client.ts +12 -21
  189. package/src/{hardware/device → device}/device.spec.ts +70 -34
  190. package/src/device/external.ts +11 -0
  191. package/src/{hardware/rack → device}/index.ts +1 -1
  192. package/src/{hardware/device → device}/payload.ts +3 -3
  193. package/src/errors.ts +2 -0
  194. package/src/framer/adapter.spec.ts +14 -14
  195. package/src/framer/client.spec.ts +14 -20
  196. package/src/framer/client.ts +15 -20
  197. package/src/framer/deleter.spec.ts +1 -1
  198. package/src/framer/frame.spec.ts +131 -0
  199. package/src/framer/frame.ts +10 -2
  200. package/src/framer/iterator.ts +3 -3
  201. package/src/framer/reader.spec.ts +736 -0
  202. package/src/framer/reader.ts +265 -0
  203. package/src/framer/streamer.spec.ts +100 -12
  204. package/src/framer/streamer.ts +29 -9
  205. package/src/framer/writer.spec.ts +5 -5
  206. package/src/index.ts +4 -5
  207. package/src/label/access.spec.ts +109 -0
  208. package/src/label/client.ts +10 -14
  209. package/src/ontology/client.ts +4 -6
  210. package/src/ontology/group/access.spec.ts +77 -0
  211. package/src/ontology/group/client.ts +3 -7
  212. package/src/ontology/group/group.spec.ts +18 -0
  213. package/src/ontology/group/payload.ts +2 -2
  214. package/src/ontology/ontology.spec.ts +2 -0
  215. package/src/ontology/payload.ts +18 -2
  216. package/src/ontology/writer.ts +3 -7
  217. package/src/rack/access.spec.ts +102 -0
  218. package/src/{hardware/rack → rack}/client.ts +14 -19
  219. package/src/{hardware/device/index.ts → rack/external.ts} +2 -1
  220. package/src/{hardware/external.ts → rack/index.ts} +1 -1
  221. package/src/{hardware/rack → rack}/payload.ts +2 -2
  222. package/src/{hardware/rack → rack}/rack.spec.ts +43 -17
  223. package/src/ranger/access.spec.ts +115 -0
  224. package/src/ranger/alias.ts +6 -14
  225. package/src/ranger/client.ts +13 -14
  226. package/src/ranger/kv.ts +7 -9
  227. package/src/ranger/ranger.spec.ts +4 -4
  228. package/src/ranger/writer.ts +3 -7
  229. package/src/status/access.spec.ts +129 -0
  230. package/src/status/client.ts +5 -9
  231. package/src/status/payload.ts +3 -2
  232. package/src/task/access.spec.ts +131 -0
  233. package/src/{hardware/task → task}/client.ts +50 -25
  234. package/src/task/external.ts +11 -0
  235. package/src/{hardware/task → task}/index.ts +1 -1
  236. package/src/{hardware/task → task}/payload.ts +22 -3
  237. package/src/{hardware/task → task}/task.spec.ts +197 -34
  238. package/src/testutil/access.ts +34 -0
  239. package/src/testutil/channels.ts +3 -3
  240. package/src/transport.ts +1 -3
  241. package/src/user/access.spec.ts +107 -0
  242. package/src/user/client.ts +10 -12
  243. package/src/user/external.ts +12 -1
  244. package/src/user/payload.ts +3 -5
  245. package/src/workspace/access.spec.ts +108 -0
  246. package/src/workspace/client.ts +11 -27
  247. package/src/workspace/lineplot/access.spec.ts +134 -0
  248. package/src/workspace/lineplot/client.ts +8 -13
  249. package/src/workspace/log/access.spec.ts +134 -0
  250. package/src/workspace/log/client.ts +8 -13
  251. package/src/workspace/schematic/access.spec.ts +134 -0
  252. package/src/workspace/schematic/client.ts +9 -18
  253. package/src/workspace/schematic/symbol/access.spec.ts +172 -0
  254. package/src/workspace/schematic/symbol/client.ts +6 -17
  255. package/src/workspace/schematic/symbol/payload.ts +1 -1
  256. package/src/workspace/table/access.spec.ts +134 -0
  257. package/src/workspace/table/client.ts +8 -13
  258. package/dist/src/access/policy/policy.spec.d.ts +0 -2
  259. package/dist/src/access/policy/policy.spec.d.ts.map +0 -1
  260. package/dist/src/hardware/client.d.ts +0 -10
  261. package/dist/src/hardware/client.d.ts.map +0 -1
  262. package/dist/src/hardware/device/client.d.ts.map +0 -1
  263. package/dist/src/hardware/device/device.spec.d.ts.map +0 -1
  264. package/dist/src/hardware/device/external.d.ts.map +0 -1
  265. package/dist/src/hardware/device/index.d.ts.map +0 -1
  266. package/dist/src/hardware/device/payload.d.ts.map +0 -1
  267. package/dist/src/hardware/external.d.ts +0 -2
  268. package/dist/src/hardware/external.d.ts.map +0 -1
  269. package/dist/src/hardware/index.d.ts +0 -2
  270. package/dist/src/hardware/index.d.ts.map +0 -1
  271. package/dist/src/hardware/rack/client.d.ts.map +0 -1
  272. package/dist/src/hardware/rack/external.d.ts.map +0 -1
  273. package/dist/src/hardware/rack/index.d.ts.map +0 -1
  274. package/dist/src/hardware/rack/payload.d.ts.map +0 -1
  275. package/dist/src/hardware/rack/rack.spec.d.ts.map +0 -1
  276. package/dist/src/hardware/task/client.d.ts.map +0 -1
  277. package/dist/src/hardware/task/external.d.ts.map +0 -1
  278. package/dist/src/hardware/task/index.d.ts.map +0 -1
  279. package/dist/src/hardware/task/payload.d.ts.map +0 -1
  280. package/dist/src/hardware/task/task.spec.d.ts.map +0 -1
  281. package/dist/src/user/retriever.d.ts +0 -16
  282. package/dist/src/user/retriever.d.ts.map +0 -1
  283. package/dist/src/user/writer.d.ts +0 -11
  284. package/dist/src/user/writer.d.ts.map +0 -1
  285. package/src/access/policy/policy.spec.ts +0 -329
  286. package/src/hardware/client.ts +0 -24
  287. package/src/hardware/device/external.ts +0 -11
  288. package/src/hardware/rack/external.ts +0 -11
  289. package/src/hardware/task/external.ts +0 -11
  290. package/src/user/retriever.ts +0 -41
  291. package/src/user/writer.ts +0 -84
  292. /package/dist/src/{hardware/device → access/role}/external.d.ts +0 -0
  293. /package/dist/src/{hardware/device → device}/device.spec.d.ts +0 -0
  294. /package/dist/src/{hardware/rack → device}/external.d.ts +0 -0
  295. /package/dist/src/{hardware/device → device}/index.d.ts +0 -0
  296. /package/dist/src/{hardware/task → rack}/external.d.ts +0 -0
  297. /package/dist/src/{hardware/rack → rack}/index.d.ts +0 -0
  298. /package/dist/src/{hardware/rack → rack}/rack.spec.d.ts +0 -0
  299. /package/dist/src/{hardware/task → task}/index.d.ts +0 -0
  300. /package/dist/src/{hardware/task → task}/task.spec.d.ts +0 -0
package/dist/client.cjs CHANGED
@@ -1,63 +1,65 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("zod"),Bl=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)},ga=t=>{const e=(n,r=_r)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!mr(n))return n;r=Yl(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&&(mr(c)?ci(c)||(c=e(c,r)):r.recursiveInArray&&oi(c)&&(c=[...c].map(u=>{let h=u;return mr(u)?ci(h)||(h=e(u,r)):oi(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},wa=ga(Bl),ql=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),Fl=ga(ql),Vl=[Number,String,Uint8Array],_r={recursive:!0,recursiveInArray:!0},Yl=(t=_r)=>(t.recursive==null?t=_r:t.recursiveInArray??=!1,t),oi=t=>t!=null&&Array.isArray(t),mr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),ci=t=>Vl.some(e=>t instanceof e);let Hl=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=wa(r);return n!=null?n.parse(s):s}encodeString(e){const n=Fl(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}};const jr=new Hl,he=t=>t!=null&&typeof t=="object"&&"value"in t;let It=class{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const Wl=t=>t!=null&&typeof t=="object"&&"toString"in t,Gl=(t,e=!1)=>{const n=Wl(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?Kl(r):r},Kl=t=>(e,n)=>t(n,e),qn=i.z.tuple([i.z.number(),i.z.number()]);i.z.tuple([i.z.bigint(),i.z.bigint()]);const ba=i.z.object({width:i.z.number(),height:i.z.number()}),Jl=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),Xl=["width","height"];i.z.enum(Xl);const Ql=["start","center","end"],eh=["signedWidth","signedHeight"];i.z.enum(eh);const Cn=i.z.object({x:i.z.number(),y:i.z.number()}),th=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),nh=["x","y"],va=i.z.enum(nh),Ta=["top","right","bottom","left"];i.z.enum(Ta);const rh=["left","right"],za=i.z.enum(rh),sh=["top","bottom"],Ea=i.z.enum(sh),Na=["center"],ui=i.z.enum(Na),ih=[...Ta,...Na],Oa=i.z.enum(ih);i.z.enum(Ql);const ah=["first","last"];i.z.enum(ah);const oh=i.z.object({lower:i.z.number(),upper:i.z.number()}),ch=i.z.object({lower:i.z.bigint(),upper:i.z.bigint()});i.z.union([oh,qn]);i.z.union([ch,qn]);i.z.enum([...va.options,...Oa.options]);i.z.enum(["x","left","right"]);i.z.enum(["y","top","bottom"]);i.z.union([va,Oa,i.z.instanceof(String)]);const Fn=t=>(e,n)=>{if(typeof e=="bigint"){if(uh(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))},Vn=Fn((t,e)=>t-e),Yn=Fn((t,e)=>t+e),uh=t=>typeof t=="bigint"?!0:Number.isInteger(t),Se=Fn((t,e)=>t*e),Hn=Fn((t,e)=>t/e),et=(t,e,n)=>{const r={};if(typeof e=="object"&&(n=e,e=void 0),n={makeValid:!0,...n},typeof t=="number"||typeof t=="bigint")e!=null?(r.lower=t,r.upper=e):(r.lower=typeof t=="bigint"?0n:0,r.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[r.lower,r.upper]=t}else r.lower=t.lower,r.upper=t.upper;return n?.makeValid?lh(r):r},lh=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,li=(t,e)=>{const n=et(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e};i.z.object({x:za.or(ui),y:Ea.or(ui)});const hh=i.z.object({x:za,y:Ea}),fh=Object.freeze({x:"left",y:"top"}),dh=(t,e)=>t.x===e.x&&t.y===e.y,hi=i.z.union([i.z.number(),Cn,qn,ba,Jl,th]),ph=(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}},fi=Object.freeze({x:0,y:0}),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:Cn,two:Cn,root:hh});const ys=(t,e,n=0,r=0,s)=>{const a={one:{...fi},two:{...fi},root:s??fh};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))},gr=t=>{const e=ys(t);return{lower:e.one.x,upper:e.two.x}},wr=t=>{const e=ys(t);return{lower:e.one.y,upper:e.two.y}},yh=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,mh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([ba,mh,Cn,qn]);const gh=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:hi,scale:hi});i.z.object({offset:i.z.number(),scale:i.z.number()});const wh=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],bh=t=>(e,n,r,s)=>[e,s?r/t:r*t],vh=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]},Th=t=>(e,n,r)=>[t,r],zh=()=>(t,e,n)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,n];const{lower:r,upper:s}=t;return[t,s-(n-r)]},Eh=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=gh(r,s,a),[e,r]};let di=class dt{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new dt().translate(e)}static magnify(e){return new dt().magnify(e)}static scale(e,n){return new dt().scale(e,n)}translate(e){const n=this.new(),r=wh(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=bh(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=et(e,n),s=this.new(),a=vh(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=et(e,n),s=this.new(),a=Eh(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=et(e,n),s=this.new(),a=Th(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=zh();e.type="invert";const n=this.new();return n.ops.push(e),n}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new dt;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 dt};(class Ee{x;y;currRoot;constructor(e=new di,n=new di,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=ph(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(yh(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!dh(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(gr(e)),n.y=n.y.scale(wr(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(gr(e)),n.y=this.y.reBound(wr(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(gr(e)),n.y=this.y.clamp(wr(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 ys(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});let $a=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const Sa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Nh=`0123456789${Sa}`,Oh=11,$h=$a(Sa,1),Sh=$a(Nh,Oh-1),Ih=()=>`${$h()}${Sh()}`,Ah=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,kh=i.z.enum(["static","dynamic"]),Mr=2n**63n-1n,xh=2**63-1,pi=365,vn=30,Zh=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)])]),Ia=(t,e)=>{const n=new _(e);if(![C.DAY,C.HOUR,C.MINUTE,C.SECOND,C.MILLISECOND,C.MICROSECOND,C.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 _?new _(r):new C(r)};let _=class z extends It{constructor(e,n="UTC"){if(e==null)super(z.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*z.MILLISECOND.valueOf());else if(typeof e=="string")super(z.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(z.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=z.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===xh?e=Mr:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=z.MAX:e=z.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 z(BigInt(s.getTime())*z.MILLISECOND.valueOf()).truncate(z.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=z.hours(parseInt(r??"00")).add(z.minutes(parseInt(s??"00"))).add(z.seconds(parseInt(o??"00"))).add(z.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(z.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return z.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())*z.MILLISECOND.valueOf(),l=BigInt(a)*z.MILLISECOND.valueOf();return c+l}const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new z(BigInt(r.getTime())*z.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(z.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 C(BigInt(new Date().getTimezoneOffset())*z.MINUTE.valueOf())}static since(e){return new z().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new z(e).valueOf()}span(e){return this.range(e).span}range(e){return new 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 z(e).valueOf()}afterEq(e){return this.valueOf()>=new z(e).valueOf()}before(e){return this.valueOf()<new z(e).valueOf()}beforeEq(e){return this.valueOf()<=new z(e).valueOf()}add(e){return new z(Yn(this.valueOf(),new C(e).valueOf()))}sub(e){return new z(Vn(this.valueOf(),new C(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(C.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(C.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(C.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(C.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 year(){return this.date().getUTCFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new z(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new z(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new z(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new z(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new z(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new z(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new z(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new z(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 Ia(this,e)}get isToday(){return this.truncate(C.DAY).equals(z.now().truncate(C.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(C.days(30))?"shortDate":e.greaterThanOrEqual(C.DAY)?"dateTime":e.greaterThanOrEqual(C.HOUR)?"time":e.greaterThanOrEqual(C.SECOND)?"preciseTime":"ISOTime"}static now(){return new z(new Date)}static max(...e){let n=z.MIN;for(const r of e){const s=new z(r);s.after(n)&&(n=s)}return n}static min(...e){let n=z.MAX;for(const r of e){const s=new z(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new z(e,n)}static NANOSECOND=z.nanoseconds(1);static microseconds(e,n="UTC"){return z.nanoseconds(e*1e3,n)}static MICROSECOND=z.microseconds(1);static milliseconds(e,n="UTC"){return z.microseconds(e*1e3,n)}static MILLISECOND=z.milliseconds(1);static seconds(e,n="UTC"){return z.milliseconds(e*1e3,n)}static SECOND=z.seconds(1);static minutes(e,n="UTC"){return z.seconds(e*60,n)}static MINUTE=z.minutes(1);static hours(e,n="UTC"){return z.minutes(e*60,n)}static HOUR=z.hours(1);static days(e,n="UTC"){return z.hours(e*24,n)}static DAY=z.days(1);static MAX=new z(Mr);static MIN=new z(0);static ZERO=new z(0);static z=i.z.union([i.z.instanceof(z),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.date().transform(e=>new z(e)),i.z.custom(e=>e instanceof C).transform(e=>new z(e)),Zh.transform(e=>new z(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}},C=class N extends It{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 N?e:e instanceof br?e.period:e instanceof _?new N(e):(he(e)&&(e=e.value),["number","bigint"].includes(typeof e)?N.seconds(e):new N(e))}static fromMilliseconds(e){return e instanceof N?e:e instanceof br?e.period:e instanceof _?new N(e):(he(e)&&(e=e.value),["number","bigint"].includes(typeof e)?N.milliseconds(e):new N(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new N(e).valueOf()}greaterThan(e){return this.valueOf()>new N(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new N(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new N(e).valueOf()}remainder(e){return Ia(this,e)}truncate(e){return new N(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(N.DAY),r=this.truncate(N.HOUR),s=this.truncate(N.MINUTE),a=this.truncate(N.SECOND),o=this.truncate(N.MILLISECOND),c=this.truncate(N.MICROSECOND),l=this.truncate(N.NANOSECOND),u=n,h=r.sub(n),d=s.sub(r),f=a.sub(s),v=o.sub(a),$=c.sub(o),k=l.sub(c);let b="";return u.isZero||(b+=`${u.days}d `),h.isZero||(b+=`${h.hours}h `),d.isZero||(b+=`${d.minutes}m `),f.isZero||(b+=`${f.seconds}s `),v.isZero||(b+=`${v.milliseconds}ms `),$.isZero||(b+=`${$.microseconds}µs `),k.isZero||(b+=`${k.nanoseconds}ns`),b.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new N(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(N.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/pi),u=Math.floor(s/vn),h=Math.floor(s/7),d=Math.floor(s),f=Math.floor(a),v=Math.floor(o),$=Math.floor(c),k=r?"-":"";if(l>=1){let b=`${l}y`;if(l<2){const E=Math.floor(s%pi/vn);E>0&&(b+=` ${E}mo`)}return k+b}if(h>=1&&s<vn&&s%7===0){let b=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?b+=` ${E}d`:A>0&&A<24&&(b+=` ${A}h`)),k+b}if(u>=1){let b=`${u}mo`;if(u<3){const E=Math.floor(s%vn);E>0&&(b+=` ${E}d`)}return k+b}if(h>=1){let b=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?b+=` ${E}d`:A>0&&A<24&&(b+=` ${A}h`)),k+b}if(d>=1){let b=`${d}d`;const E=Math.floor(a-d*24);return d<2&&E>0&&(b+=` ${E}h`),k+b}if(f>=1){let b=`${f}h`;if(f<3){const E=Math.floor(o-f*60);E>0&&(b+=` ${E}m`)}return k+b}if(v>=1){let b=`${v}m`;if(v<5){const E=Math.floor(c-v*60);E>0&&(b+=` ${E}s`)}return k+b}return`${k}${$}s`}mult(e){return new N(Se(this.valueOf(),e))}div(e){return new N(Hn(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(N.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(N.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(N.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(N.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(N.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(N.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new N(e).valueOf()}add(e){return new N(this.valueOf()+new N(e).valueOf())}sub(e){return new N(this.valueOf()-new N(e).valueOf())}static nanoseconds(e=1){return new N(e)}static NANOSECOND=N.nanoseconds(1);static microseconds(e=1){return N.nanoseconds(Se(e,1e3))}static MICROSECOND=N.microseconds(1);static milliseconds(e=1){return N.microseconds(Se(e,1e3))}static MILLISECOND=N.milliseconds(1);static seconds(e=1){return N.milliseconds(Se(e,1e3))}static SECOND=N.seconds(1);static minutes(e=1){return N.seconds(Se(e,60))}static MINUTE=N.minutes(1);static hours(e){return N.minutes(Se(e,60))}static HOUR=N.hours(1);static days(e){return N.hours(Se(e,24))}static DAY=N.days(1);static MAX=new N(Mr);static MIN=new N(0);static ZERO=new N(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new N(e.value)),i.z.string().transform(e=>new N(BigInt(e))),i.z.number().transform(e=>new N(e)),i.z.bigint().transform(e=>new N(e)),i.z.instanceof(N),i.z.instanceof(_).transform(e=>new N(e)),i.z.custom(e=>e instanceof br).transform(e=>new N(e))])},br=class le extends It{constructor(e){he(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new le(e).valueOf()}get period(){return C.seconds(1/this.valueOf())}sampleCount(e){return new C(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new re(n).valueOf()}span(e){return C.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new re(n).valueOf())}add(e){return new le(Yn(this.valueOf(),new le(e).valueOf()))}sub(e){return new le(Vn(this.valueOf(),new le(e).valueOf()))}mult(e){return new le(Se(this.valueOf(),e))}div(e){return new le(Hn(this.valueOf(),e))}static hz(e){return new le(e)}static khz(e){return le.hz(e*1e3)}static z=i.z.union([i.z.number().transform(e=>new le(e)),i.z.instanceof(le)])},re=class ie extends It{constructor(e){he(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new Dr(e*this.valueOf())}add(e){return new ie(Yn(this.valueOf(),new ie(e).valueOf()))}sub(e){return new ie(Vn(this.valueOf(),new ie(e).valueOf()))}mult(e){return new ie(Se(this.valueOf(),e))}div(e){return new ie(Hn(this.valueOf(),e))}static UNKNOWN=new ie(0);static BIT128=new ie(16);static BIT64=new ie(8);static BIT32=new ie(4);static BIT16=new ie(2);static BIT8=new ie(1);static z=i.z.union([i.z.number().transform(e=>new ie(e)),i.z.instanceof(ie)])},Mt=class Ne{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new _(e.start),this.end=new _(e.end)):(this.start=new _(e),this.end=new _(n))}get span(){return new C(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 Ne(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=C.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=C.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=_.max(r.start,e.start),a=_.min(r.end,e.end);return a.before(s)?!1:new C(a.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof Ne?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new Ne(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 Ne(_.min(...e.map(n=>n.start)),_.max(...e.map(n=>n.end)))}static MAX=new Ne(_.MIN,_.MAX);static ZERO=new Ne(_.ZERO,_.ZERO);static z=i.z.union([i.z.object({start:_.z,end:_.z}).transform(e=>new Ne(e.start,e.end)),i.z.instanceof(Ne)]);static sort(e,n){return _.sort(e.start,n.start)||_.sort(e.end,n.end)}static simplify(e){return e.map(n=>n.makeValid()).sort((n,r)=>Ne.sort(n,r)).reduce((n,r)=>{if(r.span.isZero)return n;if(n.length===0)return n.push(r),n;const s=n[n.length-1];return s.overlapsWith(r)||s.end.equals(r.start)?s.end=_.max(s.end,r.end):n.push(r),n},[])}},B=class m extends It{constructor(e){if(he(e)&&(e=e.value),e instanceof m||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=m.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=m.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?m.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(m.JSON)||this.equals(m.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(m.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=m.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(m.UINT8)||this.equals(m.UINT16)||this.equals(m.UINT32)||this.equals(m.UINT64)}get isSignedInteger(){return this.equals(m.INT8)||this.equals(m.INT16)||this.equals(m.INT32)||this.equals(m.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(m.INT32)&&e.equals(m.FLOAT64)||this.equals(m.INT8)&&e.equals(m.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 m.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new m("unknown");static FLOAT64=new m("float64");static FLOAT32=new m("float32");static INT64=new m("int64");static INT32=new m("int32");static INT16=new m("int16");static INT8=new m("int8");static UINT64=new m("uint64");static UINT32=new m("uint32");static UINT16=new m("uint16");static UINT8=new m("uint8");static BOOLEAN=new m("boolean");static TIMESTAMP=new m("timestamp");static UUID=new m("uuid");static STRING=new m("string");static JSON=new m("json");static ARRAY_CONSTRUCTORS=new Map([[m.UINT8.toString(),Uint8Array],[m.UINT16.toString(),Uint16Array],[m.UINT32.toString(),Uint32Array],[m.UINT64.toString(),BigUint64Array],[m.FLOAT32.toString(),Float32Array],[m.FLOAT64.toString(),Float64Array],[m.INT8.toString(),Int8Array],[m.INT16.toString(),Int16Array],[m.INT32.toString(),Int32Array],[m.INT64.toString(),BigInt64Array],[m.TIMESTAMP.toString(),BigInt64Array],[m.STRING.toString(),Uint8Array],[m.JSON.toString(),Uint8Array],[m.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,m.UINT8],[Uint16Array.name,m.UINT16],[Uint32Array.name,m.UINT32],[BigUint64Array.name,m.UINT64],[Float32Array.name,m.FLOAT32],[Float64Array.name,m.FLOAT64],[Int8Array.name,m.INT8],[Int16Array.name,m.INT16],[Int32Array.name,m.INT32],[BigInt64Array.name,m.INT64]]);static DENSITIES=new Map([[m.UINT8.toString(),re.BIT8],[m.UINT16.toString(),re.BIT16],[m.UINT32.toString(),re.BIT32],[m.UINT64.toString(),re.BIT64],[m.FLOAT32.toString(),re.BIT32],[m.FLOAT64.toString(),re.BIT64],[m.INT8.toString(),re.BIT8],[m.INT16.toString(),re.BIT16],[m.INT32.toString(),re.BIT32],[m.INT64.toString(),re.BIT64],[m.TIMESTAMP.toString(),re.BIT64],[m.STRING.toString(),re.UNKNOWN],[m.JSON.toString(),re.UNKNOWN],[m.UUID.toString(),re.BIT128]]);static ALL=[m.UNKNOWN,m.FLOAT64,m.FLOAT32,m.INT64,m.INT32,m.INT16,m.INT8,m.UINT64,m.UINT32,m.UINT16,m.UINT8,m.TIMESTAMP,m.UUID,m.STRING,m.JSON];static SHORT_STRINGS=new Map([[m.UINT8.toString(),"u8"],[m.UINT16.toString(),"u16"],[m.UINT32.toString(),"u32"],[m.UINT64.toString(),"u64"],[m.INT8.toString(),"i8"],[m.INT16.toString(),"i16"],[m.INT32.toString(),"i32"],[m.INT64.toString(),"i64"],[m.FLOAT32.toString(),"f32"],[m.FLOAT64.toString(),"f64"],[m.BOOLEAN.toString(),"bool"],[m.TIMESTAMP.toString(),"ts"],[m.UUID.toString(),"uuid"],[m.STRING.toString(),"str"],[m.JSON.toString(),"json"]]);static BIG_INT_TYPES=[m.INT64,m.UINT64,m.TIMESTAMP];static z=i.z.union([i.z.string().transform(e=>new m(e)),i.z.instanceof(m)])},Dr=class x extends It{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 x(Yn(this.valueOf(),e.valueOf()))}sub(e){return he(e)&&(e=e.value),new x(Vn(this.valueOf(),e.valueOf()))}mult(e){return new x(Se(this.valueOf(),e))}div(e){return new x(Hn(this.valueOf(),e))}truncate(e){return new x(Math.trunc(this.valueOf()/new x(e).valueOf())*new x(e).valueOf())}remainder(e){return x.bytes(this.valueOf()%new x(e).valueOf())}get gigabytes(){return this.valueOf()/x.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/x.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/x.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/x.TERABYTE.valueOf()}toString(){const e=this.truncate(x.TERABYTE),n=this.truncate(x.GIGABYTE),r=this.truncate(x.MEGABYTE),s=this.truncate(x.KILOBYTE),a=this.truncate(x.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 x(e)}static BYTE=new x(1);static kilobytes(e=1){return x.bytes(new x(e).valueOf()*1e3)}static KILOBYTE=x.kilobytes(1);static megabytes(e=1){return x.kilobytes(new x(e).valueOf()*1e3)}static MEGABYTE=x.megabytes(1);static gigabytes(e=1){return x.megabytes(new x(e).valueOf()*1e3)}static GIGABYTE=x.gigabytes(1);static terabytes(e){return x.gigabytes(new x(e).valueOf()*1e3)}static TERABYTE=x.terabytes(1);static ZERO=new x(0);static z=i.z.union([i.z.number().transform(e=>new x(e)),i.z.instanceof(x)]);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 Aa=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof _||t instanceof C||t instanceof Date},Ch=(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),An=(t,e)=>e==0?t:t==0?e:typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:Number(t)+Number(e),Rh=/^(?:[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 _h(t){return typeof t=="string"&&Rh.test(t)}const J=[];for(let t=0;t<256;++t)J.push((t+256).toString(16).slice(1));function jh(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 Mh(t,e=0){const n=jh(t,e);if(!_h(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const ka=(t,e)=>Mh(t,e),Me=-1,Dh=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Ph=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Pr=10,Uh=(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`)},xa="sy_x_telem_series";let Za=class Le{key;discriminator=xa;dataType;sampleOffset;gl;_data;timeRange=Mt.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Me;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=i.z.object({timeRange:Mt.z.optional(),dataType:B.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Dh,Ph,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:kh.optional().default("static").optional()});static z=Le.crudeZ.transform(e=>new Le(e));constructor(e){Lh(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=Ih(),data:u}=e;if(Bh(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=Aa(u),d=Array.isArray(u);if(n!=null)this.dataType=new B(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=B.STRING;else if(typeof f=="number")this.dataType=B.FLOAT64;else if(typeof f=="bigint")this.dataType=B.INT64;else if(typeof f=="boolean")this.dataType=B.BOOLEAN;else if(f instanceof _||f instanceof Date||f instanceof _)this.dataType=B.TIMESTAMP;else if(typeof f=="object")this.dataType=B.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new B(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 v=f[0];(v instanceof _||v instanceof Date||v instanceof C)&&(f=f.map($=>new _($).valueOf())),this.dataType.equals(B.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"),eh=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)},ba=t=>{const e=(n,r=Er)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!sr(n))return n;r=sh(r);const s={},a=n;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),r):(Object.keys(a).forEach(o=>{let c=a[o];const l=t(o);r.recursive&&(sr(c)?pi(c)||(c=e(c,r)):r.recursiveInArray&&di(c)&&(c=[...c].map(u=>{let h=u;return sr(u)?pi(h)||(h=e(u,r)):di(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},va=ba(eh),th=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),nh=ba(th),rh=[Number,String,Uint8Array],Er={recursive:!0,recursiveInArray:!0},sh=(t=Er)=>(t.recursive==null?t=Er:t.recursiveInArray??=!1,t),di=t=>t!=null&&Array.isArray(t),sr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),pi=t=>rh.some(e=>t instanceof e);let ih=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=va(r);return n!=null?n.parse(s):s}encodeString(e){const n=nh(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}};const Nr=new ih,ce=t=>t!=null&&typeof t=="object"&&"value"in t;class At{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const ah=t=>t!=null&&typeof t=="object"&&"toString"in t,oh=(t,e=!1)=>{const n=ah(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?ch(r):r},ch=t=>(e,n)=>t(n,e);let za=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const Ta="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",uh=`0123456789${Ta}`,lh=11,hh=za(Ta,1),fh=za(uh,lh-1),dh=()=>`${hh()}${fh()}`,ph=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,yh=2**12-1,Sr=2n**63n-1n,mh=2**63-1,Mn=t=>(e,n)=>{if(typeof e=="bigint"){if(gh(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))},Kt=Mn((t,e)=>t-e),et=Mn((t,e)=>t+e),gh=t=>typeof t=="bigint"?!0:Number.isInteger(t),Te=Mn((t,e)=>t*e),jn=Mn((t,e)=>t/e),Oa=i.z.tuple([i.z.number(),i.z.number()]),Ea=i.z.object({width:i.z.number(),height:i.z.number()}),wh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),bh=["start","center","end"],Pt=i.z.object({x:i.z.number(),y:i.z.number()}),vh=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),zh=["x","y"],Na=i.z.enum(zh),Sa=["top","right","bottom","left"];i.z.enum(Sa);const Th=["left","right"],ka=i.z.enum(Th),Oh=["top","bottom"],Aa=i.z.enum(Oh),$a=["center"],yi=i.z.enum($a),Eh=[...Sa,...$a],Ia=i.z.enum(Eh);i.z.enum(bh);const Nh=["first","last"];i.z.enum(Nh);i.z.object({lower:i.z.number(),upper:i.z.number()});i.z.enum([...Na.options,...Ia.options]);i.z.union([Na,Ia,i.z.instanceof(String)]);const tt=(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?Sh(r):r},Sh=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,mi=(t,e)=>{const n=tt(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e};i.z.object({x:ka.or(yi),y:Aa.or(yi)});const Za=i.z.object({x:ka,y:Aa}),kh=Object.freeze({x:"left",y:"top"}),Ah=(t,e)=>t.x===e.x&&t.y===e.y,gi=i.z.union([i.z.number(),Pt,Oa,Ea,wh,vh]),$h=(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}},wi=Object.freeze({x:0,y:0}),yn=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:yn,left:yn,width:yn,height:yn});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:Pt,two:Pt,root:Za});const is=(t,e,n=0,r=0,s)=>{const a={one:{...wi},two:{...wi},root:s??kh};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:t,y:e},a.two={x:a.one.x+n,y:a.one.y+r},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(a.one={x:t.left,y:t.top},a.two={x:t.right,y:t.bottom},a):(a.one=t,e==null?a.two={x:a.one.x+n,y:a.one.y+r}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+n}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},ir=t=>{const e=is(t);return{lower:e.one.x,upper:e.two.x}},ar=t=>{const e=is(t);return{lower:e.one.y,upper:e.two.y}},Ih=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,Zh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([Ea,Zh,Pt,Oa]);const xh=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:gi,scale:gi});i.z.object({offset:i.z.number(),scale:i.z.number()});const Ch=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],Rh=t=>(e,n,r,s)=>[e,s?r/t:r*t],_h=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:a}=e,{lower:o,upper:c}=t,l=a-s,u=c-o;if(n==="dimension")return[t,r*(u/l)];const h=(r-s)*(u/l)+o;return[t,h]},Mh=t=>(e,n,r)=>[t,r],jh=()=>(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)]},Uh=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=xh(r,s,a),[e,r]};class Be{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Be().translate(e)}static magnify(e){return new Be().magnify(e)}static scale(e,n){return new Be().scale(e,n)}translate(e){const n=this.new(),r=Ch(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=Rh(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=tt(e,n),s=this.new(),a=_h(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=tt(e,n),s=this.new(),a=Uh(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=tt(e,n),s=this.new(),a=Mh(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=jh();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 Be;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 Be}class be{x;y;currRoot;constructor(e=new Be,n=new Be,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new be().translate(e,n)}static translateX(e){return new be().translateX(e)}static translateY(e){return new be().translateY(e)}static clamp(e){return new be().clamp(e)}static magnify(e){return new be().magnify(e)}static scale(e){return new be().scale(e)}static reBound(e){return new be().reBound(e)}translate(e,n){const r=$h(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(Ih(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!Ah(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(ir(e)),n.y=n.y.scale(ar(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(ir(e)),n.y=this.y.reBound(ar(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(ir(e)),n.y=this.y.clamp(ar(e)),n}copy(){const e=new be;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 is(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 be}const Dh=Pt.extend({root:Za,units:i.object({x:i.enum(["px","decimal"]),y:i.enum(["px","decimal"])})});Dh.partial({root:!0,units:!0});const Ph=i.z.enum(["static","dynamic"]),bi=365,mn=30,Lh=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)])]),xa=(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 At{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===mh?e=Sr:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=b.MAX:e=b.MIN)),ce(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 Rt(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(et(this.valueOf(),new v(e).valueOf()))}sub(e){return new b(Kt(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 xa(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(Sr);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)),Lh.transform(e=>new b(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}}class v extends At{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),ce(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof v?e:e instanceof or?e.period:e instanceof b?new v(e):(ce(e)&&(e=e.value),["number","bigint"].includes(typeof e)?v.seconds(e):new v(e))}static fromMilliseconds(e){return e instanceof v?e:e instanceof or?e.period:e instanceof b?new v(e):(ce(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 xa(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 z="";return u.isZero||(z+=`${u.days}d `),h.isZero||(z+=`${h.hours}h `),d.isZero||(z+=`${d.minutes}m `),f.isZero||(z+=`${f.seconds}s `),O.isZero||(z+=`${O.milliseconds}ms `),S.isZero||(z+=`${S.microseconds}µs `),Z.isZero||(z+=`${Z.nanoseconds}ns`),z.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new v(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(v.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/bi),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 z=`${l}y`;if(l<2){const E=Math.floor(s%bi/mn);E>0&&(z+=` ${E}mo`)}return Z+z}if(h>=1&&s<mn&&s%7===0){let z=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?z+=` ${E}d`:A>0&&A<24&&(z+=` ${A}h`)),Z+z}if(u>=1){let z=`${u}mo`;if(u<3){const E=Math.floor(s%mn);E>0&&(z+=` ${E}d`)}return Z+z}if(h>=1){let z=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?z+=` ${E}d`:A>0&&A<24&&(z+=` ${A}h`)),Z+z}if(d>=1){let z=`${d}d`;const E=Math.floor(a-d*24);return d<2&&E>0&&(z+=` ${E}h`),Z+z}if(f>=1){let z=`${f}h`;if(f<3){const E=Math.floor(o-f*60);E>0&&(z+=` ${E}m`)}return Z+z}if(O>=1){let z=`${O}m`;if(O<5){const E=Math.floor(c-O*60);E>0&&(z+=` ${E}s`)}return Z+z}return`${Z}${S}s`}mult(e){return new v(Te(this.valueOf(),e))}div(e){return new v(jn(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(Te(e,1e3))}static MICROSECOND=v.microseconds(1);static milliseconds(e=1){return v.microseconds(Te(e,1e3))}static MILLISECOND=v.milliseconds(1);static seconds(e=1){return v.milliseconds(Te(e,1e3))}static SECOND=v.seconds(1);static minutes(e=1){return v.seconds(Te(e,60))}static MINUTE=v.minutes(1);static hours(e){return v.minutes(Te(e,60))}static HOUR=v.hours(1);static days(e){return v.hours(Te(e,24))}static DAY=v.days(1);static MAX=new v(Sr);static MIN=new v(0);static ZERO=new v(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new v(e.value)),i.z.string().transform(e=>new v(BigInt(e))),i.z.number().transform(e=>new v(e)),i.z.bigint().transform(e=>new v(e)),i.z.instanceof(v),i.z.instanceof(b).transform(e=>new v(e)),i.z.custom(e=>e instanceof or).transform(e=>new v(e))])}let or=class oe extends At{constructor(e){ce(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new oe(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 _(n).valueOf()}span(e){return v.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new _(n).valueOf())}add(e){return new oe(et(this.valueOf(),new oe(e).valueOf()))}sub(e){return new oe(Kt(this.valueOf(),new oe(e).valueOf()))}mult(e){return new oe(Te(this.valueOf(),e))}div(e){return new oe(jn(this.valueOf(),e))}static hz(e){return new oe(e)}static khz(e){return oe.hz(e*1e3)}static z=i.z.union([i.z.number().transform(e=>new oe(e)),i.z.instanceof(oe)])};class _ extends At{constructor(e){ce(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 _(et(this.valueOf(),new _(e).valueOf()))}sub(e){return new _(Kt(this.valueOf(),new _(e).valueOf()))}mult(e){return new _(Te(this.valueOf(),e))}div(e){return new _(jn(this.valueOf(),e))}static UNKNOWN=new _(0);static BIT128=new _(16);static BIT64=new _(8);static BIT32=new _(4);static BIT16=new _(2);static BIT8=new _(1);static z=i.z.union([i.z.number().transform(e=>new _(e)),i.z.instanceof(_)])}let Rt=class ve{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 ve(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 ve?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new ve(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 ve(b.min(...e.map(n=>n.start)),b.max(...e.map(n=>n.end)))}static MAX=new ve(b.MIN,b.MAX);static ZERO=new ve(b.ZERO,b.ZERO);static z=i.z.union([i.z.object({start:b.z,end:b.z}).transform(e=>new ve(e.start,e.end)),i.z.instanceof(ve)]);static sort(e,n){return b.sort(e.start,n.start)||b.sort(e.end,n.end)}static simplify(e){return e.map(n=>n.makeValid()).sort((n,r)=>ve.sort(n,r)).reduce((n,r)=>{if(r.span.isZero)return n;if(n.length===0)return n.push(r),n;const s=n[n.length-1];return s.overlapsWith(r)||s.end.equals(r.start)?s.end=b.max(s.end,r.end):n.push(r),n},[])}};class y extends At{constructor(e){if(ce(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(),_.BIT8],[y.UINT16.toString(),_.BIT16],[y.UINT32.toString(),_.BIT32],[y.UINT64.toString(),_.BIT64],[y.FLOAT32.toString(),_.BIT32],[y.FLOAT64.toString(),_.BIT64],[y.INT8.toString(),_.BIT8],[y.INT16.toString(),_.BIT16],[y.INT32.toString(),_.BIT32],[y.INT64.toString(),_.BIT64],[y.TIMESTAMP.toString(),_.BIT64],[y.STRING.toString(),_.UNKNOWN],[y.JSON.toString(),_.UNKNOWN],[y.UUID.toString(),_.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 I extends At{constructor(e){ce(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return ce(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return ce(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return ce(e)&&(e=e.value),new I(et(this.valueOf(),e.valueOf()))}sub(e){return ce(e)&&(e=e.value),new I(Kt(this.valueOf(),e.valueOf()))}mult(e){return new I(Te(this.valueOf(),e))}div(e){return new I(jn(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 Ca=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof b||t instanceof v||t instanceof Date},Bh=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Kt(n,r),qh=/^(?:[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 Fh(t){return typeof t=="string"&&qh.test(t)}const X=[];for(let t=0;t<256;++t)X.push((t+256).toString(16).slice(1));function Yh(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 Gh(t,e=0){const n=Yh(t,e);if(!Fh(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Ra=(t,e)=>Gh(t,e),je=-1,Vh=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Hh=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),kr=10,Wh=(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`)},_a="sy_x_telem_series";let Ma=class Le{key;discriminator=_a;dataType;sampleOffset;gl;_data;timeRange=Rt.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=je;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=i.z.object({timeRange:Rt.z.optional(),dataType:y.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Vh,Hh,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:Ph.default("static").optional()});static z=Le.crudeZ.transform(e=>new Le(e));constructor(e){Kh(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=dh(),data:u}=e;if(Jh(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=Ca(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 b||f instanceof Date||f instanceof b)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 b||O instanceof Date||O instanceof v)&&(f=f.map(S=>new b(S).valueOf())),this.dataType.equals(y.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
2
2
  `)}
3
- `).buffer):this.dataType.equals(B.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map($=>jr.encodeString($)).join(`
3
+ `).buffer):this.dataType.equals(y.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(S=>Nr.encodeString(S)).join(`
4
4
  `)}
5
- `).buffer):this.dataType.usesBigInt&&typeof v=="number"?this._data=new this.dataType.Array(f.map($=>BigInt(Math.round($)))).buffer:!this.dataType.usesBigInt&&typeof v=="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 B(n).Array(e),a=new Le({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===Me)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===Me)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===Me?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(B.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(jr.decodeString(n)))}get byteCapacity(){return new Dr(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Me?this.byteCapacity:this.dataType.isVariable?new Dr(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Me?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===Pr&&(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]=Ch(this.dataType,e,this.data[s],n);return new Le({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(B.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(),An(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(B.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(),An(this.cachedMin,this.sampleOffset))}get bounds(){return et(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const n=e.cachedMin??e.calcRawMin();n<this.cachedMin&&(this.cachedMin=n)}if(this.cachedMax!=null){const n=e.cachedMax??e.calcRawMax();n>this.cachedMax&&(this.cachedMax=n)}}atAlignment(e,n){const r=Number((e-this.alignment)/this.alignmentMultiple);if(r<0||r>=this.length){if(n===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,n)}at(e,n=!1){if(this.dataType.isVariable)return this.atVariable(e,n??!1);if(this.dataType.equals(B.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 An(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=ka(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]===Pr){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(B.STRING)?new TextDecoder().decode(a):wa(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=Gl(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(B.FLOAT32)&&!this.dataType.equals(B.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!==Me){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=Me}as(e){return Uh(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:mi(this.alignmentBounds.lower),upper:mi(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return et(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new qh(this);return this.dataType.equals(B.JSON)?new Fh(e):e}return this.dataType.equals(B.UUID)?new Vh(this):new Yh(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new yi(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 yi(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 Le({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 Le({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new Le({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 Lh=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Za?!0:Aa(t),Bh=Ah(xa,Za);class yi{series;end;index;constructor(e,n,r){this.series=e;const s=et(0,e.length+1);this.end=li(s,r),this.index=li(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}let qh=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]!==Pr;)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))})}},Fh=class Ca{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:jr.decodeString(e.value,Ca.schema)}}},Vh=class{series;index;data;density;constructor(e){if(!e.dataType.equals(B.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=B.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=ka(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}},Yh=class{series;index;constructor(t){this.series=t,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 mi=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}};i.z.object({key:i.z.string(),value:i.z.string()});i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown());const Hh=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Hh();const Wh=["macOS","Windows","Linux"],Gh=["macos","windows","linux"],Kh={macos:"macOS",windows:"Windows",linux:"Linux"};i.z.enum(Wh).or(i.z.enum(Gh).transform(t=>Kh[t]));const Jh=(...t)=>t.map(Ra).join(""),Ra=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Xh=t=>t.endsWith("/")?t.slice(0,-1):t,Qh=(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 ef=class kn{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=Ra(s)}replace(e){return new kn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new kn({...this,pathPrefix:Jh(this.path,e)})}toString(){return Xh(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new kn({host:"unknown",port:0})};const tf=async t=>await new Promise(e=>setTimeout(e,C.fromMilliseconds(t).milliseconds));class nf{config;retries;interval;constructor(e){this.config={baseInterval:new C(e?.baseInterval??C.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??tf},this.retries=0,this.interval=new C(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 rf=i.z.object({baseInterval:C.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),sf=Object.freeze(Object.defineProperty({__proto__:null,Breaker:nf,breakerConfigZ:rf},Symbol.toStringTag,{value:"Module"})),af=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,_a=i.z.string().regex(af),bt=i.z.number().min(0).max(255),ja=i.z.number().min(0).max(1),Ma=i.z.tuple([bt,bt,bt,ja]),of=i.z.tuple([bt,bt,bt]),cf=i.z.object({rgba255:Ma}),uf=i.z.number().min(0).max(360),lf=i.z.number().min(0).max(100),hf=i.z.number().min(0).max(100),ff=i.z.tuple([uf,lf,hf,ja]),ms=i.z.union([_a,of,Ma,ff,cf]),df=ms.transform(t=>gs(t)),gs=(t,e=1)=>{if(t=ms.parse(t),typeof t=="string")return pf(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},pf=(t,e=1)=>(t=_a.parse(t),t=yf(t),[Tn(t,0),Tn(t,2),Tn(t,4),t.length===8?Tn(t,6)/255:e]),Tn=(t,e)=>parseInt(t.slice(e,e+2),16),yf=t=>t.startsWith("#")?t.slice(1):t;gs("#000000");gs("#ffffff");const mf=i.z.object({key:i.z.string(),color:ms,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(mf);const gf=i.z.object({key:i.z.string(),name:i.z.string(),color:df});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(gf)});i.z.int().min(0).max(255);i.z.object({name:i.z.string(),key:i.z.string()});const wf=t=>Object.getOwnPropertySymbols(globalThis).includes(t),bf=(t,e)=>{const n=Symbol.for(t);if(!wf(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},Da="sy_x_error",vf=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),tn=t=>class Dt extends Error{static discriminator=Da;discriminator=Dt.discriminator;static TYPE=t;type=Dt.TYPE;static matches=vf(t);matches=Dt.matches;constructor(n,r){super(n,r),this.name=Dt.TYPE}static sub(n){return tn(`${t}.${n}`)}},Pa=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Da)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},pt="unknown",Ur="nil";let Tf=class{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Ur,data:""};if(Pa(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:pt,data:e.message};if(typeof e=="string")return{type:pt,data:e};try{return{type:pt,data:JSON.stringify(e)}}catch{return{type:pt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Ur)return null;if(e.type===pt)return new Lr(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new Lr(e.data)}};const ws=bf("synnax-error-registry",()=>new Tf),zf=({encode:t,decode:e})=>ws().register({encode:t,decode:e}),Ef=t=>ws().encode(t),Nf=t=>t==null?null:ws().decode(t);let Lr=class extends tn("unknown"){};const Of=i.z.object({type:i.z.string(),data:i.z.string()});class $f extends tn("canceled"){}let Sf=class extends tn("not_implemented"){};const qe=Object.freeze(Object.defineProperty({__proto__:null,Canceled:$f,NONE:Ur,NotImplemented:Sf,UNKNOWN:pt,Unknown:Lr,createTyped:tn,decode:Nf,encode:Ef,isTyped:Pa,payloadZ:Of,register:zf},Symbol.toStringTag,{value:"Module"})),If=i.object({jsonrpc:i.literal("2.0"),method:i.string(),params:i.any().optional(),id:i.union([i.string(),i.number(),i.null()]).optional()}),Ua=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()])}),Af=Ua.extend({result:i.json()}),kf=Ua.extend({error:i.object({code:i.number().int(),message:i.string().optional(),data:i.json().optional()})}),xf=i.union([Af,kf]);i.union([If,xf]);const Zf=i.uuid();i.object({key:Zf,name:i.string().min(1),color:i.string()});i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/);const Cf=["standard","scientific","engineering"];i.z.enum(Cf);i.z.enum(["success","info","warning","error","loading","disabled"]);i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)});let nn=class extends qe.createTyped("freighter"){},be=class extends nn.sub("eof"){constructor(){super("EOF")}},Nt=class extends nn.sub("stream_closed"){constructor(){super("StreamClosed")}},Fe=class extends nn.sub("unreachable"){url;constructor(e={}){const{message:n="Unreachable",url:r=ef.UNKNOWN}=e;super(n),this.url=r}};const Rf=t=>{if(!t.type.startsWith(nn.TYPE))return null;if(be.matches(t))return{type:be.TYPE,data:"EOF"};if(Nt.matches(t))return{type:Nt.TYPE,data:"StreamClosed"};if(Fe.matches(t))return{type:Fe.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},_f=t=>{if(!t.type.startsWith(nn.TYPE))return null;switch(t.type){case be.TYPE:return new be;case Nt.TYPE:return new Nt;case Fe.TYPE:return new Fe;default:throw new qe.Unknown(`Unknown error type: ${t.data}`)}};qe.register({encode:Rf,decode:_f});class La{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 Ba="Content-Type",jf=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),Mf=t=>{const e=t?.cause?.code??t?.code??t?.errno;if(typeof e=="string"&&jf.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},Df=400;class Pf extends La{endpoint;encoder;constructor(e,n,r=!1){return super(),this.endpoint=e.replace({protocol:r?"https":"http"}),this.encoder=n,new Proxy(this,{get:(s,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(s,a,o)})}get headers(){return{[Ba]: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(v){if(!(v instanceof Error))throw v;return[h,Mf(v)?new Fe({url:o}):v]}const f=await d.arrayBuffer();if(d?.ok)return s!=null&&(a=this.encoder.decode(f,s)),[h,null];try{if(d.status!==Df)return[h,new Error(d.statusText)];const v=this.encoder.decode(f,qe.payloadZ),$=qe.decode(v);return[h,$]}catch(v){return[h,new Error(`[freighter] - failed to decode error: ${d.statusText}: ${v.message}`)]}});if(l!=null)return[null,l];if(a==null)throw new Error("Response must be defined");return[a,null]}}const Uf=(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 sf.Breaker(e);do{const[u,h]=await this.wrapped.send(s,a,o,c);if(h==null)return[u,null];if(!Fe.matches(h))return[null,h];if(console.warn(`[freighter] ${l.retryMessage}`,h),!await l.wait())return[u,h]}while(!0)}}return new n(t)},w=async(t,e,n,r,s)=>{const[a,o]=await t.send(e,n,r,s);if(o!=null)throw o;return a},Lf=i.z.object({type:i.z.enum(["data","close","open"]),payload:i.z.unknown(),error:i.z.optional(qe.payloadZ)});class Bf{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 qe.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new be;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=qe.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,Lf))}onClose(e){this.addMessage({type:"close",error:{type:e.code===Ff?be.TYPE:Nt.TYPE,data:""}})}}const qf="freighterctx",Ff=1e3;let Vf=class Br extends La{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,n,r=!1){super(),this.secure=r,this.baseUrl=e.replace({protocol:r?"wss":"ws"}),this.encoder=n}withCodec(e){const n=new Br(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=Br.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=Qh({[Ba]:this.encoder.contentType,...n.params},qf);return this.baseUrl.child(e).toString()+r}async wrapSocket(e,n,r){return await new Promise(s=>{e.onopen=()=>{const a=new Bf(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 qa=t=>i.union([i.union([i.null(),i.undefined()]).transform(()=>[]),t.array()]),Yf=t=>Array.isArray(t)?t:t==null?[]:[t],Fa=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>Fa(s,a),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s==e),r=[...t];return n===-1?r.push(e):r[n]=e,r},Hf=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n)):t.filter(n=>n!=e)}),Va=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>Va(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},Wf=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n.key)):t.filter(n=>n.key!==e)}),T=Object.freeze(Object.defineProperty({__proto__:null,nullableZ:qa,remove:Hf,removeKeyed:Wf,toArray:Yf,upsert:Fa,upsertKeyed:Va},Symbol.toStringTag,{value:"Module"})),Gf=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=qr)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!vr(n))return n;r=Xf(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&&(vr(c)?wi(c)||(c=e(c,r)):r.recursiveInArray&&gi(c)&&(c=[...c].map(u=>{let h=u;return vr(u)?wi(h)||(h=e(u,r)):gi(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},bs=Wn(Gf),Kf=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),Ya=Wn(Kf),Ha=t=>t.length===0?t:t[0].toUpperCase()+t.slice(1),Jf=[Number,String,Uint8Array],qr={recursive:!0,recursiveInArray:!0},Xf=(t=qr)=>(t.recursive==null?t=qr:t.recursiveInArray??=!1,t),gi=t=>t!=null&&Array.isArray(t),vr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),wi=t=>Jf.some(e=>t instanceof e),Qf=t=>t.replace(/[\s_]+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}-${r.toLowerCase()}`).toLowerCase(),ed=Wn(Qf),td=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},nd=Wn(td),rd=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:Ya,capitalize:Ha,snakeToCamel:bs,toKebab:ed,toProperNoun:nd},Symbol.toStringTag,{value:"Module"})),Wa=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);let Ga=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=bs(r);return n!=null?n.parse(s):s}encodeString(e){const n=Ya(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}},Ka=class{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||!Wa(e[0]))throw new Error("Payload must be an array of objects");const n=Object.keys(e[0]),r=[n.join(",")];return e.forEach(s=>{const a=n.map(o=>JSON.stringify(s[o]??""));r.push(a.join(","))}),r.join(`
5
+ `).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(f.map(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??Rt.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 Le({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===je)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===je)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===je?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(Nr.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===je?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===je?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===kr&&(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]=Bh(this.dataType,e,this.data[s],n);return new Le({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(),et(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(),et(this.cachedMin,this.sampleOffset))}get bounds(){return tt(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 et(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=Ra(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]===kr){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):va(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=oh(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!==je){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=je}as(e){return Wh(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:zi(this.alignmentBounds.lower),upper:zi(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return tt(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 Xh(this);return this.dataType.equals(y.JSON)?new as(e):e}return this.dataType.equals(y.UUID)?new Qh(this):new ef(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new vi(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 vi(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 Le({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 Le({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new Le({data:this.buffer,dataType:this.dataType,timeRange:Rt.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 Kh=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Ma?!0:Ca(t),Jh=ph(_a,Ma);let vi=class{series;end;index;constructor(e,n,r){this.series=e;const s=tt(0,e.length+1);this.end=mi(s,r),this.index=mi(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}};class Xh{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]!==kr;)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:Nr.decodeString(e.value,as.schema)}}}let Qh=class{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=Ra(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}};class ef{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 zi=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},tf=async t=>await new Promise(e=>setTimeout(e,v.fromMilliseconds(t).milliseconds));let nf=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??tf},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 rf=i.z.object({baseInterval:v.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),sf=Object.freeze(Object.defineProperty({__proto__:null,Breaker:nf,breakerConfigZ:rf},Symbol.toStringTag,{value:"Module"})),af=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,ja=i.z.string().regex(af),vt=i.z.number().min(0).max(255),Ua=i.z.number().min(0).max(1),Da=i.z.tuple([vt,vt,vt,Ua]),of=i.z.tuple([vt,vt,vt]),cf=i.z.object({rgba255:Da}),uf=i.z.number().min(0).max(360),lf=i.z.number().min(0).max(100),hf=i.z.number().min(0).max(100),ff=i.z.tuple([uf,lf,hf,Ua]),os=i.z.union([ja,of,Da,ff,cf]),df=os.transform(t=>cs(t)),cs=(t,e=1)=>{if(t=os.parse(t),typeof t=="string")return pf(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},pf=(t,e=1)=>(t=ja.parse(t),t=yf(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),yf=t=>t.startsWith("#")?t.slice(1):t;cs("#000000");cs("#ffffff");const mf=i.z.object({key:i.z.string(),color:os,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(mf);const gf=i.z.object({key:i.z.string(),name:i.z.string(),color:df});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(gf)});i.z.int().min(0).max(255);i.z.object({name:i.z.string(),key:i.z.string()});const wf=t=>Object.getOwnPropertySymbols(globalThis).includes(t),bf=(t,e)=>{const n=Symbol.for(t);if(!wf(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},Pa="sy_x_error",vf=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),Jt=t=>class _t extends Error{static discriminator=Pa;discriminator=_t.discriminator;static TYPE=t;type=_t.TYPE;static matches=vf(t);matches=_t.matches;constructor(n,r){super(n,r),this.name=_t.TYPE}static sub(n){return Jt(`${t}.${n}`)}},La=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Pa)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},gt="unknown",Ar="nil";class zf{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Ar,data:""};if(La(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:gt,data:e.message};if(typeof e=="string")return{type:gt,data:e};try{return{type:gt,data:JSON.stringify(e)}}catch{return{type:gt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Ar)return null;if(e.type===gt)return new $r(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new $r(e.data)}}const us=bf("synnax-error-registry",()=>new zf),Tf=({encode:t,decode:e})=>us().register({encode:t,decode:e}),Of=t=>us().encode(t),Ef=t=>t==null?null:us().decode(t);let $r=class extends Jt("unknown"){};const Nf=i.z.object({type:i.z.string(),data:i.z.string()});let Sf=class extends Jt("canceled"){},kf=class extends Jt("not_implemented"){};const Fe=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Sf,NONE:Ar,NotImplemented:kf,UNKNOWN:gt,Unknown:$r,createTyped:Jt,decode:Ef,encode:Of,isTyped:La,payloadZ:Nf,register:Tf},Symbol.toStringTag,{value:"Module"})),Af=i.object({jsonrpc:i.literal("2.0"),method:i.string(),params:i.any().optional(),id:i.union([i.string(),i.number(),i.null()]).optional()}),Ba=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()])}),$f=Ba.extend({result:i.json()}),If=Ba.extend({error:i.object({code:i.number().int(),message:i.string().optional(),data:i.json().optional()})}),Zf=i.union([$f,If]);i.union([Af,Zf]);i.z.object({key:i.z.string(),value:i.z.string()});const xf=i.uuid();i.object({key:xf,name:i.string().min(1),color:i.string()});i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/);const Cf=["standard","scientific","engineering"];i.z.enum(Cf);i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown());const Rf=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Rf();const _f=["macOS","Windows","Linux"],Mf=["macos","windows","linux"],jf={macos:"macOS",windows:"Windows",linux:"Linux"};i.z.enum(_f).or(i.z.enum(Mf).transform(t=>jf[t]));i.z.enum(["success","info","warning","error","loading","disabled"]);i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)});const Uf=(...t)=>t.map(qa).join(""),qa=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Df=t=>t.endsWith("/")?t.slice(0,-1):t,Pf=(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 Lf=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=qa(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:Uf(this.path,e)})}toString(){return Df(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new Nn({host:"unknown",port:0})};i.z.int().min(0).max(yh);class Xt extends Fe.createTyped("freighter"){}let ye=class extends Xt.sub("eof"){constructor(){super("EOF")}},Et=class extends Xt.sub("stream_closed"){constructor(){super("StreamClosed")}},Ye=class extends Xt.sub("unreachable"){url;constructor(e={}){const{message:n="Unreachable",url:r=Lf.UNKNOWN}=e;super(n),this.url=r}};const Bf=t=>{if(!t.type.startsWith(Xt.TYPE))return null;if(ye.matches(t))return{type:ye.TYPE,data:"EOF"};if(Et.matches(t))return{type:Et.TYPE,data:"StreamClosed"};if(Ye.matches(t))return{type:Ye.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},qf=t=>{if(!t.type.startsWith(Xt.TYPE))return null;switch(t.type){case ye.TYPE:return new ye;case Et.TYPE:return new Et;case Ye.TYPE:return new Ye;default:throw new Fe.Unknown(`Unknown error type: ${t.data}`)}};Fe.register({encode:Bf,decode:qf});let Fa=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 Ya="Content-Type",Ff=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),Yf=t=>{const e=t?.cause?.code??t?.code??t?.errno;if(typeof e=="string"&&Ff.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},Gf=400;let Vf=class extends Fa{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{[Ya]: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,Yf(O)?new Ye({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!==Gf)return[h,new Error(d.statusText)];const O=this.encoder.decode(f,Fe.payloadZ),S=Fe.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 Hf=(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 sf.Breaker(e);do{const[u,h]=await this.wrapped.send(s,a,o,c);if(h==null)return[u,null];if(!Ye.matches(h))return[null,h];if(console.warn(`[freighter] ${l.retryMessage}`,h),!await l.wait())return[u,h]}while(!0)}}return new n(t)},T=async(t,e,n,r,s)=>{const[a,o]=await t.send(e,n,r,s);if(o!=null)throw o;return a},Wf=i.z.object({type:i.z.enum(["data","close","open"]),payload:i.z.unknown(),error:i.z.optional(Fe.payloadZ)});let Kf=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 Fe.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new ye;if(this.sendClosed)throw new Et;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=Fe.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,Wf))}onClose(e){this.addMessage({type:"close",error:{type:e.code===Xf?ye.TYPE:Et.TYPE,data:""}})}};const Jf="freighterctx",Xf=1e3;let Qf=class Ir extends Fa{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 Ir(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=Ir.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=Pf({[Ya]:this.encoder.contentType,...n.params},Jf);return this.baseUrl.child(e).toString()+r}async wrapSocket(e,n,r){return await new Promise(s=>{e.onopen=()=>{const a=new Kf(e,this.encoder,n,r);a.receiveOpenAck().then(o=>{o!=null?s(o):s(a)}).catch(o=>s(o))},e.onerror=a=>{const o=a;s(new Error(o.message))}})}};const Ga=t=>i.union([i.union([i.null(),i.undefined()]).transform(()=>[]),t.array()]),ed=t=>Array.isArray(t)?t:t==null?[]:[t],Va=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>Va(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},td=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n)):t.filter(n=>n!=e)}),Ha=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>Ha(s,a),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s.key===e.key),r=[...t];return n===-1?r.push(e):r[n]=e,r},nd=((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:Ga,remove:td,removeKeyed:nd,toArray:ed,upsert:Va,upsertKeyed:Ha},Symbol.toStringTag,{value:"Module"})),rd=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=Zr)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!cr(n))return n;r=ad(r);const s={},a=n;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),r):(Object.keys(a).forEach(o=>{let c=a[o];const l=t(o);r.recursive&&(cr(c)?Oi(c)||(c=e(c,r)):r.recursiveInArray&&Ti(c)&&(c=[...c].map(u=>{let h=u;return cr(u)?Oi(h)||(h=e(u,r)):Ti(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},ls=Un(rd),sd=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),Wa=Un(sd),Ka=t=>t.length===0?t:t[0].toUpperCase()+t.slice(1),id=[Number,String,Uint8Array],Zr={recursive:!0,recursiveInArray:!0},ad=(t=Zr)=>(t.recursive==null?t=Zr:t.recursiveInArray??=!1,t),Ti=t=>t!=null&&Array.isArray(t),cr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Oi=t=>id.some(e=>t instanceof e),od=t=>t.replace(/[\s_]+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}-${r.toLowerCase()}`).toLowerCase(),cd=Un(od),ud=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},ld=Un(ud),hd=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:Wa,capitalize:Ka,snakeToCamel:ls,toKebab:cd,toProperNoun:ld},Symbol.toStringTag,{value:"Module"})),fd=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);class Ja{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=ls(r);return n!=null?n.parse(s):s}encodeString(e){const n=Wa(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}}class Xa{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||!fd(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}},Ja=class{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 Ga,sd=new Ka,id=new Ja,ad=[Ft],it=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Ka,CSV_CODEC:sd,ENCODERS:ad,JSONCodec:Ga,JSON_CODEC:Ft,TEXT_CODEC:id,TextCodec:Ja},Symbol.toStringTag,{value:"Module"})),Fr=t=>[...new Set(t)],od=(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())},bi=Object.freeze(Object.defineProperty({__proto__:null,by:od,unique:Fr},Symbol.toStringTag,{value:"Module"})),fe=t=>t!=null&&typeof t=="object"&&"value"in t;let At=class{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const cd=t=>t!=null&&typeof t=="object"&&"toString"in t,rn=(t,e=!1)=>{const n=cd(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?Qa(r):r},ud=(t,e,n)=>{const r=rn(e[t],n);return(s,a)=>r(s[t],a[t])},ld=(t,e)=>t.length!==e.length?t.length-e.length:t.every((n,r)=>n===e[r])?0:-1,Xa=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const n=rn(t[0]),r=[...t].sort(n),s=[...e].sort(n);return r.every((a,o)=>a===s[o])?0:-1},hd=(t,e)=>{const n=Fr(t),r=Fr(e);return Xa(n,r)},fd=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,Qa=t=>(e,n)=>t(n,e),at=0,Ze=-1,Ce=1,eo=t=>t<at,to=t=>t>at,dd=t=>t>=at,no=t=>t===at,pd=(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},Gn=i.z.tuple([i.z.number(),i.z.number()]);i.z.tuple([i.z.bigint(),i.z.bigint()]);const ro=i.z.object({width:i.z.number(),height:i.z.number()}),yd=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),md=["width","height"];i.z.enum(md);const gd=["start","center","end"],wd=["signedWidth","signedHeight"];i.z.enum(wd);const Vt=i.z.object({x:i.z.number(),y:i.z.number()}),so=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),io=["x","y"],ao=i.z.enum(io),vs=["top","right","bottom","left"],bd=i.z.enum(vs),oo=["left","right"],Ts=i.z.enum(oo),co=["top","bottom"],zs=i.z.enum(co),Es=["center"],Vr=i.z.enum(Es),vd=[...vs,...Es],Ns=i.z.enum(vd);i.z.enum(gd);const Td=["first","last"];i.z.enum(Td);const zd=i.z.object({lower:i.z.number(),upper:i.z.number()}),Ed=i.z.object({lower:i.z.bigint(),upper:i.z.bigint()});i.z.union([zd,Gn]);i.z.union([Ed,Gn]);i.z.enum([...ao.options,...Ns.options]);i.z.enum(["x","left","right"]);i.z.enum(["y","top","bottom"]);const Nd=i.z.union([ao,Ns,i.z.instanceof(String)]),kt=t=>(e,n)=>{if(typeof e=="bigint"){if(Rn(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))},Be=kt((t,e)=>t-e),xt=kt((t,e)=>t+e),Od=(t,e,n=1e-4)=>Math.abs(t-e)<n,Yr=(t,e)=>{const n=typeof t=="bigint",r=typeof e=="bigint";return n&&r?t===e:n&&Rn(e)?t===BigInt(e):r&&Rn(t)?e===BigInt(t):t===e},$d=t=>{const e=10**Math.floor(Math.log10(t));return Math.round(t/e)*e},uo=kt((t,e)=>t<=e?t:e),Rn=t=>typeof t=="bigint"?!0:Number.isInteger(t),Sd=kt((t,e)=>t>=e?t:e),lo=t=>typeof t=="bigint"?t<0n?-t:t:t<0?-t:t,ge=kt((t,e)=>t*e),sn=kt((t,e)=>t/e),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?Id(r):r},Id=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,vi=(t,e)=>{const n=K(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e},zn=(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},ho=t=>{const e=K(t);return e.upper-e.lower},Ad=t=>({lower:Math.min(...t.map(e=>K(e).lower)),upper:Math.max(...t.map(e=>K(e).upper))}),kd=(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(;Yr(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=Be(l.upper,o):u=Be(o,l.lower),u>0){const h=uo(lo(a),u);if(o=xt(o,s>0?h:-h),a=Be(a,s>0?h:-h),Yr(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},xd=(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,l=o.upper<s.upper?o.upper:s.upper;if(c<l){const u=l-c;a=a+u}}return a},Zd=Ts,Cd=zs,Rd=Vr,_d={top:"bottom",right:"left",bottom:"top",left:"right",center:"center"},jd={top:"left",right:"top",bottom:"right",left:"bottom",center:"center"},Md=Nd,Ve=t=>t instanceof String||!io.includes(t)?t:t==="x"?"left":"top",Dd=t=>_d[Ve(t)],Pd=t=>jd[Ve(t)],Yt=t=>{const e=Ve(t);return e==="top"||e==="bottom"?"y":"x"},Ud=i.z.object({x:Ts.or(Vr),y:zs.or(Vr)}),fo=i.z.object({x:Ts,y:zs}),Os=Object.freeze({x:"left",y:"top"}),po=Object.freeze({x:"right",y:"top"}),yo=Object.freeze({x:"left",y:"bottom"}),mo=Object.freeze({x:"right",y:"bottom"}),$s=Object.freeze({x:"center",y:"center"}),go=Object.freeze({x:"center",y:"top"}),wo=Object.freeze({x:"center",y:"bottom"}),bo=Object.freeze({x:"right",y:"center"}),vo=Object.freeze({x:"left",y:"center"}),Ld=Object.freeze([vo,bo,go,wo,Os,po,yo,mo,$s]),To=(t,e)=>t.x===e.x&&t.y===e.y,Bd=(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},qd=t=>[t.x,t.y],xn=t=>Yt(Ve(t))==="x",Fd=t=>Yt(Ve(t))==="y",Vd=t=>`${t.x}${Ha(t.y)}`,Yd=(t,e)=>{let n,r;if(typeof t=="object"&&"x"in t?(n=t.x,r=t.y):(n=Ve(t),r=Ve(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={...$s};return n==="center"?xn(r)?[s.x,s.y]=[r,n]:[s.x,s.y]=[n,r]:r==="center"?xn(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n]:xn(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n],s},Hd=Object.freeze(Object.defineProperty({__proto__:null,BOTTOM_CENTER:wo,BOTTOM_LEFT:yo,BOTTOM_RIGHT:mo,CENTER:$s,CENTER_LEFT:vo,CENTER_LOCATIONS:Es,CENTER_RIGHT:bo,OUTER_LOCATIONS:vs,TOP_CENTER:go,TOP_LEFT:Os,TOP_RIGHT:po,XY_LOCATIONS:Ld,X_LOCATIONS:oo,Y_LOCATIONS:co,center:Rd,construct:Ve,constructXY:Yd,corner:fo,crude:Md,direction:Yt,isX:xn,isY:Fd,location:Ns,outer:bd,rotate90:Pd,swap:Dd,x:Zd,xy:Ud,xyCouple:qd,xyEquals:To,xyMatches:Bd,xyToString:Vd,y:Cd},Symbol.toStringTag,{value:"Module"})),Hr=i.z.union([i.z.number(),Vt,Gn,ro,yd,so]),M=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},nt=Object.freeze({x:0,y:0}),Wd=Object.freeze({x:1,y:1}),Gd=Object.freeze({x:1/0,y:1/0}),Kd=Object.freeze({x:NaN,y:NaN}),zo=(t,e,n=0)=>{const r=M(t),s=M(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},Jd=t=>zo(t,nt),Ss=(t,e,n)=>{const r=M(t),s=M(e,n);return{x:r.x*s.x,y:r.y*s.y}},Eo=(t,e)=>{const n=M(t);return{x:n.x+e,y:n.y}},No=(t,e)=>{const n=M(t);return{x:n.x,y:n.y+e}},Oo=(t,e,n,...r)=>{if(typeof e=="string"){if(typeof n!="number")throw new Error("The value must be a number.");return e==="x"?Eo(t,n):No(t,n)}if(typeof e=="object"&&"x"in e&&typeof e.x=="string"){const s=M(n),a=M(t);return e.x==="left"?s.x=-s.x:e.x==="center"&&(s.x=0),e.y==="top"?s.y=-s.y:e.y==="center"&&(s.y=0),{x:a.x+s.x,y:a.y+s.y}}return[t,e,n??nt,...r].reduce((s,a)=>{const o=M(a);return{x:s.x+o.x,y:s.y+o.y}},nt)},Xd=(t,e,n)=>{const r=M(t);return e==="x"?{x:n,y:r.y}:{x:r.x,y:n}},Qd=(t,e)=>{const n=M(t),r=M(e);return Math.sqrt((n.x-r.x)**2+(n.y-r.y)**2)},ep=(t,e)=>{const n=M(t),r=M(e);return{x:r.x-n.x,y:r.y-n.y}},tp=t=>{const e=M(t);return Number.isNaN(e.x)||Number.isNaN(e.y)},np=t=>{const e=M(t);return Number.isFinite(e.x)&&Number.isFinite(e.y)},rp=t=>{const e=M(t);return[e.x,e.y]},sp=t=>{const e=M(t);return{left:e.x,top:e.y}},ip=(t,e=0)=>{const n=M(t);return{x:Number(n.x.toFixed(e)),y:Number(n.y.toFixed(e))}},Pt=(t,e)=>{const n=M(t),r=M(e);return{x:n.x-r.x,y:n.y-r.y}},Ut=t=>{const e=M(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:-e.y/n,y:e.x/n}},$o=t=>{const e=M(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:e.x/n,y:e.y/n}},So=(...t)=>{const e=t.reduce((n,r)=>Oo(n,r),nt);return Ss(e,1/t.length)},ap=(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=Pt(u,s);o=Ut(h),c=o,l=e}else if(r===t.length-1){const u=t[r-1],h=Pt(s,u);a=Ut(h),c=a,l=e}else{const u=t[r-1],h=t[r+1],d=Pt(s,u),f=Pt(h,s);a=Ut(d),o=Ut(f);const v=Math.acos((d.x*f.x+d.y*f.y)/(Math.hypot(d.x,d.y)*Math.hypot(f.x,f.y))),$=Math.sin(v/2);$===0?l=e:l=e/$,c=$o(So(a,o))}n.push(Ss(c,l))}return n},op=t=>{const e=M(t);return{x:e.y,y:e.x}},cp=t=>{const e=M(t);return{x:Math.round(e.x),y:Math.round(e.y)}},up=t=>{const e=M(t);return{x:1/e.x,y:1/e.y}},Is=Object.freeze(Object.defineProperty({__proto__:null,INFINITY:Gd,NAN:Kd,ONE:Wd,ZERO:nt,average:So,calculateMiters:ap,clientXY:so,construct:M,couple:rp,crudeZ:Hr,css:sp,distance:Qd,equals:zo,isFinite:np,isNan:tp,isZero:Jd,normal:Ut,normalize:$o,reciprocal:up,round:cp,scale:Ss,set:Xd,sub:Pt,swap:op,translate:Oo,translateX:Eo,translateY:No,translation:ep,truncate:ip,xy:Vt},Symbol.toStringTag,{value:"Module"})),En=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:En,left:En,width:En,height:En});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:Vt,two:Vt,root:fo});const As=(t,e,n=0,r=0,s)=>{const a={one:{...nt},two:{...nt},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))},Tr=t=>{const e=As(t);return{lower:e.one.x,upper:e.two.x}},zr=t=>{const e=As(t);return{lower:e.one.y,upper:e.two.y}},lp=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,hp=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([ro,hp,Vt,Gn]);const fp=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:Hr,scale:Hr});i.z.object({offset:i.z.number(),scale:i.z.number()});const dp=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],pp=t=>(e,n,r,s)=>[e,s?r/t:r*t],yp=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]},mp=t=>(e,n,r)=>[t,r],gp=()=>(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)]},wp=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=fp(r,s,a),[e,r]};let Ti=class yt{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new yt().translate(e)}static magnify(e){return new yt().magnify(e)}static scale(e,n){return new yt().scale(e,n)}translate(e){const n=this.new(),r=dp(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=pp(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=K(e,n),s=this.new(),a=yp(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=K(e,n),s=this.new(),a=wp(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=K(e,n),s=this.new(),a=mp(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=gp();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 yt;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 yt},BS=class Oe{x;y;currRoot;constructor(e=new Ti,n=new Ti,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new Oe().translate(e,n)}static translateX(e){return new Oe().translateX(e)}static translateY(e){return new Oe().translateY(e)}static clamp(e){return new Oe().clamp(e)}static magnify(e){return new Oe().magnify(e)}static scale(e){return new Oe().scale(e)}static reBound(e){return new Oe().reBound(e)}translate(e,n){const r=M(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(lp(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!To(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(Tr(e)),n.y=n.y.scale(zr(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(Tr(e)),n.y=this.y.reBound(zr(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(Tr(e)),n.y=this.y.clamp(zr(e)),n}copy(){const e=new Oe;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return As(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new Oe},Io=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const Ao="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",bp=`0123456789${Ao}`,ko=11,vp=Io(Ao,1),Tp=Io(bp,ko-1),ks=()=>`${vp()}${Tp()}`,zp=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:ko,create:ks},Symbol.toStringTag,{value:"Module"})),Ep=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,Np=i.z.enum(["static","dynamic"]),Op=2**8-1,$p=2**16-1,Sp=2**32-1,Ip=2n**64n-1n,Ap=2**64-1,kp=-128,xp=2**7-1,Zp=-32768,Cp=2**15-1,Rp=-2147483648,_p=2**31-1,jp=-(2n**63n),_n=2n**63n-1n,Mp=-9223372036854776e3,xo=2**63-1,zi=365,Nn=30,Dp=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)])]),Zo=(t,e)=>{const n=new p(e);if(![S.DAY,S.HOUR,S.MINUTE,S.SECOND,S.MILLISECOND,S.MICROSECOND,S.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 p?new p(r):new S(r)};class p extends At{constructor(e,n="UTC"){if(e==null)super(p.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*p.MILLISECOND.valueOf());else if(typeof e=="string")super(p.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(p.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=p.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===xo?e=_n:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=p.MAX:e=p.MIN)),fe(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 p(BigInt(s.getTime())*p.MILLISECOND.valueOf()).truncate(p.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=p.hours(parseInt(r??"00")).add(p.minutes(parseInt(s??"00"))).add(p.seconds(parseInt(o??"00"))).add(p.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(p.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return p.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())*p.MILLISECOND.valueOf(),l=BigInt(a)*p.MILLISECOND.valueOf();return c+l}const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new p(BigInt(r.getTime())*p.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(p.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 S(BigInt(new Date().getTimezoneOffset())*p.MINUTE.valueOf())}static since(e){return new p().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new p(e).valueOf()}span(e){return this.range(e).span}range(e){return new P(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new p(e).valueOf()}afterEq(e){return this.valueOf()>=new p(e).valueOf()}before(e){return this.valueOf()<new p(e).valueOf()}beforeEq(e){return this.valueOf()<=new p(e).valueOf()}add(e){return new p(xt(this.valueOf(),new S(e).valueOf()))}sub(e){return new p(Be(this.valueOf(),new S(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(S.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(S.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(S.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(S.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(p.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(p.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 p(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new p(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new p(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new p(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new p(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new p(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new p(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new p(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 Zo(this,e)}get isToday(){return this.truncate(S.DAY).equals(p.now().truncate(S.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(S.days(30))?"shortDate":e.greaterThanOrEqual(S.DAY)?"dateTime":e.greaterThanOrEqual(S.HOUR)?"time":e.greaterThanOrEqual(S.SECOND)?"preciseTime":"ISOTime"}static now(){return new p(new Date)}static max(...e){let n=p.MIN;for(const r of e){const s=new p(r);s.after(n)&&(n=s)}return n}static min(...e){let n=p.MAX;for(const r of e){const s=new p(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new p(e,n)}static NANOSECOND=p.nanoseconds(1);static microseconds(e,n="UTC"){return p.nanoseconds(e*1e3,n)}static MICROSECOND=p.microseconds(1);static milliseconds(e,n="UTC"){return p.microseconds(e*1e3,n)}static MILLISECOND=p.milliseconds(1);static seconds(e,n="UTC"){return p.milliseconds(e*1e3,n)}static SECOND=p.seconds(1);static minutes(e,n="UTC"){return p.seconds(e*60,n)}static MINUTE=p.minutes(1);static hours(e,n="UTC"){return p.minutes(e*60,n)}static HOUR=p.hours(1);static days(e,n="UTC"){return p.hours(e*24,n)}static DAY=p.days(1);static MAX=new p(_n);static MIN=new p(0);static ZERO=new p(0);static z=i.z.union([i.z.instanceof(p),i.z.object({value:i.z.bigint()}).transform(e=>new p(e.value)),i.z.string().transform(e=>new p(BigInt(e))),i.z.number().transform(e=>new p(e)),i.z.bigint().transform(e=>new p(e)),i.z.date().transform(e=>new p(e)),i.z.custom(e=>e instanceof S).transform(e=>new p(e)),Dp.transform(e=>new p(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}}let S=class O extends At{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),fe(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof O?e:e instanceof se?e.period:e instanceof p?new O(e):(fe(e)&&(e=e.value),["number","bigint"].includes(typeof e)?O.seconds(e):new O(e))}static fromMilliseconds(e){return e instanceof O?e:e instanceof se?e.period:e instanceof p?new O(e):(fe(e)&&(e=e.value),["number","bigint"].includes(typeof e)?O.milliseconds(e):new O(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new O(e).valueOf()}greaterThan(e){return this.valueOf()>new O(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new O(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new O(e).valueOf()}remainder(e){return Zo(this,e)}truncate(e){return new O(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(O.DAY),r=this.truncate(O.HOUR),s=this.truncate(O.MINUTE),a=this.truncate(O.SECOND),o=this.truncate(O.MILLISECOND),c=this.truncate(O.MICROSECOND),l=this.truncate(O.NANOSECOND),u=n,h=r.sub(n),d=s.sub(r),f=a.sub(s),v=o.sub(a),$=c.sub(o),k=l.sub(c);let b="";return u.isZero||(b+=`${u.days}d `),h.isZero||(b+=`${h.hours}h `),d.isZero||(b+=`${d.minutes}m `),f.isZero||(b+=`${f.seconds}s `),v.isZero||(b+=`${v.milliseconds}ms `),$.isZero||(b+=`${$.microseconds}µs `),k.isZero||(b+=`${k.nanoseconds}ns`),b.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new O(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(O.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/zi),u=Math.floor(s/Nn),h=Math.floor(s/7),d=Math.floor(s),f=Math.floor(a),v=Math.floor(o),$=Math.floor(c),k=r?"-":"";if(l>=1){let b=`${l}y`;if(l<2){const E=Math.floor(s%zi/Nn);E>0&&(b+=` ${E}mo`)}return k+b}if(h>=1&&s<Nn&&s%7===0){let b=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?b+=` ${E}d`:A>0&&A<24&&(b+=` ${A}h`)),k+b}if(u>=1){let b=`${u}mo`;if(u<3){const E=Math.floor(s%Nn);E>0&&(b+=` ${E}d`)}return k+b}if(h>=1){let b=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?b+=` ${E}d`:A>0&&A<24&&(b+=` ${A}h`)),k+b}if(d>=1){let b=`${d}d`;const E=Math.floor(a-d*24);return d<2&&E>0&&(b+=` ${E}h`),k+b}if(f>=1){let b=`${f}h`;if(f<3){const E=Math.floor(o-f*60);E>0&&(b+=` ${E}m`)}return k+b}if(v>=1){let b=`${v}m`;if(v<5){const E=Math.floor(c-v*60);E>0&&(b+=` ${E}s`)}return k+b}return`${k}${$}s`}mult(e){return new O(ge(this.valueOf(),e))}div(e){return new O(sn(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(O.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(O.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(O.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(O.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(O.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(O.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new O(e).valueOf()}add(e){return new O(this.valueOf()+new O(e).valueOf())}sub(e){return new O(this.valueOf()-new O(e).valueOf())}static nanoseconds(e=1){return new O(e)}static NANOSECOND=O.nanoseconds(1);static microseconds(e=1){return O.nanoseconds(ge(e,1e3))}static MICROSECOND=O.microseconds(1);static milliseconds(e=1){return O.microseconds(ge(e,1e3))}static MILLISECOND=O.milliseconds(1);static seconds(e=1){return O.milliseconds(ge(e,1e3))}static SECOND=O.seconds(1);static minutes(e=1){return O.seconds(ge(e,60))}static MINUTE=O.minutes(1);static hours(e){return O.minutes(ge(e,60))}static HOUR=O.hours(1);static days(e){return O.hours(ge(e,24))}static DAY=O.days(1);static MAX=new O(_n);static MIN=new O(0);static ZERO=new O(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new O(e.value)),i.z.string().transform(e=>new O(BigInt(e))),i.z.number().transform(e=>new O(e)),i.z.bigint().transform(e=>new O(e)),i.z.instanceof(O),i.z.instanceof(p).transform(e=>new O(e)),i.z.custom(e=>e instanceof se).transform(e=>new O(e))])};class se extends At{constructor(e){fe(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new se(e).valueOf()}get period(){return S.seconds(1/this.valueOf())}sampleCount(e){return new S(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new Q(n).valueOf()}span(e){return S.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new Q(n).valueOf())}add(e){return new se(xt(this.valueOf(),new se(e).valueOf()))}sub(e){return new se(Be(this.valueOf(),new se(e).valueOf()))}mult(e){return new se(ge(this.valueOf(),e))}div(e){return new se(sn(this.valueOf(),e))}static hz(e){return new se(e)}static khz(e){return se.hz(e*1e3)}static z=i.z.union([i.z.number().transform(e=>new se(e)),i.z.instanceof(se)])}let Q=class ae extends At{constructor(e){fe(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new Ot(e*this.valueOf())}add(e){return new ae(xt(this.valueOf(),new ae(e).valueOf()))}sub(e){return new ae(Be(this.valueOf(),new ae(e).valueOf()))}mult(e){return new ae(ge(this.valueOf(),e))}div(e){return new ae(sn(this.valueOf(),e))}static UNKNOWN=new ae(0);static BIT128=new ae(16);static BIT64=new ae(8);static BIT32=new ae(4);static BIT16=new ae(2);static BIT8=new ae(1);static z=i.z.union([i.z.number().transform(e=>new ae(e)),i.z.instanceof(ae)])},P=class $e{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new p(e.start),this.end=new p(e.end)):(this.start=new p(e),this.end=new p(n))}get span(){return new S(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new $e(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=S.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=S.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=p.max(r.start,e.start),a=p.min(r.end,e.end);return a.before(s)?!1:new S(a.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof $e?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new $e(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 $e(p.min(...e.map(n=>n.start)),p.max(...e.map(n=>n.end)))}static MAX=new $e(p.MIN,p.MAX);static ZERO=new $e(p.ZERO,p.ZERO);static z=i.z.union([i.z.object({start:p.z,end:p.z}).transform(e=>new $e(e.start,e.end)),i.z.instanceof($e)]);static sort(e,n){return p.sort(e.start,n.start)||p.sort(e.end,n.end)}static simplify(e){return e.map(n=>n.makeValid()).sort((n,r)=>$e.sort(n,r)).reduce((n,r)=>{if(r.span.isZero)return n;if(n.length===0)return n.push(r),n;const s=n[n.length-1];return s.overlapsWith(r)||s.end.equals(r.start)?s.end=p.max(s.end,r.end):n.push(r),n},[])}},R=class g extends At{constructor(e){if(fe(e)&&(e=e.value),e instanceof g||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=g.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=g.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?g.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(g.JSON)||this.equals(g.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(g.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=g.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(g.UINT8)||this.equals(g.UINT16)||this.equals(g.UINT32)||this.equals(g.UINT64)}get isSignedInteger(){return this.equals(g.INT8)||this.equals(g.INT16)||this.equals(g.INT32)||this.equals(g.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(g.INT32)&&e.equals(g.FLOAT64)||this.equals(g.INT8)&&e.equals(g.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 g.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new g("unknown");static FLOAT64=new g("float64");static FLOAT32=new g("float32");static INT64=new g("int64");static INT32=new g("int32");static INT16=new g("int16");static INT8=new g("int8");static UINT64=new g("uint64");static UINT32=new g("uint32");static UINT16=new g("uint16");static UINT8=new g("uint8");static BOOLEAN=new g("boolean");static TIMESTAMP=new g("timestamp");static UUID=new g("uuid");static STRING=new g("string");static JSON=new g("json");static ARRAY_CONSTRUCTORS=new Map([[g.UINT8.toString(),Uint8Array],[g.UINT16.toString(),Uint16Array],[g.UINT32.toString(),Uint32Array],[g.UINT64.toString(),BigUint64Array],[g.FLOAT32.toString(),Float32Array],[g.FLOAT64.toString(),Float64Array],[g.INT8.toString(),Int8Array],[g.INT16.toString(),Int16Array],[g.INT32.toString(),Int32Array],[g.INT64.toString(),BigInt64Array],[g.TIMESTAMP.toString(),BigInt64Array],[g.STRING.toString(),Uint8Array],[g.JSON.toString(),Uint8Array],[g.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,g.UINT8],[Uint16Array.name,g.UINT16],[Uint32Array.name,g.UINT32],[BigUint64Array.name,g.UINT64],[Float32Array.name,g.FLOAT32],[Float64Array.name,g.FLOAT64],[Int8Array.name,g.INT8],[Int16Array.name,g.INT16],[Int32Array.name,g.INT32],[BigInt64Array.name,g.INT64]]);static DENSITIES=new Map([[g.UINT8.toString(),Q.BIT8],[g.UINT16.toString(),Q.BIT16],[g.UINT32.toString(),Q.BIT32],[g.UINT64.toString(),Q.BIT64],[g.FLOAT32.toString(),Q.BIT32],[g.FLOAT64.toString(),Q.BIT64],[g.INT8.toString(),Q.BIT8],[g.INT16.toString(),Q.BIT16],[g.INT32.toString(),Q.BIT32],[g.INT64.toString(),Q.BIT64],[g.TIMESTAMP.toString(),Q.BIT64],[g.STRING.toString(),Q.UNKNOWN],[g.JSON.toString(),Q.UNKNOWN],[g.UUID.toString(),Q.BIT128]]);static ALL=[g.UNKNOWN,g.FLOAT64,g.FLOAT32,g.INT64,g.INT32,g.INT16,g.INT8,g.UINT64,g.UINT32,g.UINT16,g.UINT8,g.TIMESTAMP,g.UUID,g.STRING,g.JSON];static SHORT_STRINGS=new Map([[g.UINT8.toString(),"u8"],[g.UINT16.toString(),"u16"],[g.UINT32.toString(),"u32"],[g.UINT64.toString(),"u64"],[g.INT8.toString(),"i8"],[g.INT16.toString(),"i16"],[g.INT32.toString(),"i32"],[g.INT64.toString(),"i64"],[g.FLOAT32.toString(),"f32"],[g.FLOAT64.toString(),"f64"],[g.BOOLEAN.toString(),"bool"],[g.TIMESTAMP.toString(),"ts"],[g.UUID.toString(),"uuid"],[g.STRING.toString(),"str"],[g.JSON.toString(),"json"]]);static BIG_INT_TYPES=[g.INT64,g.UINT64,g.TIMESTAMP];static z=i.z.union([i.z.string().transform(e=>new g(e)),i.z.instanceof(g)])},Ot=class Z extends At{constructor(e){fe(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return fe(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return fe(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return fe(e)&&(e=e.value),new Z(xt(this.valueOf(),e.valueOf()))}sub(e){return fe(e)&&(e=e.value),new Z(Be(this.valueOf(),e.valueOf()))}mult(e){return new Z(ge(this.valueOf(),e))}div(e){return new Z(sn(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),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 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 Co=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof p||t instanceof S||t instanceof Date},Pp=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Zn(n,-r),Zn=(t,e)=>e==0?t:t==0?e:typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:Number(t)+Number(e),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 Bp(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 qp(t,e=0){const n=Bp(t,e);if(!Lp(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Ro=(t,e)=>qp(t,e),De=-1,Wr={[Symbol.iterator]:()=>Wr,next:()=>({done:!0,value:void 0})},Fp=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Vp=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Gr=10,_o=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},jo="sy_x_telem_series";class ee{key;discriminator=jo;dataType;sampleOffset;gl;_data;timeRange=P.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=De;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=i.z.object({timeRange:P.z.optional(),dataType:R.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Fp,Vp,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:Np.optional().default("static").optional()});static z=ee.crudeZ.transform(e=>new ee(e));constructor(e){Yp(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=ks(),data:u}=e;if(Mo(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=Co(u),d=Array.isArray(u);if(n!=null)this.dataType=new R(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=R.STRING;else if(typeof f=="number")this.dataType=R.FLOAT64;else if(typeof f=="bigint")this.dataType=R.INT64;else if(typeof f=="boolean")this.dataType=R.BOOLEAN;else if(f instanceof p||f instanceof Date||f instanceof p)this.dataType=R.TIMESTAMP;else if(typeof f=="object")this.dataType=R.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new R(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 v=f[0];(v instanceof p||v instanceof Date||v instanceof S)&&(f=f.map($=>new p($).valueOf())),this.dataType.equals(R.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
8
+ `).map(c=>c.trim());if(r.length===0)return n!=null?n.parse({}):{};const a=r.split(",").map(c=>c.trim()),o={};return a.forEach(c=>{o[c]=[]}),s.forEach(c=>{const l=c.split(",").map(u=>u.trim());a.forEach((u,h)=>{const d=this.parseValue(l[h]);d!=null&&o[u].push(d)})}),n!=null?n.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const n=Number(e);return isNaN(n)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:n}}class Qa{contentType="text/plain";encode(e){if(typeof e!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(e)}decode(e,n){const r=new TextDecoder().decode(e);return n!=null?n.parse(r):r}}const Lt=new Ja,dd=new Xa,pd=new Qa,yd=[Lt],ot=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Xa,CSV_CODEC:dd,ENCODERS:yd,JSONCodec:Ja,JSON_CODEC:Lt,TEXT_CODEC:pd,TextCodec:Qa},Symbol.toStringTag,{value:"Module"})),re=t=>t!=null&&typeof t=="object"&&"value"in t;class ct{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const hs=t=>t!=null&&typeof t=="object"&&"toString"in t,eo=t=>{if(hs(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}},md=t=>!eo(t),gd=Object.freeze(Object.defineProperty({__proto__:null,ValueExtension:ct,isCrudeValueExtension:re,isNonZero:md,isStringer:hs,isZero:eo},Symbol.toStringTag,{value:"Module"})),xr=t=>[...new Set(t)],wd=(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())},Ei=Object.freeze(Object.defineProperty({__proto__:null,by:wd,unique:xr},Symbol.toStringTag,{value:"Module"})),Qt=(t,e=!1)=>{const n=hs(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?no(r):r},bd=(t,e,n)=>{const r=Qt(e[t],n);return(s,a)=>r(s[t],a[t])},vd=(t,e)=>t.length!==e.length?t.length-e.length:t.every((n,r)=>n===e[r])?0:-1,to=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const n=Qt(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=xr(t),r=xr(e);return to(n,r)},Td=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,no=t=>(e,n)=>t(n,e),ut=0,$e=-1,Ie=1,ro=t=>t<ut,so=t=>t>ut,Od=t=>t>=ut,io=t=>t===ut,Ed=(t,e)=>{const n=/([a-zA-Z]+)|(\d+)/g,r=t.replace(/[\s_.-]+/g,"").match(n),s=e.replace(/[\s_.-]+/g,"").match(n);if(!r||!s)return 0;for(let a=0;a<Math.min(r.length,s.length);a++){const o=r[a],c=s[a];if(isNaN(Number(o))&&isNaN(Number(c))){const l=o.localeCompare(c);if(l!==0)return l}else if(!isNaN(Number(o))&&!isNaN(Number(c))){const l=Number(o)-Number(c);if(l!==0)return l}else return isNaN(Number(o))?-1:1}return r.length-s.length},ao=(t,e,n)=>{let r=0,s=t.length;const a=n??Qt(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},Nd=(t,e,n)=>{const r=ao(t,e,n);t.splice(r,0,e)},Ni=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:ut,GREATER_THAN:Ie,LESS_THAN:$e,insert:Nd,isEqualTo:io,isGreaterThan:so,isGreaterThanEqual:Od,isLessThan:ro,newF:Qt,newFieldF:bd,order:Td,primitiveArrays:vd,reverseF:no,search:ao,stringsWithNumbers:Ed,uniqueUnorderedPrimitiveArrays:zd,unorderedPrimitiveArrays:to},Symbol.toStringTag,{value:"Module"}));let oo=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const co="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Sd=`0123456789${co}`,uo=11,kd=oo(co,1),Ad=oo(Sd,uo-1),fs=()=>`${kd()}${Ad()}`,lo=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:uo,create:fs},Symbol.toStringTag,{value:"Module"})),$d=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,Id=2**8-1,ho=2**12-1,Zd=2**16-1,xd=2**32-1,Cd=2n**64n-1n,Rd=2**64-1,_d=-128,Md=2**7-1,jd=-32768,Ud=2**15-1,Dd=-2147483648,Pd=2**31-1,Ld=-(2n**63n),kn=2n**63n-1n,Bd=-9223372036854776e3,fo=2**63-1,$t=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))},Ze=$t((t,e)=>t-e),xe=$t((t,e)=>t+e),qd=(t,e,n=1e-4)=>Math.abs(t-e)<n,Cr=(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},Fd=t=>{const e=10**Math.floor(Math.log10(t));return Math.round(t/e)*e},po=$t((t,e)=>t<=e?t:e),An=t=>typeof t=="bigint"?!0:Number.isInteger(t),Yd=$t((t,e)=>t>=e?t:e),yo=t=>typeof t=="bigint"?t<0n?-t:t:t<0?-t:t,de=$t((t,e)=>t*e),en=$t((t,e)=>t/e),mo=i.z.tuple([i.z.number(),i.z.number()]),go=i.z.object({width:i.z.number(),height:i.z.number()}),Gd=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),Vd=["start","center","end"],Nt=i.z.object({x:i.z.number(),y:i.z.number()}),wo=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),ds=["x","y"],bo=i.z.enum(ds),ps=["top","right","bottom","left"],Hd=i.z.enum(ps),vo=["left","right"],ys=i.z.enum(vo),ms=["top","bottom"],gs=i.z.enum(ms),ws=["center"],Rr=i.z.enum(ws),Wd=[...ps,...ws],bs=i.z.enum(Wd);i.z.enum(Vd);const Kd=["first","last"];i.z.enum(Kd);i.z.object({lower:i.z.number(),upper:i.z.number()});i.z.enum([...bo.options,...bs.options]);const Jd=i.z.union([bo,bs,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?Xd(r):r},Xd=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,Si=(t,e)=>{const n=K(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e},wn=(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},zo=t=>{const e=K(t);return e.upper-e.lower},Qd=t=>({lower:Math.min(...t.map(e=>K(e).lower)),upper:Math.max(...t.map(e=>K(e).upper))}),ep=(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(;Cr(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=Ze(l.upper,o):u=Ze(o,l.lower),u>0){const h=po(yo(a),u);if(o=xe(o,s>0?h:-h),a=Ze(a,s>0?h:-h),Cr(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},tp=(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,l=o.upper<s.upper?o.upper:s.upper;if(c<l){const u=l-c;a=a+u}}return a},_r=2,Mr=3,To=2,np=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=zo(e);if(n==0)return t;let r;n>=1e3?r=_r:n>=1?r=Mr:r=Math.ceil(-Math.log10(n))+To;const s=10**r;return Math.round(t*s)/s},rp=5,sp=1e-10,ip=(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=zo(e);const c=s/n;r=s>0&&c>sp}if(r){let c;s>=1e3?c=_r:s>=1?c=Mr:c=Math.ceil(-Math.log10(s))+To;const l=10**c;return Math.round(t*l)/l}if(n>=1e3){const c=10**_r;return Math.round(t*c)/c}if(n>=1){const c=10**Mr;return Math.round(t*c)/c}const a=Math.floor(Math.log10(n)),o=10**(rp-a-1);return Math.round(t*o)/o},jr=Object.freeze(Object.defineProperty({__proto__:null,MAX_INT16:Ud,MAX_INT32:Pd,MAX_INT64:kn,MAX_INT64_NUMBER:fo,MAX_INT8:Md,MAX_UINT12:ho,MAX_UINT16:Zd,MAX_UINT32:xd,MAX_UINT64:Cd,MAX_UINT64_NUMBER:Rd,MAX_UINT8:Id,MIN_INT16:jd,MIN_INT32:Dd,MIN_INT64:Ld,MIN_INT64_NUMBER:Bd,MIN_INT8:_d,abs:yo,add:xe,closeTo:qd,div:en,equal:Cr,isInteger:An,max:Yd,min:po,mult:de,roundBySpan:np,roundToNearestMagnitude:Fd,smartRound:ip,sub:Ze},Symbol.toStringTag,{value:"Module"})),ap=t=>ds.includes(t)?t:ms.includes(t)?"y":"x",op=ys,cp=gs,up=Rr,lp={top:"bottom",right:"left",bottom:"top",left:"right",center:"center"},hp={top:{clockwise:"left",counterclockwise:"right"},right:{clockwise:"top",counterclockwise:"bottom"},bottom:{clockwise:"right",counterclockwise:"left"},left:{clockwise:"bottom",counterclockwise:"top"}},fp=Jd,rt=t=>t instanceof String||!ds.includes(t)?t:t==="x"?"left":"top",dp=t=>lp[rt(t)],pp=(t,e)=>hp[t][e],Bt=t=>{const e=rt(t);return e==="top"||e==="bottom"?"y":"x"},yp=i.z.object({x:ys.or(Rr),y:gs.or(Rr)}),vs=i.z.object({x:ys,y:gs}),zs=Object.freeze({x:"left",y:"top"}),Oo=Object.freeze({x:"right",y:"top"}),Eo=Object.freeze({x:"left",y:"bottom"}),No=Object.freeze({x:"right",y:"bottom"}),Ts=Object.freeze({x:"center",y:"center"}),So=Object.freeze({x:"center",y:"top"}),ko=Object.freeze({x:"center",y:"bottom"}),Ao=Object.freeze({x:"right",y:"center"}),$o=Object.freeze({x:"left",y:"center"}),mp=Object.freeze([$o,Ao,So,ko,zs,Oo,Eo,No,Ts]),Io=(t,e)=>t.x===e.x&&t.y===e.y,gp=(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},wp=t=>[t.x,t.y],Sn=t=>Bt(rt(t))==="x",bp=t=>Bt(rt(t))==="y",vp=t=>`${t.x}${Ka(t.y)}`,zp=(t,e)=>{let n,r;if(typeof t=="object"&&"x"in t?(n=t.x,r=t.y):(n=rt(t),r=rt(e??t)),Bt(n)===Bt(r)&&n!=="center"&&r!=="center")throw new Error(`[XYLocation] - encountered two locations with the same direction: ${n.toString()} - ${r.toString()}`);const s={...Ts};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},Tp=Object.freeze(Object.defineProperty({__proto__:null,BOTTOM_CENTER:ko,BOTTOM_LEFT:Eo,BOTTOM_RIGHT:No,CENTER:Ts,CENTER_LEFT:$o,CENTER_LOCATIONS:ws,CENTER_RIGHT:Ao,OUTER_LOCATIONS:ps,TOP_CENTER:So,TOP_LEFT:zs,TOP_RIGHT:Oo,XY_LOCATIONS:mp,X_LOCATIONS:vo,Y_LOCATIONS:ms,center:up,construct:rt,constructXY:zp,corner:vs,crude:fp,direction:Bt,isX:Sn,isY:bp,location:bs,outer:Hd,rotate:pp,swap:dp,x:op,xy:yp,xyCouple:wp,xyEquals:Io,xyMatches:gp,xyToString:vp,y:cp},Symbol.toStringTag,{value:"Module"})),Ur=i.z.union([i.z.number(),Nt,mo,go,Gd,wo]),M=(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}},st=Object.freeze({x:0,y:0}),Op=Object.freeze({x:1,y:1}),Ep=Object.freeze({x:1/0,y:1/0}),Np=Object.freeze({x:NaN,y:NaN}),Zo=(t,e,n=0)=>{const r=M(t),s=M(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},Sp=t=>Zo(t,st),Os=(t,e,n)=>{const r=M(t),s=M(e,n);return{x:r.x*s.x,y:r.y*s.y}},xo=(t,e)=>{const n=M(t);return{x:n.x+e,y:n.y}},Co=(t,e)=>{const n=M(t);return{x:n.x,y:n.y+e}},Ro=(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):Co(t,n)}if(typeof e=="object"&&"x"in e&&typeof e.x=="string"){const s=M(n),a=M(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??st,...r].reduce((s,a)=>{const o=M(a);return{x:s.x+o.x,y:s.y+o.y}},st)},kp=(t,e,n)=>{const r=M(t);return ap(e)==="x"?{x:n,y:r.y}:{x:r.x,y:n}},Ap=(t,e)=>{const n=M(t),r=M(e);return Math.sqrt((n.x-r.x)**2+(n.y-r.y)**2)},$p=(t,e)=>{const n=M(t),r=M(e);return{x:r.x-n.x,y:r.y-n.y}},Ip=t=>{const e=M(t);return Number.isNaN(e.x)||Number.isNaN(e.y)},Zp=t=>{const e=M(t);return Number.isFinite(e.x)&&Number.isFinite(e.y)},xp=t=>{const e=M(t);return[e.x,e.y]},Cp=t=>{const e=M(t);return{left:e.x,top:e.y}},Rp=(t,e=0)=>{const n=M(t);return{x:Number(n.x.toFixed(e)),y:Number(n.y.toFixed(e))}},Mt=(t,e)=>{const n=M(t),r=M(e);return{x:n.x-r.x,y:n.y-r.y}},jt=t=>{const e=M(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:-e.y/n,y:e.x/n}},_o=t=>{const e=M(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:e.x/n,y:e.y/n}},Mo=(...t)=>{const e=t.reduce((n,r)=>Ro(n,r),st);return Os(e,1/t.length)},_p=(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=Mt(u,s);o=jt(h),c=o,l=e}else if(r===t.length-1){const u=t[r-1],h=Mt(s,u);a=jt(h),c=a,l=e}else{const u=t[r-1],h=t[r+1],d=Mt(s,u),f=Mt(h,s);a=jt(d),o=jt(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=_o(Mo(a,o))}n.push(Os(c,l))}return n},Mp=t=>{const e=M(t);return{x:e.y,y:e.x}},jp=t=>{const e=M(t);return{x:Math.round(e.x),y:Math.round(e.y)}},Up=t=>{const e=M(t);return{x:1/e.x,y:1/e.y}},Dp=(t,e,n)=>{const r=M(t),s=M(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}},Es=Object.freeze(Object.defineProperty({__proto__:null,INFINITY:Ep,NAN:Np,ONE:Op,ZERO:st,average:Mo,calculateMiters:_p,clientXY:wo,construct:M,couple:xp,crudeZ:Ur,css:Cp,distance:Ap,equals:Zo,isFinite:Zp,isNan:Ip,isZero:Sp,normal:jt,normalize:_o,reciprocal:Up,rotate:Dp,round:jp,scale:Os,set:kp,sub:Mt,swap:Mp,translate:Ro,translateX:xo,translateY:Co,translation:$p,truncate:Rp,xy:Nt},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:Nt,two:Nt,root:vs});const Ns=(t,e,n=0,r=0,s)=>{const a={one:{...st},two:{...st},root:s??zs};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:t,y:e},a.two={x:a.one.x+n,y:a.one.y+r},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(a.one={x:t.left,y:t.top},a.two={x:t.right,y:t.bottom},a):(a.one=t,e==null?a.two={x:a.one.x+n,y:a.one.y+r}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+n}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},ur=t=>{const e=Ns(t);return{lower:e.one.x,upper:e.two.x}},lr=t=>{const e=Ns(t);return{lower:e.one.y,upper:e.two.y}},Pp=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,Lp=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([go,Lp,Nt,mo]);const Bp=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:Ur,scale:Ur});i.z.object({offset:i.z.number(),scale:i.z.number()});const qp=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],Fp=t=>(e,n,r,s)=>[e,s?r/t:r*t],Yp=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]},Gp=t=>(e,n,r)=>[t,r],Vp=()=>(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)]},Hp=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=Bp(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=qp(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=Fp(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=K(e,n),s=this.new(),a=Yp(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=K(e,n),s=this.new(),a=Hp(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=K(e,n),s=this.new(),a=Gp(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Vp();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=M(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(Pp(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!Io(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(ur(e)),n.y=n.y.scale(lr(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(ur(e)),n.y=this.y.reBound(lr(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(ur(e)),n.y=this.y.clamp(lr(e)),n}copy(){const e=new 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 Ns(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 Wp=Nt.extend({root:vs,units:i.object({x:i.enum(["px","decimal"]),y:i.enum(["px","decimal"])})});Wp.partial({root:!0,units:!0});const Kp=i.z.enum(["static","dynamic"]),ki=365,vn=30,Jp=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)])]),jo=(t,e)=>{const n=new m(e);if(![g.DAY,g.HOUR,g.MINUTE,g.SECOND,g.MILLISECOND,g.MICROSECOND,g.NANOSECOND].some(s=>s.equals(n)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=t.valueOf()%n.valueOf();return t instanceof m?new m(r):new g(r)};class m extends ct{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===fo?e=kn:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=m.MAX:e=m.MIN)),re(e)&&(e=e.value),super(BigInt(e.valueOf())+r)}}static parseDate([e=1970,n=1,r=1]){const s=new Date(e,n-1,r,0,0,0,0);return new m(BigInt(s.getTime())*m.MILLISECOND.valueOf()).truncate(m.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let l=m.hours(parseInt(r??"00")).add(m.minutes(parseInt(s??"00"))).add(m.seconds(parseInt(o??"00"))).add(m.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(m.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return m.parseTimeString(e,n);if(e.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let s=e,a=0;if(e.includes(".")){const u=e.split(".");s=u[0];const h=u[1]||"0";a=parseInt(h.padEnd(3,"0").slice(0,3))}const o=n==="local"?new Date(s.replace("T"," ")):new Date(`${s}Z`),c=BigInt(o.getTime())*m.MILLISECOND.valueOf(),l=BigInt(a)*m.MILLISECOND.valueOf();return c+l}const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new m(BigInt(r.getTime())*m.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(m.utcOffset).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new g(BigInt(new Date().getTimezoneOffset())*m.MINUTE.valueOf())}static since(e){return new m().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new m(e).valueOf()}span(e){return this.range(e).span}range(e){return new 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(xe(this.valueOf(),new g(e).valueOf()))}sub(e){return new m(Ze(this.valueOf(),new g(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(g.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(g.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(g.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(g.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(m.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(m.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new m(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new m(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new m(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new m(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new m(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new m(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new m(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new m(n)}toString(e="ISO",n="UTC"){switch(e){case"ISODate":return this.toISOString(n).slice(0,10);case"ISOTime":return this.toISOString(n).slice(11,23);case"time":return this.timeString(!1,n);case"preciseTime":return this.timeString(!0,n);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,n)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,n)}`;default:return this.toISOString(n)}}remainder(e){return jo(this,e)}get isToday(){return this.truncate(g.DAY).equals(m.now().truncate(g.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(g.days(30))?"shortDate":e.greaterThanOrEqual(g.DAY)?"dateTime":e.greaterThanOrEqual(g.HOUR)?"time":e.greaterThanOrEqual(g.SECOND)?"preciseTime":"ISOTime"}static now(){return new m(new Date)}static max(...e){let n=m.MIN;for(const r of e){const s=new m(r);s.after(n)&&(n=s)}return n}static min(...e){let n=m.MAX;for(const r of e){const s=new m(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new m(e,n)}static NANOSECOND=m.nanoseconds(1);static microseconds(e,n="UTC"){return m.nanoseconds(e*1e3,n)}static MICROSECOND=m.microseconds(1);static milliseconds(e,n="UTC"){return m.microseconds(e*1e3,n)}static MILLISECOND=m.milliseconds(1);static seconds(e,n="UTC"){return m.milliseconds(e*1e3,n)}static SECOND=m.seconds(1);static minutes(e,n="UTC"){return m.seconds(e*60,n)}static MINUTE=m.minutes(1);static hours(e,n="UTC"){return m.minutes(e*60,n)}static HOUR=m.hours(1);static days(e,n="UTC"){return m.hours(e*24,n)}static DAY=m.days(1);static MAX=new m(kn);static MIN=new m(0);static ZERO=new m(0);static z=i.z.union([i.z.instanceof(m),i.z.object({value:i.z.bigint()}).transform(e=>new m(e.value)),i.z.string().transform(e=>new m(BigInt(e))),i.z.number().transform(e=>new m(e)),i.z.bigint().transform(e=>new m(e)),i.z.date().transform(e=>new m(e)),i.z.custom(e=>e instanceof g).transform(e=>new m(e)),Jp.transform(e=>new m(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}}class g extends ct{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),re(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof g?e:e instanceof G?e.period:e instanceof m?new g(e):(re(e)&&(e=e.value),["number","bigint"].includes(typeof e)?g.seconds(e):new g(e))}static fromMilliseconds(e){return e instanceof g?e:e instanceof G?e.period:e instanceof m?new g(e):(re(e)&&(e=e.value),["number","bigint"].includes(typeof e)?g.milliseconds(e):new g(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new g(e).valueOf()}greaterThan(e){return this.valueOf()>new g(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new g(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new g(e).valueOf()}remainder(e){return jo(this,e)}truncate(e){return new g(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(g.DAY),r=this.truncate(g.HOUR),s=this.truncate(g.MINUTE),a=this.truncate(g.SECOND),o=this.truncate(g.MILLISECOND),c=this.truncate(g.MICROSECOND),l=this.truncate(g.NANOSECOND),u=n,h=r.sub(n),d=s.sub(r),f=a.sub(s),O=o.sub(a),S=c.sub(o),Z=l.sub(c);let z="";return u.isZero||(z+=`${u.days}d `),h.isZero||(z+=`${h.hours}h `),d.isZero||(z+=`${d.minutes}m `),f.isZero||(z+=`${f.seconds}s `),O.isZero||(z+=`${O.milliseconds}ms `),S.isZero||(z+=`${S.microseconds}µs `),Z.isZero||(z+=`${Z.nanoseconds}ns`),z.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new g(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(g.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/ki),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 z=`${l}y`;if(l<2){const E=Math.floor(s%ki/vn);E>0&&(z+=` ${E}mo`)}return Z+z}if(h>=1&&s<vn&&s%7===0){let z=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?z+=` ${E}d`:A>0&&A<24&&(z+=` ${A}h`)),Z+z}if(u>=1){let z=`${u}mo`;if(u<3){const E=Math.floor(s%vn);E>0&&(z+=` ${E}d`)}return Z+z}if(h>=1){let z=`${h}w`;const E=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(E>0?z+=` ${E}d`:A>0&&A<24&&(z+=` ${A}h`)),Z+z}if(d>=1){let z=`${d}d`;const E=Math.floor(a-d*24);return d<2&&E>0&&(z+=` ${E}h`),Z+z}if(f>=1){let z=`${f}h`;if(f<3){const E=Math.floor(o-f*60);E>0&&(z+=` ${E}m`)}return Z+z}if(O>=1){let z=`${O}m`;if(O<5){const E=Math.floor(c-O*60);E>0&&(z+=` ${E}s`)}return Z+z}return`${Z}${S}s`}mult(e){return new g(de(this.valueOf(),e))}div(e){return new g(en(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(g.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(g.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(g.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(g.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(g.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(g.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new g(e).valueOf()}add(e){return new g(this.valueOf()+new g(e).valueOf())}sub(e){return new g(this.valueOf()-new g(e).valueOf())}static nanoseconds(e=1){return new g(e)}static NANOSECOND=g.nanoseconds(1);static microseconds(e=1){return g.nanoseconds(de(e,1e3))}static MICROSECOND=g.microseconds(1);static milliseconds(e=1){return g.microseconds(de(e,1e3))}static MILLISECOND=g.milliseconds(1);static seconds(e=1){return g.milliseconds(de(e,1e3))}static SECOND=g.seconds(1);static minutes(e=1){return g.seconds(de(e,60))}static MINUTE=g.minutes(1);static hours(e){return g.minutes(de(e,60))}static HOUR=g.hours(1);static days(e){return g.hours(de(e,24))}static DAY=g.days(1);static MAX=new g(kn);static MIN=new g(0);static ZERO=new g(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new g(e.value)),i.z.string().transform(e=>new g(BigInt(e))),i.z.number().transform(e=>new g(e)),i.z.bigint().transform(e=>new g(e)),i.z.instanceof(g),i.z.instanceof(m).transform(e=>new g(e)),i.z.custom(e=>e instanceof G).transform(e=>new g(e))])}class G extends ct{constructor(e){re(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new G(e).valueOf()}get period(){return g.seconds(1/this.valueOf())}sampleCount(e){return new g(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new C(n).valueOf()}span(e){return g.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new C(n).valueOf())}add(e){return new G(xe(this.valueOf(),new G(e).valueOf()))}sub(e){return new G(Ze(this.valueOf(),new G(e).valueOf()))}mult(e){return new G(de(this.valueOf(),e))}div(e){return new G(en(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 ct{constructor(e){re(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(xe(this.valueOf(),new C(e).valueOf()))}sub(e){return new C(Ze(this.valueOf(),new C(e).valueOf()))}mult(e){return new C(de(this.valueOf(),e))}div(e){return new C(en(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 m(e.start),this.end=new m(e.end)):(this.start=new m(e),this.end=new m(n))}get span(){return new g(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new x(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=g.ZERO){if(n.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return r<0&&(r=-r),s<0&&(s=-s),r<=n.valueOf()&&s<=n.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,n=g.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const s=m.max(r.start,e.start),a=m.min(r.end,e.end);return a.before(s)?!1:new g(a.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof 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 simplify(e){return e.map(n=>n.makeValid()).sort((n,r)=>x.sort(n,r)).reduce((n,r)=>{if(r.span.isZero)return n;if(n.length===0)return n.push(r),n;const s=n[n.length-1];return s.overlapsWith(r)||s.end.equals(r.start)?s.end=m.max(s.end,r.end):n.push(r),n},[])}}class p extends ct{constructor(e){if(re(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(),C.BIT8],[p.UINT16.toString(),C.BIT16],[p.UINT32.toString(),C.BIT32],[p.UINT64.toString(),C.BIT64],[p.FLOAT32.toString(),C.BIT32],[p.FLOAT64.toString(),C.BIT64],[p.INT8.toString(),C.BIT8],[p.INT16.toString(),C.BIT16],[p.INT32.toString(),C.BIT32],[p.INT64.toString(),C.BIT64],[p.TIMESTAMP.toString(),C.BIT64],[p.STRING.toString(),C.UNKNOWN],[p.JSON.toString(),C.UNKNOWN],[p.UUID.toString(),C.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 $ extends ct{constructor(e){re(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return re(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return re(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return re(e)&&(e=e.value),new $(xe(this.valueOf(),e.valueOf()))}sub(e){return re(e)&&(e=e.value),new $(Ze(this.valueOf(),e.valueOf()))}mult(e){return new $(de(this.valueOf(),e))}div(e){return new $(en(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 Uo=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof m||t instanceof g||t instanceof Date},Xp=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Ze(n,r),Qp=/^(?:[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 ey(t){return typeof t=="string"&&Qp.test(t)}const Q=[];for(let t=0;t<256;++t)Q.push((t+256).toString(16).slice(1));function ty(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 ny(t,e=0){const n=ty(t,e);if(!ey(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Do=(t,e)=>ny(t,e),Ue=-1,Dr={[Symbol.iterator]:()=>Dr,next:()=>({done:!0,value:void 0})},ry=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),sy=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Pr=10,Po=(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`)},Lo="sy_x_telem_series";class ee{key;discriminator=Lo;dataType;sampleOffset;gl;_data;timeRange=x.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Ue;_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([ry,sy,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:Kp.default("static").optional()});static z=ee.crudeZ.transform(e=>new ee(e));constructor(e){iy(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=fs(),data:u}=e;if(Bo(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=Uo(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 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(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 m||O instanceof Date||O instanceof g)&&(f=f.map(S=>new m(S).valueOf())),this.dataType.equals(p.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
9
9
  `)}
10
- `).buffer):this.dataType.equals(R.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map($=>Ft.encodeString($)).join(`
10
+ `).buffer):this.dataType.equals(p.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(S=>Lt.encodeString(S)).join(`
11
11
  `)}
12
- `).buffer):this.dataType.usesBigInt&&typeof v=="number"?this._data=new this.dataType.Array(f.map($=>BigInt(Math.round($)))).buffer:!this.dataType.usesBigInt&&typeof v=="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??P.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 R(n).Array(e),a=new ee({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(R.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 Ot(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 Ot(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===Gr&&(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]=Pp(this.dataType,e,this.data[s],n);return new ee({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(R.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(),Zn(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(R.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((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(),Zn(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(R.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 Zn(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=Ro(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]===Gr){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(R.STRING)?new TextDecoder().decode(a):bs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=rn(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(R.FLOAT32)&&!this.dataType.equals(R.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 _o(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Ni(this.alignmentBounds.lower),upper:Ni(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 Hp(this);return this.dataType.equals(R.JSON)?new Wp(e):e}return this.dataType.equals(R.UUID)?new Gp(this):new Kp(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new Ei(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 Ei(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 ee({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 ee({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new ee({data:this.buffer,dataType:this.dataType,timeRange:P.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 Yp=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof ee?!0:Co(t),Mo=Ep(jo,ee);class Ei{series;end;index;constructor(e,n,r){this.series=e;const s=K(0,e.length+1);this.end=vi(s,r),this.index=vi(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}let Hp=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]!==Gr;)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))})}},Wp=class Do{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,Do.schema)}}};class Gp{series;index;data;density;constructor(e){if(!e.dataType.equals(R.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=R.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Ro(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let Kp=class{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 Po{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 _o(e,this.dataType),this}get dataType(){return this.series.length===0?R.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?P.ZERO:new P(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(Mo(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(zn(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 Er(this,e,n??this.length)}subAlignmentIterator(e,n){if(e>=this.alignmentBounds.upper||n<=this.alignmentBounds.lower)return Wr;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(zn(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(zn(o.alignmentBounds,n)){s+=Math.ceil(Number(n-o.alignment)/Number(o.alignmentMultiple));break}}return new Er(this,r,s)}subAlignmentSpanIterator(e,n){if(e>=this.alignmentBounds.upper)return Wr;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(zn(a.alignmentBounds,e)){r+=Number(e-a.alignment);break}}return new Er(this,r,r+n)}updateGLBuffer(e){this.series.forEach(n=>n.updateGLBuffer(e))}get bounds(){return Ad(this.series.map(e=>e.bounds))}get byteLength(){return new Ot(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 kd(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 xd(r,e,n)}parseJSON(e){if(!this.dataType.equals(R.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 Jp(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}}let Jp=class{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}},Er=class{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 Ni=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},Uo=(t,e,n)=>{let r=0,s=t.length;const a=n??rn(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},Xp=(t,e,n)=>{const r=Uo(t,e,n);t.splice(r,0,e)},Oi=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:at,GREATER_THAN:Ce,LESS_THAN:Ze,insert:Xp,isEqualTo:no,isGreaterThan:to,isGreaterThanEqual:dd,isLessThan:eo,newF:rn,newFieldF:ud,order:fd,primitiveArrays:ld,reverseF:Qa,search:Uo,stringsWithNumbers:pd,uniqueUnorderedPrimitiveArrays:hd,unorderedPrimitiveArrays:Xa},Symbol.toStringTag,{value:"Module"})),Qp=(t,e)=>{let n=null;return e===0?t:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>t(...r),e)}},ey=(t,e,n=".")=>{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)},ty=(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)},ny=((t,e,n={optional:!1})=>{const{optional:r,getter:s=ty}=n;if(e==="")return t;const a=e.split(".");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("."),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)});i.z.object({key:i.z.string(),value:i.z.string()});let ry=class{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?.()}},sy=class{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 iy=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:sy,Observer:ry},Symbol.toStringTag,{value:"Module"})),ay=i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown()),xs=t=>Object.entries(t),oy=(t,e)=>Object.fromEntries(xs(t).map(([n,r])=>[n,e(r,n)])),cy=t=>Object.fromEntries(xs(t).filter(([e,n])=>n!==void 0)),uy=(t,...e)=>{const n={...t};for(const r of e)delete n[r];return n},ve=Object.freeze(Object.defineProperty({__proto__:null,entries:xs,map:oy,omit:uy,purgeUndefined:cy,unknownZ:ay},Symbol.toStringTag,{value:"Module"})),ly=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";ly();const hy=["macOS","Windows","Linux"],fy=["macos","windows","linux"],dy={macos:"macOS",windows:"Windows",linux:"Linux"};i.z.enum(hy).or(i.z.enum(fy).transform(t=>dy[t]));const py=(...t)=>t.map(Lo).join(""),Lo=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),yy=t=>t.endsWith("/")?t.slice(0,-1):t;class vt{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=Lo(s)}replace(e){return new vt({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new vt({...this,pathPrefix:py(this.path,e)})}toString(){return yy(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new vt({host:"unknown",port:0})}const my=t=>t.nullable().transform(e=>e===null?void 0:e).optional(),gy=t=>i.array(t).or(t.transform(e=>[e])),Bo=t=>ey(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"]}),$i=(t,e)=>{if(t==null)return null;const n=t[e];return n==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:n},wy=((t,e,n)=>e===""?t:ny($i(t,"shape"),Bo(e),{...n,getter:$i})),qt=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:wy,getFieldSchemaPath:Bo,nullToUndefined:my,toArray:gy},Symbol.toStringTag,{value:"Module"})),Kr=2,Jr=3,qo=2,by=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=ho(e);if(n==0)return t;let r;n>=1e3?r=Kr:n>=1?r=Jr:r=Math.ceil(-Math.log10(n))+qo;const s=10**r;return Math.round(t*s)/s},vy=5,Ty=1e-10,zy=(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=ho(e);const c=s/n;r=s>0&&c>Ty}if(r){let c;s>=1e3?c=Kr:s>=1?c=Jr:c=Math.ceil(-Math.log10(s))+qo;const l=10**c;return Math.round(t*l)/l}if(n>=1e3){const c=10**Kr;return Math.round(t*c)/c}if(n>=1){const c=10**Jr;return Math.round(t*c)/c}const a=Math.floor(Math.log10(n)),o=10**(vy-a-1);return Math.round(t*o)/o},Xr=Object.freeze(Object.defineProperty({__proto__:null,MAX_INT16:Cp,MAX_INT32:_p,MAX_INT64:_n,MAX_INT64_NUMBER:xo,MAX_INT8:xp,MAX_UINT16:$p,MAX_UINT32:Sp,MAX_UINT64:Ip,MAX_UINT64_NUMBER:Ap,MAX_UINT8:Op,MIN_INT16:Zp,MIN_INT32:Rp,MIN_INT64:jp,MIN_INT64_NUMBER:Mp,MIN_INT8:kp,abs:lo,add:xt,closeTo:Od,div:sn,equal:Yr,isInteger:Rn,max:Sd,min:uo,mult:ge,roundBySpan:by,roundToNearestMagnitude:$d,smartRound:zy,sub:Be},Symbol.toStringTag,{value:"Module"})),Ey=async t=>await new Promise(e=>setTimeout(e,S.fromMilliseconds(t).milliseconds));class Ny{config;retries;interval;constructor(e){this.config={baseInterval:new S(e?.baseInterval??S.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Ey},this.retries=0,this.interval=new S(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 Oy=i.z.object({baseInterval:S.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),Zs=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Ny,breakerConfigZ:Oy},Symbol.toStringTag,{value:"Module"})),$y=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Fo=i.z.string().regex($y),Tt=i.z.number().min(0).max(255),Vo=i.z.number().min(0).max(1),Yo=i.z.tuple([Tt,Tt,Tt,Vo]),Sy=i.z.tuple([Tt,Tt,Tt]),Iy=i.z.object({rgba255:Yo}),Ay=i.z.number().min(0).max(360),ky=i.z.number().min(0).max(100),xy=i.z.number().min(0).max(100),Zy=i.z.tuple([Ay,ky,xy,Vo]),Cs=i.z.union([Fo,Sy,Yo,Zy,Iy]),Cy=Cs.transform(t=>Rs(t)),Rs=(t,e=1)=>{if(t=Cs.parse(t),typeof t=="string")return Ry(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},Ry=(t,e=1)=>(t=Fo.parse(t),t=_y(t),[On(t,0),On(t,2),On(t,4),t.length===8?On(t,6)/255:e]),On=(t,e)=>parseInt(t.slice(e,e+2),16),_y=t=>t.startsWith("#")?t.slice(1):t;Rs("#000000");Rs("#ffffff");const jy=i.z.object({key:i.z.string(),color:Cs,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(jy);const My=i.z.object({key:i.z.string(),name:i.z.string(),color:Cy});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(My)});const Ho=i.z.int().min(0).max(255),Wo=255,Go=0,Dy={lower:Go,upper:Wo+1},Ko=i.z.object({name:i.z.string(),key:i.z.string()}),Ht=t=>i.z.object({subject:Ko,resource:t,authority:Ho}),Py=(...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}),Jo=t=>i.z.object({from:Ht(t),to:i.z.null()}),Xo=t=>i.z.object({from:i.z.null(),to:Ht(t)}),Uy=t=>i.z.union([Jo(t),Xo(t),i.z.object({from:Ht(t),to:Ht(t)})]),de=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:Wo,AUTHORITY_BOUNDS:Dy,ZERO_AUTHORITY:Go,acquireZ:Xo,authorityZ:Ho,filterTransfersByChannelKey:Py,releaseZ:Jo,stateZ:Ht,subjectZ:Ko,transferZ:Uy},Symbol.toStringTag,{value:"Module"})),Ly=t=>Object.getOwnPropertySymbols(globalThis).includes(t),By=(t,e)=>{const n=Symbol.for(t);if(!Ly(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},Qo="sy_x_error",qy=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),an=t=>class Lt extends Error{static discriminator=Qo;discriminator=Lt.discriminator;static TYPE=t;type=Lt.TYPE;static matches=qy(t);matches=Lt.matches;constructor(n,r){super(n,r),this.name=Lt.TYPE}static sub(n){return an(`${t}.${n}`)}},ec=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Qo)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},mt="unknown",Qr="nil";class Fy{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Qr,data:""};if(ec(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:mt,data:e.message};if(typeof e=="string")return{type:mt,data:e};try{return{type:mt,data:JSON.stringify(e)}}catch{return{type:mt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Qr)return null;if(e.type===mt)return new es(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new es(e.data)}}const _s=By("synnax-error-registry",()=>new Fy),Vy=({encode:t,decode:e})=>_s().register({encode:t,decode:e}),Yy=t=>_s().encode(t),Hy=t=>t==null?null:_s().decode(t);class es extends an("unknown"){}const Wy=i.z.object({type:i.z.string(),data:i.z.string()});class Gy extends an("canceled"){}class Ky extends an("not_implemented"){}const _e=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Gy,NONE:Qr,NotImplemented:Ky,UNKNOWN:mt,Unknown:es,createTyped:an,decode:Hy,encode:Yy,isTyped:ec,payloadZ:Wy,register:Vy},Symbol.toStringTag,{value:"Module"})),Jy=i.object({jsonrpc:i.literal("2.0"),method:i.string(),params:i.any().optional(),id:i.union([i.string(),i.number(),i.null()]).optional()}),tc=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()])}),Xy=tc.extend({result:i.json()}),Qy=tc.extend({error:i.object({code:i.number().int(),message:i.string().optional(),data:i.json().optional()})}),em=i.union([Xy,Qy]);i.union([Jy,em]);const nc=i.uuid(),rc=i.object({key:nc,name:i.string().min(1),color:i.string()}),sc=Object.freeze(Object.defineProperty({__proto__:null,keyZ:nc,labelZ:rc},Symbol.toStringTag,{value:"Module"})),ts=i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/),tm=(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 Ce;const l=/^\d+$/.test(o),u=/^\d+$/.test(c);if(l&&!u)return Ze;if(!l&&u)return Ce;if(l&&u){const h=parseInt(o),d=parseInt(c);if(h<d)return Ze;if(h>d)return Ce}else{if(o<c)return Ze;if(o>c)return Ce}}return at},on=((t,e,n={})=>{n.checkMajor??=!0,n.checkMinor??=!0,n.checkPatch??=!0;const r=ts.parse(t),s=ts.parse(e),[a,o]=r.split("-"),[c,l]=s.split("-"),[u,h,d]=a.split(".").map(Number),[f,v,$]=c.split(".").map(Number);if(n.checkMajor){if(u<f)return Ze;if(u>f)return Ce}if(n.checkMinor){if(h<v)return Ze;if(h>v)return Ce}if(n.checkPatch){if(d<$)return Ze;if(d>$)return Ce}return o===void 0&&l===void 0?at:o===void 0?Ce:l===void 0?Ze:tm(o,l)}),nm=(t,e,n={})=>no(on(t,e,n)),ic=(t,e,n={})=>to(on(t,e,n)),rm=(t,e,n={})=>eo(on(t,e,n)),sm=({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}},im=({name:t,migrations:e,targetSchema:n,defaultVersion:r,def:s})=>{const a=Object.keys(e).sort(on).pop();if(a==null)return u=>{if(u.version??=r,u.version!==s.version)return console.log(`${t} version ${u.version} is newer than latest version of ${s.version}.
12
+ `).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(f.map(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 p(n).Array(e),a=new ee({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(`
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(Lt.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===Ue?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===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===Pr&&(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]=Xp(this.dataType,e,this.data[s],n);return new ee({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(),xe(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(),xe(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 xe(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=Do(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]===Pr){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):ls(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=Qt(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 Po(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:$i(this.alignmentBounds.lower),upper:$i(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 ay(this);return this.dataType.equals(p.JSON)?new Ss(e):e}return this.dataType.equals(p.UUID)?new oy(this):new cy(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new Ai(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 Ai(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 ee({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 ee({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new ee({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 iy=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof ee?!0:Uo(t),Bo=$d(Lo,ee);class Ai{series;end;index;constructor(e,n,r){this.series=e;const s=K(0,e.length+1);this.end=Si(s,r),this.index=Si(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class ay{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]!==Pr;)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 Ss{wrapped;static schema=i.z.record(i.z.string(),i.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Lt.decodeString(e.value,Ss.schema)}}}class oy{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=Do(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}class cy{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 qo{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 Po(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(Bo(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 hr(this,e,n??this.length)}subAlignmentIterator(e,n){if(e>=this.alignmentBounds.upper||n<=this.alignmentBounds.lower)return Dr;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 hr(this,r,s)}subAlignmentSpanIterator(e,n){if(e>=this.alignmentBounds.upper)return Dr;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 hr(this,r,r+n)}updateGLBuffer(e){this.series.forEach(n=>n.updateGLBuffer(e))}get bounds(){return Qd(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 ep(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 tp(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 uy(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}}class uy{series;seriesIndex;internal;constructor(e){this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[Symbol.iterator](){return this}}class hr{series;index;end;constructor(e,n,r){this.series=e,this.end=r,this.index=n}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}const $i=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},ly=async t=>await new Promise(e=>setTimeout(e,g.fromMilliseconds(t).milliseconds));class hy{config;retries;interval;constructor(e){this.config={baseInterval:new g(e?.baseInterval??g.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??ly},this.retries=0,this.interval=new g(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:n,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(n),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const fy=i.z.object({baseInterval:g.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),ks=Object.freeze(Object.defineProperty({__proto__:null,Breaker:hy,breakerConfigZ:fy},Symbol.toStringTag,{value:"Module"})),dy=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Fo=i.z.string().regex(dy),zt=i.z.number().min(0).max(255),Yo=i.z.number().min(0).max(1),Go=i.z.tuple([zt,zt,zt,Yo]),py=i.z.tuple([zt,zt,zt]),yy=i.z.object({rgba255:Go}),my=i.z.number().min(0).max(360),gy=i.z.number().min(0).max(100),wy=i.z.number().min(0).max(100),by=i.z.tuple([my,gy,wy,Yo]),As=i.z.union([Fo,py,Go,by,yy]),vy=As.transform(t=>$s(t)),$s=(t,e=1)=>{if(t=As.parse(t),typeof t=="string")return zy(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},zy=(t,e=1)=>(t=Fo.parse(t),t=Ty(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),Ty=t=>t.startsWith("#")?t.slice(1):t;$s("#000000");$s("#ffffff");const Oy=i.z.object({key:i.z.string(),color:As,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(Oy);const Ey=i.z.object({key:i.z.string(),name:i.z.string(),color:vy});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(Ey)});const Vo=i.z.int().min(0).max(255),Ho=255,Wo=0,Ny={lower:Wo,upper:Ho+1},Ko=i.z.object({name:i.z.string(),key:i.z.string()}),qt=t=>i.z.object({subject:Ko,resource:t,authority:Vo}),Sy=(...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}),Jo=t=>i.z.object({from:qt(t),to:i.z.null()}),Xo=t=>i.z.object({from:i.z.null(),to:qt(t)}),ky=t=>i.z.union([Jo(t),Xo(t),i.z.object({from:qt(t),to:qt(t)})]),ue=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:Ho,AUTHORITY_BOUNDS:Ny,ZERO_AUTHORITY:Wo,acquireZ:Xo,authorityZ:Vo,filterTransfersByChannelKey:Sy,releaseZ:Jo,stateZ:qt,subjectZ:Ko,transferZ:ky},Symbol.toStringTag,{value:"Module"})),Ay=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 Ii(t.toString());case"object":return t==null?"":Ii(JSON.stringify(t))}},$y=/[",\n]/,Ii=t=>$y.test(t)?`"${t.replace(/"/g,'""')}"`:t,Zi=Object.freeze(Object.defineProperty({__proto__:null,formatValue:Ay},Symbol.toStringTag,{value:"Module"})),Iy=(t,e)=>{let n=null;return e===0?t:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>t(...r),e)}},Lr=".",Zy=(t,e,n=Lr)=>{const r=t.split(n);return r.map((s,a)=>{const o=e(s,a,r);return o==null?null:typeof o=="string"?o:o.join(n)}).filter(s=>s!=null).join(n)},xy=(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)},Cy=((t,e,n={optional:!1})=>{const{optional:r,getter:s=xy}=n;if(e==="")return t;const a=e.split(Lr);if(a.length===1){const c=s(t,a[0]);if(c===void 0){if(r)return null;throw new Error(`Path ${e} does not exist. ${a[0]} is undefined`)}return c}const o=(c,l)=>{if(l>=a.length)return c;for(let u=a.length-l;u>=1;u--){const h=a.slice(l,l+u).join(Lr),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)}),Ry=t=>Object.getOwnPropertySymbols(globalThis).includes(t),_y=(t,e)=>{const n=Symbol.for(t);if(!Ry(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},Qo="sy_x_error",My=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),tn=t=>class Ut extends Error{static discriminator=Qo;discriminator=Ut.discriminator;static TYPE=t;type=Ut.TYPE;static matches=My(t);matches=Ut.matches;constructor(n,r){super(n,r),this.name=Ut.TYPE}static sub(n){return tn(`${t}.${n}`)}},ec=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Qo)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},wt="unknown",Br="nil";class jy{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Br,data:""};if(ec(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===Br)return null;if(e.type===wt)return new qr(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new qr(e.data)}}const Is=_y("synnax-error-registry",()=>new jy),Uy=({encode:t,decode:e})=>Is().register({encode:t,decode:e}),Dy=t=>Is().encode(t),Py=t=>t==null?null:Is().decode(t);class qr extends tn("unknown"){}const Ly=i.z.object({type:i.z.string(),data:i.z.string()});class By extends tn("canceled"){}class qy extends tn("not_implemented"){}const Re=Object.freeze(Object.defineProperty({__proto__:null,Canceled:By,NONE:Br,NotImplemented:qy,UNKNOWN:wt,Unknown:qr,createTyped:tn,decode:Py,encode:Dy,isTyped:ec,payloadZ:Ly,register:Uy},Symbol.toStringTag,{value:"Module"})),Fy=i.object({jsonrpc:i.literal("2.0"),method:i.string(),params:i.any().optional(),id:i.union([i.string(),i.number(),i.null()]).optional()}),tc=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()])}),Yy=tc.extend({result:i.json()}),Gy=tc.extend({error:i.object({code:i.number().int(),message:i.string().optional(),data:i.json().optional()})}),Vy=i.union([Yy,Gy]);i.union([Fy,Vy]);i.z.object({key:i.z.string(),value:i.z.string()});const nc=i.uuid(),rc=i.object({key:nc,name:i.string().min(1),color:i.string()}),sc=Object.freeze(Object.defineProperty({__proto__:null,keyZ:nc,labelZ:rc},Symbol.toStringTag,{value:"Module"})),Fr=i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/),Hy=(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 $e;if(c===void 0)return Ie;const l=/^\d+$/.test(o),u=/^\d+$/.test(c);if(l&&!u)return $e;if(!l&&u)return Ie;if(l&&u){const h=parseInt(o),d=parseInt(c);if(h<d)return $e;if(h>d)return Ie}else{if(o<c)return $e;if(o>c)return Ie}}return ut},nn=((t,e,n={})=>{n.checkMajor??=!0,n.checkMinor??=!0,n.checkPatch??=!0;const r=Fr.parse(t),s=Fr.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 $e;if(u>f)return Ie}if(n.checkMinor){if(h<O)return $e;if(h>O)return Ie}if(n.checkPatch){if(d<S)return $e;if(d>S)return Ie}return o===void 0&&l===void 0?ut:o===void 0?Ie:l===void 0?$e:Hy(o,l)}),Wy=(t,e,n={})=>io(nn(t,e,n)),ic=(t,e,n={})=>so(nn(t,e,n)),Ky=(t,e,n={})=>ro(nn(t,e,n)),Jy=({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}},Xy=({name:t,migrations:e,targetSchema:n,defaultVersion:r,def:s})=>{const a=Object.keys(e).sort(nn).pop();if(a==null)return u=>{if(u.version??=r,u.version!==s.version)return console.log(`${t} version ${u.version} is newer than latest version of ${s.version}.
14
14
  Returning default instead.
15
- `),s;try{return n!=null?n.parse(u):u}catch(h){return console.log(`${t} failed to parse default. Exiting with default`),console.error(h),s}};const o=Object.keys(e).length;let c=!1;const l=u=>{try{if(o===0||ic(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}}},Si=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:on,createMigration:sm,migrator:im,semVerNewer:ic,semVerOlder:rm,semVerZ:ts,versionsEqual:nm},Symbol.toStringTag,{value:"Module"})),am=["standard","scientific","engineering"];i.z.enum(am);const ac=i.z.enum(["success","info","warning","error","loading","disabled"]),om=t=>i.z.object({key:i.z.string(),name:i.z.string().default(""),variant:ac,message:i.z.string(),description:i.z.string().optional(),time:p.z,labels:qa(rc).optional(),details:t??i.z.unknown().optional()}),cm=i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)}),um=(t,e)=>{if(!(t instanceof Error))throw t;return oc({variant:"error",message:e??t.message,description:e!=null?t.message:void 0,details:{stack:t.stack??"",error:t}})},oc=t=>({key:ks(),time:p.now(),name:"",...t}),lm=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?t:void 0:e===t?t:void 0},hm=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?void 0:t:e===t?void 0:t},Zt=Object.freeze(Object.defineProperty({__proto__:null,create:oc,exceptionDetailsSchema:cm,fromException:um,keepVariants:lm,removeVariants:hm,statusZ:om,variantZ:ac},Symbol.toStringTag,{value:"Module"})),fm=(t,e)=>{if(!e.has(t))return t;let n=t,r=1,s=t;for(;e.has(s);){const a=s.match(dm);a?(n=s.slice(0,a.index).trim(),r=parseInt(a[1])+1):(n=s,r=1),s=`${n} (${r})`}return s},dm=/\((\d+)\)$/,pm=(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]}`},ym=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))},mm=(t,e)=>t.startsWith(e)?t.slice(e.length):t,ns=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:ym,deduplicateFileName:fm,naturalLanguageJoin:pm,trimPrefix:mm},Symbol.toStringTag,{value:"Module"})),cc="all",uc="create",lc="delete",hc="retrieve",fc="update",jn=i.z.enum([cc,uc,lc,hc,fc]);class Ae extends _e.createTyped("sy"){}class H extends Ae.sub("validation"){}class Wt extends H.sub("path"){path;error;static encodedSchema=i.z.object({path:i.z.string().array(),error:_e.payloadZ});constructor(e,n){const r=T.toArray(e);super(`${r.join(".")}: ${n.message}`),this.path=r.flatMap(s=>s.split(".")),this.error=n}static decode(e){const n=Wt.encodedSchema.parse(JSON.parse(e.data));return new Wt(n.path,_e.decode(n.error))}}class Gt extends Ae.sub("auth"){}class rs extends Gt.sub("invalid_token"){}class ss extends Gt.sub("expired_token"){}class zt extends Ae.sub("unexpected"){constructor(e){super(`
15
+ `),s;try{return n!=null?n.parse(u):u}catch(h){return console.log(`${t} failed to parse default. Exiting with default`),console.error(h),s}};const o=Object.keys(e).length;let c=!1;const l=u=>{try{if(o===0||ic(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}}},xi=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:nn,createMigration:Jy,migrator:Xy,semVerNewer:ic,semVerOlder:Ky,semVerZ:Fr,versionsEqual:Wy},Symbol.toStringTag,{value:"Module"})),Qy=["standard","scientific","engineering"];i.z.enum(Qy);class em{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 tm{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 nm=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:tm,Observer:em},Symbol.toStringTag,{value:"Module"})),rm=i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown()),Zs=t=>Object.entries(t),sm=(t,e)=>Object.fromEntries(Zs(t).map(([n,r])=>[n,e(r,n)])),im=t=>Object.fromEntries(Zs(t).filter(([e,n])=>n!==void 0)),am=(t,...e)=>{const n={...t};for(const r of e)delete n[r];return n},me=Object.freeze(Object.defineProperty({__proto__:null,entries:Zs,map:sm,omit:am,purgeUndefined:im,unknownZ:rm},Symbol.toStringTag,{value:"Module"})),ac=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",om=ac(),oc=["macOS","Windows","Linux"],cm=["macos","windows","linux"],um={macos:"macOS",windows:"Windows",linux:"Linux"},lm=i.z.enum(oc).or(i.z.enum(cm).transform(t=>um[t])),hm=()=>{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 fr;const fm=((t={})=>{const{force:e,default:n}=t;return e??fr??(fr=hm(),fr??n)}),dm=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:oc,RUNTIME:om,detect:ac,getOS:fm,osZ:lm},Symbol.toStringTag,{value:"Module"})),cc=i.z.enum(["success","info","warning","error","loading","disabled"]),pm=t=>i.z.object({key:i.z.string(),name:i.z.string().default(""),variant:cc,message:i.z.string(),description:i.z.string().optional(),time:m.z,labels:Ga(rc).optional(),details:t??i.z.unknown().optional()}),ym=i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)}),mm=(t,e)=>{if(!(t instanceof Error))throw t;return uc({variant:"error",message:e??t.message,description:e!=null?t.message:void 0,details:{stack:t.stack??"",error:t}})},uc=t=>({key:fs(),time:m.now(),name:"",...t}),gm=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?t:void 0:e===t?t:void 0},wm=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?void 0:t:e===t?void 0:t},lt=Object.freeze(Object.defineProperty({__proto__:null,create:uc,exceptionDetailsSchema:ym,fromException:mm,keepVariants:gm,removeVariants:wm,statusZ:pm,variantZ:cc},Symbol.toStringTag,{value:"Module"})),bm=(t,e)=>{if(!e.has(t))return t;let n=t,r=1,s=t;for(;e.has(s);){const a=s.match(vm);a?(n=s.slice(0,a.index).trim(),r=parseInt(a[1])+1):(n=s,r=1),s=`${n} (${r})`}return s},vm=/\((\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]}`},Tm=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))},Om=(t,e)=>t.startsWith(e)?t.slice(e.length):t,Yr=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:Tm,deduplicateFileName:bm,naturalLanguageJoin:zm,trimPrefix:Om},Symbol.toStringTag,{value:"Module"})),Em=(...t)=>t.map(lc).join(""),lc=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Nm=t=>t.endsWith("/")?t.slice(0,-1):t;class Tt{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=lc(s)}replace(e){return new Tt({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Tt({...this,pathPrefix:Em(this.path,e)})}toString(){return Nm(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new Tt({host:"unknown",port:0})}const Sm=t=>t.nullable().transform(e=>e===null?void 0:e).optional(),km=i.z.int().min(0).max(ho),Am=t=>i.array(t).or(t.transform(e=>[e])),hc=t=>Zy(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"]}),Ci=(t,e)=>{if(t==null)return null;const n=t[e];return n==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:n},$m=((t,e,n)=>e===""?t:Cy(Ci(t,"shape"),hc(e),{...n,getter:Ci})),Ee=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:$m,getFieldSchemaPath:hc,nullToUndefined:Sm,toArray:Am,uint12:km},Symbol.toStringTag,{value:"Module"})),xs=i.z.enum(["create","delete","retrieve","update"]);class Ne extends Re.createTyped("sy"){}class V extends Ne.sub("validation"){}class Ft extends V.sub("path"){path;error;static encodedSchema=i.z.object({path:i.z.string().array(),error:Re.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=Ft.encodedSchema.parse(JSON.parse(e.data));return new Ft(n.path,Re.decode(n.error))}}class St extends Ne.sub("auth"){}class Gr extends St.sub("invalid_token"){}class Vr extends St.sub("expired_token"){}class ck extends St.sub("access_denied"){}class nt extends Ne.sub("unexpected"){constructor(e){super(`
16
16
  Unexpected error encountered:
17
17
 
18
18
  ${e}
19
19
 
20
20
  Please report this to the Synnax team.
21
- `)}}class Ye extends Ae.sub("query"){}class Kt extends Ye.sub("not_found"){}class Jt extends Ye.sub("multiple_results"){}class is extends Ae.sub("route"){path;constructor(e,n){super(e),this.path=n}}class as extends Ae.sub("control"){}class Ii extends as.sub("unauthorized"){}class gm extends Ae.sub("disconnected"){constructor(e="Operation failed because no Core is connected."){super(e)}}class wm extends Ae.sub("contiguity"){}const bm=t=>t.type.startsWith(Ae.TYPE)?t.type.startsWith(H.TYPE)?t.type===Wt.TYPE?Wt.decode(t):new H(t.data):t.type.startsWith(Gt.TYPE)?t.type.startsWith(rs.TYPE)?new rs(t.data):t.type.startsWith(ss.TYPE)?new ss(t.data):new Gt(t.data):t.type.startsWith(zt.TYPE)?new zt(t.data):t.type.startsWith(Ye.TYPE)?t.type.startsWith(Kt.TYPE)?new Kt(t.data):t.type.startsWith(Jt.TYPE)?new Jt(t.data):new Ye(t.data):t.type.startsWith(as.TYPE)?t.type.startsWith(Ii.TYPE)?new Ii(t.data):new as(t.data):t.type.startsWith(is.TYPE)?new is(t.data,t.data):new zt(t.data):null,vm=()=>{throw new _e.NotImplemented};_e.register({encode:vm,decode:bm});const Tm=async(t,e)=>{const[n,r]=await e(t);return r==null?[n,r]:r instanceof Fe?[n,new Fe({message:`Cannot reach Core at ${r.url.host}:${r.url.port}`,url:r.url})]:[n,r]},cn=i.z.uuid(),dc=i.z.string(),Kn=i.z.object({key:cn,name:dc}),zm=t=>({type:"group",key:t}),Jn=i.z.enum(["label","log","allow_all","builtin","cluster","channel","node","group","range","framer","range-alias","user","workspace","schematic","lineplot","rack","device","task","policy","table","arc","schematic_symbol","status"]),pc=i.z.string().transform(t=>{const[e,n]=t.split(":");return{type:Jn.parse(e),key:n??""}}),j=i.z.object({type:Jn,key:i.z.string()}).or(pc),Em={type:"builtin",key:"root"},$t=(t=>(typeof t=="string"&&(t=pc.parse(t)),Array.isArray(t)?t.map(e=>$t(e)):`${t.type}:${t.key}`)),Nm=(t,e)=>t.type===e.type&&t.key===e.key,yc=t=>{const e=T.toArray(t);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:n})=>n):e.map(n=>j.parse(n))},mc=i.z.object({id:j,name:i.z.string(),data:ve.unknownZ.optional().nullable()}).transform(t=>({key:$t(t.id),...t})),Om=t=>t==="to"?"from":"to",$m=i.z.object({from:j,type:i.z.string(),to:j}).or(i.z.string().transform(t=>{const[e,n,r]=t.split("->");return{from:j.parse(e),type:n,to:j.parse(r)}})),Sm=t=>`${$t(t.from)}->${t.type}->${$t(t.to)}`,Im="parent",Am=(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),km="sy_group_set",xm="sy_group_delete",Zm=i.object({group:Kn}),Cm=i.object({parent:j,key:cn.optional(),name:i.string()}),Rm=i.object({key:cn,name:i.string()}),_m=i.object({keys:i.array(cn)}),jm="/ontology/create-group",Mm="/ontology/rename-group",Dm="/ontology/delete-group";let gc=class{client;constructor(e){this.client=e}async create(e){return(await w(this.client,jm,e,Cm,Zm)).group}async rename(e,n){await w(this.client,Mm,{key:e,name:n},Rm,i.object({}))}async delete(e){await w(this.client,Dm,{keys:T.toArray(e)},_m,i.object({}))}};const Pm=Object.freeze(Object.defineProperty({__proto__:null,Client:gc,DELETE_CHANNEL_NAME:xm,SET_CHANNEL_NAME:km,groupZ:Kn,keyZ:cn,nameZ:dc,ontologyID:zm},Symbol.toStringTag,{value:"Module"})),Um="/ontology/add-children",Lm="/ontology/remove-children",Bm="/ontology/move-children",Ai=i.z.object({id:j,children:j.array()}),qm=i.z.object({from:j,to:j,children:j.array()}),Nr=i.z.object({});let Fm=class{client;constructor(e){this.client=e}async addChildren(e,...n){await w(this.client,Um,{id:e,children:n},Ai,Nr)}async removeChildren(e,...n){await w(this.client,Lm,{id:e,children:n},Ai,Nr)}async moveChildren(e,n,...r){await w(this.client,Bm,{from:e,to:n,children:r},qm,Nr)}};const Vm="/ontology/retrieve",Ym=i.z.object({ids:j.array().optional(),children:i.z.boolean().optional(),parents:i.z.boolean().optional(),excludeFieldData:i.z.boolean().optional(),searchTerm:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),types:Jn.array().optional()}),Hm=i.z.object({resources:mc.array()});let wc=class{type="ontology";groups;client;writer;framer;constructor(e,n){this.client=e,this.writer=new Fm(e),this.groups=new gc(e),this.framer=n}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object"&&!("key"in e))return this.execRetrieve(e);const r=yc(e),s=await this.execRetrieve({ids:r,...n});if(Array.isArray(e))return s;if(s.length===0)throw new Ye(`No resource found with ID ${ns.naturalLanguageJoin(r.map(a=>$t(a)))}`);return s[0]}async retrieveChildren(e,n){return await this.execRetrieve({ids:T.toArray(e),children:!0,...n})}async retrieveParents(e,n){return await this.execRetrieve({ids:T.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 w(this.client,Vm,e,Ym,Hm);return n}};const Wm="sy_ontology_resource_set",Gm="sy_ontology_resource_delete",Km="sy_ontology_relationship_set",Jm="sy_ontology_relationship_delete",Xm=Object.freeze(Object.defineProperty({__proto__:null,Client:wc,PARENT_OF_RELATIONSHIP_TYPE:Im,RELATIONSHIP_DELETE_CHANNEL_NAME:Jm,RELATIONSHIP_SET_CHANNEL_NAME:Km,RESOURCE_DELETE_CHANNEL_NAME:Gm,RESOURCE_SET_CHANNEL_NAME:Wm,ROOT_ID:Em,idToString:$t,idZ:j,idsEqual:Nm,matchRelationship:Am,oppositeRelationshipDirection:Om,parseIDs:yc,relationshipToString:Sm,relationshipZ:$m,resourceTypeZ:Jn,resourceZ:mc},Symbol.toStringTag,{value:"Module"})),Ct=i.z.uuid(),Xn=i.z.object({key:Ct,subjects:T.nullableZ(j),objects:T.nullableZ(j),actions:T.nullableZ(jn)}),bc=i.z.object({key:Ct.optional(),subjects:j.array().or(j),objects:j.array().or(j),actions:jn.array().or(jn)}),Qm=i.z.object({keys:Ct.array().optional(),subjects:j.array().optional()}),eg=i.z.object({key:Ct}).transform(({key:t})=>({keys:[t]})),tg=i.z.union([i.z.object({for:j}).transform(({for:t})=>({subjects:[t]})),i.z.object({for:j.array()}).transform(({for:t})=>({subjects:t})),Qm]),ng=i.z.union([eg,tg]),rg=i.z.object({policies:T.nullableZ(Xn)}),sg=i.z.object({policies:Xn.partial({key:!0}).array()}),ig=i.z.object({policies:Xn.array()}),ag=i.z.object({keys:Ct.array()}),og=i.z.object({}),cg="/access/policy/retrieve",ug="/access/policy/create",lg="/access/policy/delete";let vc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),s=bc.array().parse(T.toArray(e)).map(o=>({objects:T.toArray(o.objects),actions:T.toArray(o.actions),subjects:T.toArray(o.subjects)})),a=await w(this.client,ug,{policies:s},sg,ig);return n?a.policies:a.policies[0]}async retrieve(e){const n="key"in e,r=await w(this.client,cg,e,ng,rg);return n?r.policies[0]:r.policies}async delete(e){await w(this.client,lg,{keys:T.toArray(e)},ag,og)}};const hg=t=>({type:"policy",key:t}),fg={type:"allow_all",key:""},dg=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:fg,Client:vc,keyZ:Ct,newZ:bc,ontologyID:hg,policyZ:Xn},Symbol.toStringTag,{value:"Module"}));let Tc=class{policy;constructor(e){this.policy=new vc(e)}};const pg=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:cc,CREATE_ACTION:uc,Client:Tc,DELETE_ACTION:lc,RETRIEVE_ACTION:hc,UPDATE_ACTION:fc,actionZ:jn},Symbol.toStringTag,{value:"Module"}));function y(t,e,n){function r(c,l){var u;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(u=c._zod).traits??(u.traits=new Set),c._zod.traits.add(t),e(c,l);for(const h in o.prototype)h in c||Object.defineProperty(c,h,{value:o.prototype[h].bind(c)});c._zod.constr=o,c._zod.def=l}const s=n?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:t});function o(c){var l;const u=n?.Parent?new a:this;r(u,c),(l=u._zod).deferred??(l.deferred=[]);for(const h of u._zod.deferred)h();return u}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}class Et extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class zc extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Ec={};function rt(t){return Ec}function yg(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 os(t,e){return typeof e=="bigint"?e.toString():e}function js(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Ms(t){return t==null}function Ds(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function mg(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 ki=Symbol("evaluating");function U(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==ki)return r===void 0&&(r=ki,r=n()),r},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function ot(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ct(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function xi(t){return JSON.stringify(t)}const Nc="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Mn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const gg=js(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Xt(t){if(Mn(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(Mn(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Oc(t){return Xt(t)?{...t}:Array.isArray(t)?[...t]:t}const wg=new Set(["string","number","symbol"]);function Qn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function I(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 bg(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const vg={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Tg(t,e){const n=t._zod.def,r=ct(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 ot(this,"shape",s),s},checks:[]});return He(t,r)}function zg(t,e){const n=t._zod.def,r=ct(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 ot(this,"shape",s),s},checks:[]});return He(t,r)}function Eg(t,e){if(!Xt(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=ct(t._zod.def,{get shape(){const a={...t._zod.def.shape,...e};return ot(this,"shape",a),a},checks:[]});return He(t,s)}function Ng(t,e){if(!Xt(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 ot(this,"shape",r),r},checks:t._zod.def.checks};return He(t,n)}function Og(t,e){const n=ct(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return ot(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return He(t,n)}function $g(t,e,n){const r=ct(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 ot(this,"shape",a),a},checks:[]});return He(e,r)}function Sg(t,e,n){const r=ct(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 ot(this,"shape",a),a},checks:[]});return He(e,r)}function gt(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function $c(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function $n(t){return typeof t=="string"?t:t?.message}function st(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const s=$n(t.inst?._zod.def?.error?.(t))??$n(e?.error?.(t))??$n(n.customError?.(t))??$n(n.localeError?.(t))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Ps(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Qt(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const Sc=(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,os,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ic=y("$ZodError",Sc),Ac=y("$ZodError",Sc,{Parent:Error});function Ig(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 Ag(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 Us=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=>st(l,a,rt())));throw Nc(c,s?.callee),c}return o.value},Ls=t=>async(e,n,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>st(l,a,rt())));throw Nc(c,s?.callee),c}return o.value},er=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??Ic)(a.issues.map(o=>st(o,s,rt())))}:{success:!0,data:a.value}},kg=er(Ac),tr=t=>async(e,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=e._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(o=>st(o,s,rt())))}:{success:!0,data:a.value}},xg=tr(Ac),Zg=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Us(t)(e,n,s)},Cg=t=>(e,n,r)=>Us(t)(e,n,r),Rg=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ls(t)(e,n,s)},_g=t=>async(e,n,r)=>Ls(t)(e,n,r),jg=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return er(t)(e,n,s)},Mg=t=>(e,n,r)=>er(t)(e,n,r),Dg=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return tr(t)(e,n,s)},Pg=t=>async(e,n,r)=>tr(t)(e,n,r),Ug=/^[cC][^\s-]{8,}$/,Lg=/^[0-9a-z]+$/,Bg=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,qg=/^[0-9a-vA-V]{20}$/,Fg=/^[A-Za-z0-9]{27}$/,Vg=/^[a-zA-Z0-9_-]{21}$/,Yg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Hg=/^([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})$/,Zi=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)$/,Wg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Gg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Kg(){return new RegExp(Gg,"u")}const Jg=/^(?:(?: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])$/,Xg=/^(([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}|:))$/,Qg=/^((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])$/,ew=/^(([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])$/,tw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kc=/^[A-Za-z0-9_-]*$/,nw=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,rw=/^\+(?:[0-9]){6,14}[0-9]$/,xc="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",sw=new RegExp(`^${xc}$`);function Zc(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 iw(t){return new RegExp(`^${Zc(t)}$`)}function aw(t){const e=Zc({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${xc}T(?:${r})$`)}const ow=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},cw=/^-?\d+$/,uw=/^-?\d+(?:\.\d+)?/,lw=/^(?:true|false)$/i,hw=/^[^A-Z]*$/,fw=/^[^a-z]*$/,oe=y("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Cc={number:"number",bigint:"bigint",object:"date"},Rc=y("$ZodCheckLessThan",(t,e)=>{oe.init(t,e);const n=Cc[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})}}),_c=y("$ZodCheckGreaterThan",(t,e)=>{oe.init(t,e);const n=Cc[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})}}),dw=y("$ZodCheckMultipleOf",(t,e)=>{oe.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):mg(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),pw=y("$ZodCheckNumberFormat",(t,e)=>{oe.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[s,a]=vg[e.format];t._zod.onattach.push(o=>{const c=o._zod.bag;c.format=e.format,c.minimum=s,c.maximum=a,n&&(c.pattern=cw)}),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})}}),yw=y("$ZodCheckMaxLength",(t,e)=>{var n;oe.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ms(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=Ps(s);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),mw=y("$ZodCheckMinLength",(t,e)=>{var n;oe.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ms(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=Ps(s);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),gw=y("$ZodCheckLengthEquals",(t,e)=>{var n;oe.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ms(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=Ps(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})}}),nr=y("$ZodCheckStringFormat",(t,e)=>{var n,r;oe.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=()=>{})}),ww=y("$ZodCheckRegex",(t,e)=>{nr.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})}}),bw=y("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=hw),nr.init(t,e)}),vw=y("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=fw),nr.init(t,e)}),Tw=y("$ZodCheckIncludes",(t,e)=>{oe.init(t,e);const n=Qn(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),zw=y("$ZodCheckStartsWith",(t,e)=>{oe.init(t,e);const n=new RegExp(`^${Qn(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Ew=y("$ZodCheckEndsWith",(t,e)=>{oe.init(t,e);const n=new RegExp(`.*${Qn(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),Nw=y("$ZodCheckOverwrite",(t,e)=>{oe.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class Ow{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
21
+ `)}}class Ge extends Ne.sub("query"){}class Yt extends Ge.sub("not_found"){}class Gt extends Ge.sub("multiple_results"){}class Hr extends Ne.sub("route"){path;constructor(e,n){super(e),this.path=n}}class Wr extends Ne.sub("control"){}class Ri extends Wr.sub("unauthorized"){}class Im extends Ne.sub("disconnected"){constructor(e="Operation failed because no Core is connected."){super(e)}}class Zm extends Ne.sub("contiguity"){}const xm=t=>t.type.startsWith(Ne.TYPE)?t.type.startsWith(V.TYPE)?t.type===Ft.TYPE?Ft.decode(t):new V(t.data):t.type.startsWith(St.TYPE)?t.type.startsWith(Gr.TYPE)?new Gr(t.data):t.type.startsWith(Vr.TYPE)?new Vr(t.data):new St(t.data):t.type.startsWith(nt.TYPE)?new nt(t.data):t.type.startsWith(Ge.TYPE)?t.type.startsWith(Yt.TYPE)?new Yt(t.data):t.type.startsWith(Gt.TYPE)?new Gt(t.data):new Ge(t.data):t.type.startsWith(Wr.TYPE)?t.type.startsWith(Ri.TYPE)?new Ri(t.data):new Wr(t.data):t.type.startsWith(Hr.TYPE)?new Hr(t.data,t.data):new nt(t.data):null,Cm=()=>{throw new Re.NotImplemented};Re.register({encode:Cm,decode:xm});const Rm=async(t,e)=>{const[n,r]=await e(t);return r==null?[n,r]:r instanceof Ye?[n,new Ye({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"]),fc=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(fc),_m={type:"builtin",key:"root"},H=t=>{const e=n=>({type:t,key:gd.isZero(n)?"":n.toString()});return(n=>Array.isArray(n)?n.map(e):e(n))},_e=(t=>(typeof t=="string"&&(t=fc.parse(t)),Array.isArray(t)?t.map(e=>_e(e)):`${t.type}:${t.key}`)),Mm=(t,e)=>t.type===e.type&&t.key===e.key,dc=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))},pc=i.z.object({id:L,name:i.z.string(),data:me.unknownZ.optional().nullable()}).transform(t=>({key:_e(t.id),...t})),jm=t=>t==="to"?"from":"to",Um=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)}})),Dm=t=>`${_e(t.from)}->${t.type}->${_e(t.to)}`,Pm="parent",Lm=(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),rn=i.z.uuid(),yc=i.z.string(),Pn=i.z.object({key:rn,name:yc}),Bm=H("group"),qm="sy_group_set",Fm="sy_group_delete",Ym=i.object({group:Pn}),Gm=i.object({parent:L,key:rn.optional(),name:i.string()}),Vm=i.object({key:rn,name:i.string()}),Hm=i.object({keys:i.array(rn)});let mc=class{client;constructor(e){this.client=e}async create(e){return(await T(this.client,"/ontology/create-group",e,Gm,Ym)).group}async rename(e,n){await T(this.client,"/ontology/rename-group",{key:e,name:n},Vm,i.object({}))}async delete(e){await T(this.client,"/ontology/delete-group",{keys:N.toArray(e)},Hm,i.object({}))}};const Wm=Object.freeze(Object.defineProperty({__proto__:null,Client:mc,DELETE_CHANNEL_NAME:Fm,SET_CHANNEL_NAME:qm,groupZ:Pn,keyZ:rn,nameZ:yc,ontologyID:Bm},Symbol.toStringTag,{value:"Module"})),_i=i.z.object({id:L,children:L.array()}),Km=i.z.object({from:L,to:L,children:L.array()}),dr=i.z.object({});let Jm=class{client;constructor(e){this.client=e}async addChildren(e,...n){await T(this.client,"/ontology/add-children",{id:e,children:n},_i,dr)}async removeChildren(e,...n){await T(this.client,"/ontology/remove-children",{id:e,children:n},_i,dr)}async moveChildren(e,n,...r){await T(this.client,"/ontology/move-children",{from:e,to:n,children:r},Km,dr)}};const Xm=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()}),Qm=i.z.object({resources:pc.array()});let gc=class{type="ontology";groups;client;writer;framer;constructor(e,n){this.client=e,this.writer=new Jm(e),this.groups=new mc(e),this.framer=n}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object"&&!("key"in e))return this.execRetrieve(e);const r=dc(e),s=await this.execRetrieve({ids:r,...n});if(Array.isArray(e))return s;if(s.length===0)throw new Ge(`No resource found with ID ${Yr.naturalLanguageJoin(r.map(a=>_e(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 T(this.client,"/ontology/retrieve",e,Xm,Qm);return n}};const eg="sy_ontology_resource_set",tg="sy_ontology_resource_delete",ng="sy_ontology_relationship_set",rg="sy_ontology_relationship_delete",sg=Object.freeze(Object.defineProperty({__proto__:null,Client:gc,PARENT_OF_RELATIONSHIP_TYPE:Pm,RELATIONSHIP_DELETE_CHANNEL_NAME:rg,RELATIONSHIP_SET_CHANNEL_NAME:ng,RESOURCE_DELETE_CHANNEL_NAME:tg,RESOURCE_SET_CHANNEL_NAME:eg,ROOT_ID:_m,createIDFactory:H,idToString:_e,idZ:L,idsEqual:Mm,matchRelationship:Lm,oppositeRelationshipDirection:jm,parseIDs:dc,relationshipToString:Dm,relationshipZ:Um,resourceTypeZ:Dn,resourceZ:pc},Symbol.toStringTag,{value:"Module"})),It=i.z.uuid(),Cs=i.z.object({key:It,name:i.z.string(),objects:N.nullableZ(L),actions:N.nullableZ(xs),internal:i.z.boolean()}),Rs=i.z.object({key:It.optional(),name:i.z.string(),objects:Ee.toArray(L),actions:Ee.toArray(xs)}),_s=H("policy"),ig=_s(""),ag="sy_policy_set",og="sy_policy_delete",cg=i.z.object({keys:It.array().optional(),subjects:L.array().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),internal:i.z.boolean().optional()}),ug=i.z.object({key:It}).transform(({key:t})=>({keys:[t]})),lg=i.z.union([i.z.object({for:L}).transform(({for:t})=>({subjects:[t]})),i.z.object({for:L.array()}).transform(({for:t})=>({subjects:t})),cg]),hg=i.z.union([ug,lg]),fg=i.z.object({policies:N.nullableZ(Cs)}),dg=Rs.transform(t=>({policies:[t]})),wc=Rs.array().transform(t=>({policies:t})),bc=i.z.union([dg,wc]),pg=i.z.object({policies:Cs.array()}),yg=i.z.object({keys:It.array()}),mg=i.z.object({});let vc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await T(this.client,"/access/policy/create",e,bc,pg);return n?r.policies:r.policies[0]}async retrieve(e){const n="key"in e,r=await T(this.client,"/access/policy/retrieve",e,hg,fg);return n?r.policies[0]:r.policies}async delete(e){await T(this.client,"/access/policy/delete",{keys:N.toArray(e)},yg,mg)}};const gg=Object.freeze(Object.defineProperty({__proto__:null,Client:vc,DELETE_CHANNEL_NAME:og,SET_CHANNEL_NAME:ag,TYPE_ONTOLOGY_ID:ig,createArgsZ:bc,keyZ:It,multipleCreateArgsZ:wc,newZ:Rs,ontologyID:_s,policyZ:Cs},Symbol.toStringTag,{value:"Module"})),Ve=i.z.uuid(),Ln=i.z.object({key:Ve,name:i.z.string(),description:i.z.string().optional(),internal:i.z.boolean().optional()}),Ms=Ln.partial({key:!0}),js=H("role"),wg=js(""),Se=i.z.uuid(),sn=i.z.object({key:Se,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)}),zc=sn.omit({rootUser:!0}).partial({key:!0,firstName:!0,lastName:!0}).extend({password:i.z.string().min(1)}),bg=i.z.object({keys:Se.array().optional(),usernames:i.z.string().array().optional()}),vg=i.z.object({key:Se}).transform(({key:t})=>({keys:[t]})),zg=i.z.object({username:i.z.string()}).transform(({username:t})=>({usernames:[t]})),Tg=i.z.object({usernames:i.z.string().array()}).transform(({usernames:t})=>({usernames:t})),Og=i.z.union([vg,zg,Tg,bg]),Eg=i.z.object({users:N.nullableZ(sn)}),Ng=i.z.object({users:zc.array()}),Sg=i.z.object({users:sn.array()}),kg=i.z.object({key:Se,username:i.z.string().min(1)}),Ag=i.z.object({}),$g=i.z.object({key:Se,firstName:i.z.string().optional(),lastName:i.z.string().optional()}),Ig=i.z.object({}),Zg=i.z.object({keys:Se.array()}),xg=i.z.object({}),Cg="sy_user_set",Rg="sy_user_delete";let Tc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await T(this.client,"/user/create",{users:N.toArray(e)},Ng,Sg);return n?r.users:r.users[0]}async changeUsername(e,n){await T(this.client,"/user/change-username",{key:e,username:n},kg,Ag)}async retrieve(e){const n="key"in e||"username"in e,r=await T(this.client,"/user/retrieve",e,Og,Eg);if(!n)return r.users;if(r.users.length===0){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new Yt(`No user with ${s} found`)}if(r.users.length>1){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new Gt(`Multiple users found with ${s}`)}return r.users[0]}async rename(e,n,r){await T(this.client,"/user/rename",{key:e,firstName:n,lastName:r},$g,Ig)}async delete(e){await T(this.client,"/user/delete",{keys:N.toArray(e)},Zg,xg)}};const Oc=H("user"),_g=Oc(""),Mg=Object.freeze(Object.defineProperty({__proto__:null,Client:Tc,DELETE_CHANNEL_NAME:Rg,SET_CHANNEL_NAME:Cg,TYPE_ONTOLOGY_ID:_g,keyZ:Se,newZ:zc,ontologyID:Oc,userZ:sn},Symbol.toStringTag,{value:"Module"})),jg=i.z.object({keys:Ve.array().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),internal:i.z.boolean().optional()}),Ug=i.z.object({key:Ve}).transform(({key:t})=>({keys:[t]})),Dg=Ms.transform(t=>({roles:[t]})),Ec=Ms.array().transform(t=>({roles:t})),Nc=i.z.union([Dg,Ec]),Pg=i.z.object({roles:Ln.array()}),Lg=i.z.object({roles:N.nullableZ(Ln)}),Sc=i.z.union([Ug,jg]),Bg=i.z.object({}),qg=Ve.transform(t=>({keys:[t]})).or(Ve.array().transform(t=>({keys:t}))),Fg=i.z.object({user:Se,role:Ve}),Yg=i.z.object({}),Gg=i.z.object({user:Se,role:Ve}),Vg=i.z.object({}),Hg="sy_role_set",Wg="sy_role_delete";let kc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await T(this.client,"/access/role/create",e,Nc,Pg);return n?r.roles:r.roles[0]}async retrieve(e){const n="key"in e,r=await T(this.client,"/access/role/retrieve",e,Sc,Lg);return n?r.roles[0]:r.roles}async delete(e){await T(this.client,"/access/role/delete",e,qg,Bg)}async assign(e){await T(this.client,"/access/role/assign",e,Fg,Yg)}async unassign(e){await T(this.client,"/access/role/unassign",e,Gg,Vg)}};const Kg=Object.freeze(Object.defineProperty({__proto__:null,Client:kc,DELETE_CHANNEL_NAME:Wg,SET_CHANNEL_NAME:Hg,TYPE_ONTOLOGY_ID:wg,createArgsZ:Nc,keyZ:Ve,multipleCreateArgsZ:Ec,newZ:Ms,ontologyID:js,retrieveArgsZ:Sc,roleZ:Ln},Symbol.toStringTag,{value:"Module"}));let Ac=class{policies;roles;constructor(e){this.policies=new vc(e),this.roles=new kc(e)}};const Jg=(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},Xg=Object.freeze(Object.defineProperty({__proto__:null,Client:Ac,actionZ:xs,allowRequest:Jg,policy:gg,role:Kg},Symbol.toStringTag,{value:"Module"}));function w(t,e,n){function r(c,l){var u;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(u=c._zod).traits??(u.traits=new Set),c._zod.traits.add(t),e(c,l);for(const h in o.prototype)h in c||Object.defineProperty(c,h,{value:o.prototype[h].bind(c)});c._zod.constr=o,c._zod.def=l}const s=n?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:t});function o(c){var l;const u=n?.Parent?new a:this;r(u,c),(l=u._zod).deferred??(l.deferred=[]);for(const h of u._zod.deferred)h();return u}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}class Ot 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 Ic={};function it(t){return Ic}function Qg(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 Kr(t,e){return typeof e=="bigint"?e.toString():e}function Us(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Ds(t){return t==null}function Ps(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function ew(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 Mi=Symbol("evaluating");function D(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Mi)return r===void 0&&(r=Mi,r=n()),r},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function ht(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ft(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function ji(t){return JSON.stringify(t)}const Zc="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function $n(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const tw=Us(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Vt(t){if($n(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!($n(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function xc(t){return Vt(t)?{...t}:Array.isArray(t)?[...t]:t}const nw=new Set(["string","number","symbol"]);function Bn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(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 rw(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const sw={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 iw(t,e){const n=t._zod.def,r=ft(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 ht(this,"shape",s),s},checks:[]});return He(t,r)}function aw(t,e){const n=t._zod.def,r=ft(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 ht(this,"shape",s),s},checks:[]});return He(t,r)}function ow(t,e){if(!Vt(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=ft(t._zod.def,{get shape(){const a={...t._zod.def.shape,...e};return ht(this,"shape",a),a},checks:[]});return He(t,s)}function cw(t,e){if(!Vt(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 ht(this,"shape",r),r},checks:t._zod.def.checks};return He(t,n)}function uw(t,e){const n=ft(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return ht(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return He(t,n)}function lw(t,e,n){const r=ft(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 ht(this,"shape",a),a},checks:[]});return He(e,r)}function hw(t,e,n){const r=ft(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 ht(this,"shape",a),a},checks:[]});return He(e,r)}function bt(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 Cc(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 at(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 Ls(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ht(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const Rc=(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,Kr,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},_c=w("$ZodError",Rc),Mc=w("$ZodError",Rc,{Parent:Error});function fw(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 dw(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 Bs=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 Ot;if(o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>at(l,a,it())));throw Zc(c,s?.callee),c}return o.value},qs=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=>at(l,a,it())));throw Zc(c,s?.callee),c}return o.value},qn=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 Ot;return a.issues.length?{success:!1,error:new(t??_c)(a.issues.map(o=>at(o,s,it())))}:{success:!0,data:a.value}},pw=qn(Mc),Fn=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=>at(o,s,it())))}:{success:!0,data:a.value}},yw=Fn(Mc),mw=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Bs(t)(e,n,s)},gw=t=>(e,n,r)=>Bs(t)(e,n,r),ww=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return qs(t)(e,n,s)},bw=t=>async(e,n,r)=>qs(t)(e,n,r),vw=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return qn(t)(e,n,s)},zw=t=>(e,n,r)=>qn(t)(e,n,r),Tw=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Fn(t)(e,n,s)},Ow=t=>async(e,n,r)=>Fn(t)(e,n,r),Ew=/^[cC][^\s-]{8,}$/,Nw=/^[0-9a-z]+$/,Sw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,kw=/^[0-9a-vA-V]{20}$/,Aw=/^[A-Za-z0-9]{27}$/,$w=/^[a-zA-Z0-9_-]{21}$/,Iw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Zw=/^([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})$/,Ui=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)$/,xw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Cw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Rw(){return new RegExp(Cw,"u")}const _w=/^(?:(?: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])$/,Mw=/^(([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}|:))$/,jw=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Uw=/^(([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])$/,Dw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,jc=/^[A-Za-z0-9_-]*$/,Pw=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Lw=/^\+(?:[0-9]){6,14}[0-9]$/,Uc="(?:(?:\\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])))",Bw=new RegExp(`^${Uc}$`);function Dc(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 qw(t){return new RegExp(`^${Dc(t)}$`)}function Fw(t){const e=Dc({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(`^${Uc}T(?:${r})$`)}const Yw=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Gw=/^-?\d+$/,Vw=/^-?\d+(?:\.\d+)?/,Hw=/^(?:true|false)$/i,Ww=/^[^A-Z]*$/,Kw=/^[^a-z]*$/,ne=w("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Pc={number:"number",bigint:"bigint",object:"date"},Lc=w("$ZodCheckLessThan",(t,e)=>{ne.init(t,e);const n=Pc[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})}}),Bc=w("$ZodCheckGreaterThan",(t,e)=>{ne.init(t,e);const n=Pc[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})}}),Jw=w("$ZodCheckMultipleOf",(t,e)=>{ne.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):ew(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})}}),Xw=w("$ZodCheckNumberFormat",(t,e)=>{ne.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[s,a]=sw[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=Gw)}),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})}}),Qw=w("$ZodCheckMaxLength",(t,e)=>{var n;ne.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ds(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const s=r.value;if(s.length<=e.maximum)return;const o=Ls(s);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),eb=w("$ZodCheckMinLength",(t,e)=>{var n;ne.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ds(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const s=r.value;if(s.length>=e.minimum)return;const o=Ls(s);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),tb=w("$ZodCheckLengthEquals",(t,e)=>{var n;ne.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ds(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{const s=r.value,a=s.length;if(a===e.length)return;const o=Ls(s),c=a>e.length;r.issues.push({origin:o,...c?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Yn=w("$ZodCheckStringFormat",(t,e)=>{var n,r;ne.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=()=>{})}),nb=w("$ZodCheckRegex",(t,e)=>{Yn.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})}}),rb=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ww),Yn.init(t,e)}),sb=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Kw),Yn.init(t,e)}),ib=w("$ZodCheckIncludes",(t,e)=>{ne.init(t,e);const n=Bn(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})}}),ab=w("$ZodCheckStartsWith",(t,e)=>{ne.init(t,e);const n=new RegExp(`^${Bn(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})}}),ob=w("$ZodCheckEndsWith",(t,e)=>{ne.init(t,e);const n=new RegExp(`.*${Bn(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})}}),cb=w("$ZodCheckOverwrite",(t,e)=>{ne.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class ub{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
22
22
  `).filter(o=>o),s=Math.min(...r.map(o=>o.length-o.trimStart().length)),a=r.map(o=>o.slice(s)).map(o=>" ".repeat(this.indent*2)+o);for(const o of a)this.content.push(o)}compile(){const e=Function,n=this?.args,s=[...(this?.content??[""]).map(a=>` ${a}`)];return new e(...n,s.join(`
23
- `))}}const $w={major:4,minor:1,patch:12},V=y("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=$w;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const a of s._zod.onattach)a(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,c,l)=>{let u=gt(o),h;for(const d of c){if(d._zod.def.when){if(!d._zod.def.when(o))continue}else if(u)continue;const f=o.issues.length,v=d._zod.check(o);if(v instanceof Promise&&l?.async===!1)throw new Et;if(h||v instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await v,o.issues.length!==f&&(u||(u=gt(o,f)))});else{if(o.issues.length===f)continue;u||(u=gt(o,f))}}return h?h.then(()=>o):o},a=(o,c,l)=>{if(gt(o))return o.aborted=!0,o;const u=s(c,r,l);if(u instanceof Promise){if(l.async===!1)throw new 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=kg(t,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return xg(t,s).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),Bs=y("$ZodString",(t,e)=>{V.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??ow(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),L=y("$ZodStringFormat",(t,e)=>{nr.init(t,e),Bs.init(t,e)}),Sw=y("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Hg),L.init(t,e)}),Iw=y("$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=Zi(r))}else e.pattern??(e.pattern=Zi());L.init(t,e)}),Aw=y("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Wg),L.init(t,e)}),kw=y("$ZodURL",(t,e)=>{L.init(t,e),t._zod.check=n=>{try{const r=n.value.trim(),s=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:nw.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})}}}),xw=y("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Kg()),L.init(t,e)}),Zw=y("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Vg),L.init(t,e)}),Cw=y("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ug),L.init(t,e)}),Rw=y("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Lg),L.init(t,e)}),_w=y("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Bg),L.init(t,e)}),jw=y("$ZodXID",(t,e)=>{e.pattern??(e.pattern=qg),L.init(t,e)}),Mw=y("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Fg),L.init(t,e)}),Dw=y("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=aw(e)),L.init(t,e)}),Pw=y("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=sw),L.init(t,e)}),Uw=y("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=iw(e)),L.init(t,e)}),Lw=y("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Yg),L.init(t,e)}),Bw=y("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Jg),L.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),qw=y("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Xg),L.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Fw=y("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Qg),L.init(t,e)}),Vw=y("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=ew),L.init(t,e),t._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[s,a]=r;if(!a)throw new Error;const o=Number(a);if(`${o}`!==a)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${s}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function jc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const Yw=y("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=tw),L.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{jc(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Hw(t){if(!kc.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return jc(n)}const Ww=y("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=kc),L.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{Hw(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Gw=y("$ZodE164",(t,e)=>{e.pattern??(e.pattern=rw),L.init(t,e)});function Kw(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 Jw=y("$ZodJWT",(t,e)=>{L.init(t,e),t._zod.check=n=>{Kw(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Mc=y("$ZodNumber",(t,e)=>{V.init(t,e),t._zod.pattern=t._zod.bag.pattern??uw,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}}),Xw=y("$ZodNumber",(t,e)=>{pw.init(t,e),Mc.init(t,e)}),Qw=y("$ZodBoolean",(t,e)=>{V.init(t,e),t._zod.pattern=lw,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}}),eb=y("$ZodUnknown",(t,e)=>{V.init(t,e),t._zod.parse=n=>n}),tb=y("$ZodNever",(t,e)=>{V.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Ci(t,e,n){t.issues.length&&e.issues.push(...$c(n,t.issues)),e.value[n]=t.value}const nb=y("$ZodArray",(t,e)=>{V.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=>Ci(u,n,o))):Ci(l,n,o)}return a.length?Promise.all(a).then(()=>n):n}});function Dn(t,e,n,r){t.issues.length&&e.issues.push(...$c(n,t.issues)),t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Dc(t){const e=Object.keys(t.shape);for(const r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=bg(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Pc(t,e,n,r,s,a){const o=[],c=s.keySet,l=s.catchall._zod,u=l.def.type;for(const h of Object.keys(e)){if(c.has(h))continue;if(u==="never"){o.push(h);continue}const d=l.run({value:e[h],issues:[]},r);d instanceof Promise?t.push(d.then(f=>Dn(f,n,h,e))):Dn(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 rb=y("$ZodObject",(t,e)=>{if(V.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){const c=e.shape;Object.defineProperty(e,"shape",{get:()=>{const l={...c};return Object.defineProperty(e,"shape",{value:l}),l}})}const r=js(()=>Dc(e));U(t._zod,"propValues",()=>{const c=e.shape,l={};for(const u in c){const h=c[u]._zod;if(h.values){l[u]??(l[u]=new Set);for(const d of h.values)l[u].add(d)}}return l});const s=Mn,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 $=d[f]._zod.run({value:u[f],issues:[]},l);$ instanceof Promise?h.push($.then(k=>Dn(k,c,f,u))):Dn($,c,f,u)}return a?Pc(h,u,c,l,r.value,t):h.length?Promise.all(h).then(()=>c):c}}),sb=y("$ZodObjectJIT",(t,e)=>{rb.init(t,e);const n=t._zod.parse,r=js(()=>Dc(e)),s=f=>{const v=new Ow(["shape","payload","ctx"]),$=r.value,k=G=>{const Y=xi(G);return`shape[${Y}]._zod.run({ value: input[${Y}], issues: [] }, ctx)`};v.write("const input = payload.value;");const b=Object.create(null);let E=0;for(const G of $.keys)b[G]=`key_${E++}`;v.write("const newResult = {};");for(const G of $.keys){const Y=b[G],me=xi(G);v.write(`const ${Y} = ${k(G)};`),v.write(`
24
- if (${Y}.issues.length) {
25
- payload.issues = payload.issues.concat(${Y}.issues.map(iss => ({
23
+ `))}}const lb={major:4,minor:1,patch:12},Y=w("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=lb;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=bt(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 Ot;if(h||O instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await O,o.issues.length!==f&&(u||(u=bt(o,f)))});else{if(o.issues.length===f)continue;u||(u=bt(o,f))}}return h?h.then(()=>o):o},a=(o,c,l)=>{if(bt(o))return o.aborted=!0,o;const u=s(c,r,l);if(u instanceof Promise){if(l.async===!1)throw new Ot;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 Ot;return l.then(u=>s(u,r,c))}return s(l,r,c)}}t["~standard"]={validate:s=>{try{const a=pw(t,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return yw(t,s).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),Fs=w("$ZodString",(t,e)=>{Y.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Yw(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}}),B=w("$ZodStringFormat",(t,e)=>{Yn.init(t,e),Fs.init(t,e)}),hb=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Zw),B.init(t,e)}),fb=w("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Ui(r))}else e.pattern??(e.pattern=Ui());B.init(t,e)}),db=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=xw),B.init(t,e)}),pb=w("$ZodURL",(t,e)=>{B.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:Pw.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})}}}),yb=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Rw()),B.init(t,e)}),mb=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=$w),B.init(t,e)}),gb=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ew),B.init(t,e)}),wb=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Nw),B.init(t,e)}),bb=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Sw),B.init(t,e)}),vb=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=kw),B.init(t,e)}),zb=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Aw),B.init(t,e)}),Tb=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Fw(e)),B.init(t,e)}),Ob=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Bw),B.init(t,e)}),Eb=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=qw(e)),B.init(t,e)}),Nb=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Iw),B.init(t,e)}),Sb=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=_w),B.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),kb=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Mw),B.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Ab=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=jw),B.init(t,e)}),$b=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Uw),B.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 qc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const Ib=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Dw),B.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{qc(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Zb(t){if(!jc.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return qc(n)}const xb=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=jc),B.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{Zb(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Cb=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Lw),B.init(t,e)});function Rb(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 _b=w("$ZodJWT",(t,e)=>{B.init(t,e),t._zod.check=n=>{Rb(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Fc=w("$ZodNumber",(t,e)=>{Y.init(t,e),t._zod.pattern=t._zod.bag.pattern??Vw,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}}),Mb=w("$ZodNumber",(t,e)=>{Xw.init(t,e),Fc.init(t,e)}),jb=w("$ZodBoolean",(t,e)=>{Y.init(t,e),t._zod.pattern=Hw,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}}),Ub=w("$ZodUnknown",(t,e)=>{Y.init(t,e),t._zod.parse=n=>n}),Db=w("$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 Di(t,e,n){t.issues.length&&e.issues.push(...Cc(n,t.issues)),e.value[n]=t.value}const Pb=w("$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],l=e.element._zod.run({value:c,issues:[]},r);l instanceof Promise?a.push(l.then(u=>Di(u,n,o))):Di(l,n,o)}return a.length?Promise.all(a).then(()=>n):n}});function In(t,e,n,r){t.issues.length&&e.issues.push(...Cc(n,t.issues)),t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Yc(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=rw(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Gc(t,e,n,r,s,a){const o=[],c=s.keySet,l=s.catchall._zod,u=l.def.type;for(const h of Object.keys(e)){if(c.has(h))continue;if(u==="never"){o.push(h);continue}const d=l.run({value:e[h],issues:[]},r);d instanceof Promise?t.push(d.then(f=>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 Lb=w("$ZodObject",(t,e)=>{if(Y.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=Us(()=>Yc(e));D(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?Gc(h,u,c,l,r.value,t):h.length?Promise.all(h).then(()=>c):c}}),Bb=w("$ZodObjectJIT",(t,e)=>{Lb.init(t,e);const n=t._zod.parse,r=Us(()=>Yc(e)),s=f=>{const O=new ub(["shape","payload","ctx"]),S=r.value,Z=P=>{const R=ji(P);return`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`};O.write("const input = payload.value;");const z=Object.create(null);let E=0;for(const P of S.keys)z[P]=`key_${E++}`;O.write("const newResult = {};");for(const P of S.keys){const R=z[P],j=ji(P);O.write(`const ${R} = ${Z(P)};`),O.write(`
24
+ if (${R}.issues.length) {
25
+ payload.issues = payload.issues.concat(${R}.issues.map(iss => ({
26
26
  ...iss,
27
- path: iss.path ? [${me}, ...iss.path] : [${me}]
27
+ path: iss.path ? [${j}, ...iss.path] : [${j}]
28
28
  })));
29
29
  }
30
30
 
31
31
 
32
- if (${Y}.value === undefined) {
33
- if (${me} in input) {
34
- newResult[${me}] = undefined;
32
+ if (${R}.value === undefined) {
33
+ if (${j} in input) {
34
+ newResult[${j}] = undefined;
35
35
  }
36
36
  } else {
37
- newResult[${me}] = ${Y}.value;
37
+ newResult[${j}] = ${R}.value;
38
38
  }
39
39
 
40
- `)}v.write("payload.value = newResult;"),v.write("return payload;");const A=v.compile();return(G,Y)=>A(f,G,Y)};let a;const o=Mn,c=!Ec.jitless,u=c&&gg.value,h=e.catchall;let d;t._zod.parse=(f,v)=>{d??(d=r.value);const $=f.value;return o($)?c&&u&&v?.async===!1&&v.jitless!==!0?(a||(a=s(e.shape)),f=a(f,v),h?Pc([],$,f,v,d,t):f):n(f,v):(f.issues.push({expected:"object",code:"invalid_type",input:$,inst:t}),f)}});function Ri(t,e,n,r){for(const a of t)if(a.issues.length===0)return e.value=a.value,e;const s=t.filter(a=>!gt(a));return s.length===1?(e.value=s[0].value,s[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(a=>a.issues.map(o=>st(o,r,rt())))}),e)}const ib=y("$ZodUnion",(t,e)=>{V.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=>Ds(a.source)).join("|")})$`)}});const n=e.options.length===1,r=e.options[0]._zod.run;t._zod.parse=(s,a)=>{if(n)return r(s,a);let o=!1;const c=[];for(const l of e.options){const u=l._zod.run({value:s.value,issues:[]},a);if(u instanceof Promise)c.push(u),o=!0;else{if(u.issues.length===0)return u;c.push(u)}}return o?Promise.all(c).then(l=>Ri(l,s,t,a)):Ri(c,s,t,a)}}),ab=y("$ZodIntersection",(t,e)=>{V.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])=>_i(n,l,u)):_i(n,a,o)}});function cs(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(Xt(t)&&Xt(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=cs(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=cs(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 _i(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),gt(t))return t;const r=cs(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 ob=y("$ZodEnum",(t,e)=>{V.init(t,e);const n=yg(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(s=>wg.has(typeof s)).map(s=>typeof s=="string"?Qn(s):s.toString()).join("|")})$`),t._zod.parse=(s,a)=>{const o=s.value;return r.has(o)||s.issues.push({code:"invalid_value",values:n,input:o,inst:t}),s}}),cb=y("$ZodTransform",(t,e)=>{V.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new zc(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 ji(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const ub=y("$ZodOptional",(t,e)=>{V.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(`^(${Ds(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>ji(a,n.value)):ji(s,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),lb=y("$ZodNullable",(t,e)=>{V.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(`^(${Ds(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)}),hb=y("$ZodDefault",(t,e)=>{V.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=>Mi(a,e)):Mi(s,e)}});function Mi(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const fb=y("$ZodPrefault",(t,e)=>{V.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))}),db=y("$ZodNonOptional",(t,e)=>{V.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=>Di(a,t)):Di(s,t)}});function Di(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const pb=y("$ZodCatch",(t,e)=>{V.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=>st(o,r,rt()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(a=>st(a,r,rt()))},input:n.value}),n.issues=[]),n)}}),yb=y("$ZodPipe",(t,e)=>{V.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=>Sn(o,e.in,r)):Sn(a,e.in,r)}const s=e.in._zod.run(n,r);return s instanceof Promise?s.then(a=>Sn(a,e.out,r)):Sn(s,e.out,r)}});function Sn(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const mb=y("$ZodReadonly",(t,e)=>{V.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(Pi):Pi(s)}});function Pi(t){return t.value=Object.freeze(t.value),t}const gb=y("$ZodCustom",(t,e)=>{oe.init(t,e),V.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=>Ui(a,n,r,t));Ui(s,n,r,t)}});function Ui(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(Qt(s))}}class wb{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 bb(){return new wb}const In=bb();function vb(t,e){return new t({type:"string",...I(e)})}function Tb(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function Li(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function Uc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function zb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function Eb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function Nb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function Ob(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function $b(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function Sb(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function Ib(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function Ab(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function kb(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function xb(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function Zb(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function Cb(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function Rb(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function _b(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function jb(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function Mb(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function Db(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function Pb(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function Ub(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function Lb(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function Bb(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function qb(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function Fb(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Vb(t,e){return new t({type:"number",checks:[],...I(e)})}function Yb(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Hb(t,e){return new t({type:"boolean",...I(e)})}function Wb(t){return new t({type:"unknown"})}function Gb(t,e){return new t({type:"never",...I(e)})}function Bi(t,e){return new Rc({check:"less_than",...I(e),value:t,inclusive:!1})}function Or(t,e){return new Rc({check:"less_than",...I(e),value:t,inclusive:!0})}function qi(t,e){return new _c({check:"greater_than",...I(e),value:t,inclusive:!1})}function $r(t,e){return new _c({check:"greater_than",...I(e),value:t,inclusive:!0})}function Fi(t,e){return new dw({check:"multiple_of",...I(e),value:t})}function Lc(t,e){return new yw({check:"max_length",...I(e),maximum:t})}function Pn(t,e){return new mw({check:"min_length",...I(e),minimum:t})}function Bc(t,e){return new gw({check:"length_equals",...I(e),length:t})}function Kb(t,e){return new ww({check:"string_format",format:"regex",...I(e),pattern:t})}function Jb(t){return new bw({check:"string_format",format:"lowercase",...I(t)})}function Xb(t){return new vw({check:"string_format",format:"uppercase",...I(t)})}function Qb(t,e){return new Tw({check:"string_format",format:"includes",...I(e),includes:t})}function ev(t,e){return new zw({check:"string_format",format:"starts_with",...I(e),prefix:t})}function tv(t,e){return new Ew({check:"string_format",format:"ends_with",...I(e),suffix:t})}function un(t){return new Nw({check:"overwrite",tx:t})}function nv(t){return un(e=>e.normalize(t))}function rv(){return un(t=>t.trim())}function sv(){return un(t=>t.toLowerCase())}function iv(){return un(t=>t.toUpperCase())}function av(t,e,n){return new t({type:"array",element:e,...I(n)})}function ov(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}function cv(t){const e=uv(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Qt(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(Qt(s))}},t(n.value,n)));return e}function uv(t,e){const n=new oe({check:"custom",...I(e)});return n._zod.check=t,n}const lv=y("ZodISODateTime",(t,e)=>{Dw.init(t,e),q.init(t,e)});function hv(t){return Lb(lv,t)}const fv=y("ZodISODate",(t,e)=>{Pw.init(t,e),q.init(t,e)});function dv(t){return Bb(fv,t)}const pv=y("ZodISOTime",(t,e)=>{Uw.init(t,e),q.init(t,e)});function yv(t){return qb(pv,t)}const mv=y("ZodISODuration",(t,e)=>{Lw.init(t,e),q.init(t,e)});function gv(t){return Fb(mv,t)}const wv=(t,e)=>{Ic.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Ag(t,n)},flatten:{value:n=>Ig(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,os,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,os,2)}},isEmpty:{get(){return t.issues.length===0}}})},ye=y("ZodError",wv,{Parent:Error}),bv=Us(ye),vv=Ls(ye),Tv=er(ye),zv=tr(ye),Ev=Zg(ye),Nv=Cg(ye),Ov=Rg(ye),$v=_g(ye),Sv=jg(ye),Iv=Mg(ye),Av=Dg(ye),kv=Pg(ye),W=y("ZodType",(t,e)=>(V.init(t,e),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone(ct(e,{checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]})),t.clone=(n,r)=>He(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>bv(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Tv(t,n,r),t.parseAsync=async(n,r)=>vv(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>zv(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>Ev(t,n,r),t.decode=(n,r)=>Nv(t,n,r),t.encodeAsync=async(n,r)=>Ov(t,n,r),t.decodeAsync=async(n,r)=>$v(t,n,r),t.safeEncode=(n,r)=>Sv(t,n,r),t.safeDecode=(n,r)=>Iv(t,n,r),t.safeEncodeAsync=async(n,r)=>Av(t,n,r),t.safeDecodeAsync=async(n,r)=>kv(t,n,r),t.refine=(n,r)=>t.check(zT(n,r)),t.superRefine=n=>t.check(ET(n)),t.overwrite=n=>t.check(un(n)),t.optional=()=>Gi(t),t.nullable=()=>Ki(t),t.nullish=()=>Gi(Ki(t)),t.nonoptional=n=>yT(t,n),t.array=()=>nT(t),t.or=n=>qs([t,n]),t.and=n=>aT(t,n),t.transform=n=>Ji(t,uT(n)),t.default=n=>fT(t,n),t.prefault=n=>pT(t,n),t.catch=n=>gT(t,n),t.pipe=n=>Ji(t,n),t.readonly=()=>vT(t),t.describe=n=>{const r=t.clone();return In.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return In.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return In.get(t);const r=t.clone();return In.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),qc=y("_ZodString",(t,e)=>{Bs.init(t,e),W.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(Kb(...r)),t.includes=(...r)=>t.check(Qb(...r)),t.startsWith=(...r)=>t.check(ev(...r)),t.endsWith=(...r)=>t.check(tv(...r)),t.min=(...r)=>t.check(Pn(...r)),t.max=(...r)=>t.check(Lc(...r)),t.length=(...r)=>t.check(Bc(...r)),t.nonempty=(...r)=>t.check(Pn(1,...r)),t.lowercase=r=>t.check(Jb(r)),t.uppercase=r=>t.check(Xb(r)),t.trim=()=>t.check(rv()),t.normalize=(...r)=>t.check(nv(...r)),t.toLowerCase=()=>t.check(sv()),t.toUpperCase=()=>t.check(iv())}),xv=y("ZodString",(t,e)=>{Bs.init(t,e),qc.init(t,e),t.email=n=>t.check(Tb(Zv,n)),t.url=n=>t.check(Ob(Rv,n)),t.jwt=n=>t.check(Ub(Gv,n)),t.emoji=n=>t.check($b(_v,n)),t.guid=n=>t.check(Li(Vi,n)),t.uuid=n=>t.check(Uc(Bt,n)),t.uuidv4=n=>t.check(zb(Bt,n)),t.uuidv6=n=>t.check(Eb(Bt,n)),t.uuidv7=n=>t.check(Nb(Bt,n)),t.nanoid=n=>t.check(Sb(jv,n)),t.guid=n=>t.check(Li(Vi,n)),t.cuid=n=>t.check(Ib(Mv,n)),t.cuid2=n=>t.check(Ab(Dv,n)),t.ulid=n=>t.check(kb(Pv,n)),t.base64=n=>t.check(Mb(Yv,n)),t.base64url=n=>t.check(Db(Hv,n)),t.xid=n=>t.check(xb(Uv,n)),t.ksuid=n=>t.check(Zb(Lv,n)),t.ipv4=n=>t.check(Cb(Bv,n)),t.ipv6=n=>t.check(Rb(qv,n)),t.cidrv4=n=>t.check(_b(Fv,n)),t.cidrv6=n=>t.check(jb(Vv,n)),t.e164=n=>t.check(Pb(Wv,n)),t.datetime=n=>t.check(hv(n)),t.date=n=>t.check(dv(n)),t.time=n=>t.check(yv(n)),t.duration=n=>t.check(gv(n))});function pe(t){return vb(xv,t)}const q=y("ZodStringFormat",(t,e)=>{L.init(t,e),qc.init(t,e)}),Zv=y("ZodEmail",(t,e)=>{Aw.init(t,e),q.init(t,e)}),Vi=y("ZodGUID",(t,e)=>{Sw.init(t,e),q.init(t,e)}),Bt=y("ZodUUID",(t,e)=>{Iw.init(t,e),q.init(t,e)});function Cv(t){return Uc(Bt,t)}const Rv=y("ZodURL",(t,e)=>{kw.init(t,e),q.init(t,e)}),_v=y("ZodEmoji",(t,e)=>{xw.init(t,e),q.init(t,e)}),jv=y("ZodNanoID",(t,e)=>{Zw.init(t,e),q.init(t,e)}),Mv=y("ZodCUID",(t,e)=>{Cw.init(t,e),q.init(t,e)}),Dv=y("ZodCUID2",(t,e)=>{Rw.init(t,e),q.init(t,e)}),Pv=y("ZodULID",(t,e)=>{_w.init(t,e),q.init(t,e)}),Uv=y("ZodXID",(t,e)=>{jw.init(t,e),q.init(t,e)}),Lv=y("ZodKSUID",(t,e)=>{Mw.init(t,e),q.init(t,e)}),Bv=y("ZodIPv4",(t,e)=>{Bw.init(t,e),q.init(t,e)}),qv=y("ZodIPv6",(t,e)=>{qw.init(t,e),q.init(t,e)}),Fv=y("ZodCIDRv4",(t,e)=>{Fw.init(t,e),q.init(t,e)}),Vv=y("ZodCIDRv6",(t,e)=>{Vw.init(t,e),q.init(t,e)}),Yv=y("ZodBase64",(t,e)=>{Yw.init(t,e),q.init(t,e)}),Hv=y("ZodBase64URL",(t,e)=>{Ww.init(t,e),q.init(t,e)}),Wv=y("ZodE164",(t,e)=>{Gw.init(t,e),q.init(t,e)}),Gv=y("ZodJWT",(t,e)=>{Jw.init(t,e),q.init(t,e)}),Fc=y("ZodNumber",(t,e)=>{Mc.init(t,e),W.init(t,e),t.gt=(r,s)=>t.check(qi(r,s)),t.gte=(r,s)=>t.check($r(r,s)),t.min=(r,s)=>t.check($r(r,s)),t.lt=(r,s)=>t.check(Bi(r,s)),t.lte=(r,s)=>t.check(Or(r,s)),t.max=(r,s)=>t.check(Or(r,s)),t.int=r=>t.check(Hi(r)),t.safe=r=>t.check(Hi(r)),t.positive=r=>t.check(qi(0,r)),t.nonnegative=r=>t.check($r(0,r)),t.negative=r=>t.check(Bi(0,r)),t.nonpositive=r=>t.check(Or(0,r)),t.multipleOf=(r,s)=>t.check(Fi(r,s)),t.step=(r,s)=>t.check(Fi(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});function Yi(t){return Vb(Fc,t)}const Kv=y("ZodNumberFormat",(t,e)=>{Xw.init(t,e),Fc.init(t,e)});function Hi(t){return Yb(Kv,t)}const Jv=y("ZodBoolean",(t,e)=>{Qw.init(t,e),W.init(t,e)});function ln(t){return Hb(Jv,t)}const Xv=y("ZodUnknown",(t,e)=>{eb.init(t,e),W.init(t,e)});function Wi(){return Wb(Xv)}const Qv=y("ZodNever",(t,e)=>{tb.init(t,e),W.init(t,e)});function eT(t){return Gb(Qv,t)}const tT=y("ZodArray",(t,e)=>{nb.init(t,e),W.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Pn(n,r)),t.nonempty=n=>t.check(Pn(1,n)),t.max=(n,r)=>t.check(Lc(n,r)),t.length=(n,r)=>t.check(Bc(n,r)),t.unwrap=()=>t.element});function nT(t,e){return av(tT,t,e)}const rT=y("ZodObject",(t,e)=>{sb.init(t,e),W.init(t,e),U(t,"shape",()=>e.shape),t.keyof=()=>oT(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Wi()}),t.loose=()=>t.clone({...t._zod.def,catchall:Wi()}),t.strict=()=>t.clone({...t._zod.def,catchall:eT()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Eg(t,n),t.safeExtend=n=>Ng(t,n),t.merge=n=>Og(t,n),t.pick=n=>Tg(t,n),t.omit=n=>zg(t,n),t.partial=(...n)=>$g(Vc,t,n[0]),t.required=(...n)=>Sg(Yc,t,n[0])});function ne(t,e){const n={type:"object",shape:t??{},...I(e)};return new rT(n)}const sT=y("ZodUnion",(t,e)=>{ib.init(t,e),W.init(t,e),t.options=e.options});function qs(t,e){return new sT({type:"union",options:t,...I(e)})}const iT=y("ZodIntersection",(t,e)=>{ab.init(t,e),W.init(t,e)});function aT(t,e){return new iT({type:"intersection",left:t,right:e})}const us=y("ZodEnum",(t,e)=>{ob.init(t,e),W.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 us({...e,checks:[],...I(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 us({...e,checks:[],...I(s),entries:a})}});function oT(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new us({type:"enum",entries:n,...I(e)})}const cT=y("ZodTransform",(t,e)=>{cb.init(t,e),W.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new zc(t.constructor.name);n.addIssue=a=>{if(typeof a=="string")n.issues.push(Qt(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(Qt(o))}};const s=e.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function uT(t){return new cT({type:"transform",transform:t})}const Vc=y("ZodOptional",(t,e)=>{ub.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Gi(t){return new Vc({type:"optional",innerType:t})}const lT=y("ZodNullable",(t,e)=>{lb.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ki(t){return new lT({type:"nullable",innerType:t})}const hT=y("ZodDefault",(t,e)=>{hb.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function fT(t,e){return new hT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Oc(e)}})}const dT=y("ZodPrefault",(t,e)=>{fb.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType});function pT(t,e){return new dT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Oc(e)}})}const Yc=y("ZodNonOptional",(t,e)=>{db.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType});function yT(t,e){return new Yc({type:"nonoptional",innerType:t,...I(e)})}const mT=y("ZodCatch",(t,e)=>{pb.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function gT(t,e){return new mT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const wT=y("ZodPipe",(t,e)=>{yb.init(t,e),W.init(t,e),t.in=e.in,t.out=e.out});function Ji(t,e){return new wT({type:"pipe",in:t,out:e})}const bT=y("ZodReadonly",(t,e)=>{mb.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType});function vT(t){return new bT({type:"readonly",innerType:t})}const TT=y("ZodCustom",(t,e)=>{gb.init(t,e),W.init(t,e)});function zT(t,e={}){return ov(TT,t,e)}function ET(t){return cv(t)}const rr=i.z.string(),hn=t=>Zt.statusZ(t),Hc=t=>hn(t).omit({labels:!0}).partial({key:!0}),NT="sy_status_set",OT="sy_status_delete",$T=t=>({type:"status",key:t}),ke=t=>t?JSON.parse(t):{},Fs=ne({key:pe(),type:pe(),config:ve.unknownZ.or(pe().transform(ke))}),Wc=Fs.extend({position:Is.xy}),ls=ne({param:pe(),node:pe()}),Vs=ne({source:ls,target:ls}),ST=ne({nodes:Fs.array(),edges:Vs.array()}),Gc=ne({nodes:Wc.array(),edges:Vs.array()}),Kc=ne({raw:pe()}),fn=Cv(),Jc=ne({running:ln()}),Xc=hn(Jc),sr=ne({key:fn,name:pe(),graph:Gc,text:Kc,deploy:ln(),version:pe(),status:Xc.optional().nullable()}),Qc=sr.partial({key:!0}).omit({status:!0}),eu="arc",IT=(t,e,{convertNumericStrings:n=!0}={})=>{const r=!Array.isArray(t);let s=T.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}},ue=(t,e,n,r)=>{if(r){if(n.length===0)throw new Kt(`${t} not found matching ${JSON.stringify(e)}`);if(n.length>1)throw new Jt(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${n.length}`)}},AT="sy_arc_set",kT="sy_arc_delete",xT="/arc/retrieve",ZT="/arc/create",CT="/arc/delete",RT="/arc/lsp",_T=ne({keys:fn.array().optional(),names:pe().array().optional(),searchTerm:pe().optional(),limit:Yi().optional(),offset:Yi().optional(),includeStatus:ln().optional()}),jT=ne({arcs:Qc.array()}),MT=ne({keys:fn.array()}),DT=ne({arcs:T.nullableZ(sr)}),PT=ne({arcs:sr.array()}),UT=ne({}),hs=ne({content:pe()}),LT=ne({key:fn,includeStatus:ln().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),BT=ne({name:pe(),includeStatus:ln().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),tu=qs([LT,BT]),qT=qs([tu,_T]);let nu=class{client;streamClient;constructor(e,n){this.client=e,this.streamClient=n}async create(e){const n=Array.isArray(e),r=await w(this.client,ZT,{arcs:T.toArray(e)},jT,PT);return n?r.arcs:r.arcs[0]}async retrieve(e){const n="key"in e||"name"in e,r=await w(this.client,xT,e,qT,DT);return ue("Arc",e,r.arcs,n),n?r.arcs[0]:r.arcs}async delete(e){await w(this.client,CT,{keys:T.toArray(e)},MT,UT)}async openLSP(){return await this.streamClient.stream(RT,hs,hs)}};const FT=t=>({type:eu,key:t}),VT=Object.freeze(Object.defineProperty({__proto__:null,Client:nu,DELETE_CHANNEL_NAME:kT,ONTOLOGY_TYPE:eu,SET_CHANNEL_NAME:AT,arcZ:sr,edgeZ:Vs,graphNodeZ:Wc,graphZ:Gc,handleZ:ls,irNodeZ:Fs,irZ:ST,keyZ:fn,lspMessageZ:hs,newZ:Qc,ontologyID:FT,singleRetrieveArgsZ:tu,statusDetailsZ:Jc,statusZ:Xc,textZ:Kc},Symbol.toStringTag,{value:"Module"})),Xi="Channel key must be a valid uint32.",D=i.z.uint32().or(i.z.string().refine(t=>!isNaN(Number(t)),{message:Xi}).transform(Number).refine(t=>t<Xr.MAX_UINT32,{message:Xi})),Re=i.z.string(),ru=["min","max","avg","none"],su=i.z.enum(ru),Ys=i.z.object({type:su,resetChannel:D.optional(),duration:S.z.optional()}),iu=Zt.statusZ(),Rt=i.z.object({name:Re,key:D,dataType:R.z,leaseholder:i.z.number(),index:D,isIndex:i.z.boolean(),internal:i.z.boolean(),virtual:i.z.boolean(),alias:i.z.string().optional(),expression:i.z.string().default(""),status:iu.optional(),operations:T.nullableZ(Ys),requires:T.nullableZ(D)}),au=Rt.extend({key:D.optional(),leaseholder:i.z.number().optional(),index:D.optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional().default(!1),virtual:i.z.boolean().optional().default(!1),expression:i.z.string().optional().default(""),operations:T.nullableZ(Ys).optional(),requires:T.nullableZ(D).optional()}),ut=i.z.union([qt.toArray(D),qt.toArray(Re),qt.toArray(Rt).transform(t=>t.map(e=>e.key))]),YT=new Error("request for lock canceled");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 WT{constructor(e,n=YT){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=ou(this._queue,c=>n<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return HT(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=ou(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function ou(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var KT=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 JT{constructor(e){this._semaphore=new WT(1,e)}acquire(){return KT(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 XT=i.z.object({leaseholder:i.z.number().optional(),keys:D.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),rangeKey:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),dataTypes:R.z.array().optional(),notDataTypes:R.z.array().optional(),virtual:i.z.boolean().optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional(),calculated:i.z.boolean().optional(),legacyCalculated:i.z.boolean().optional()}),QT=i.z.object({channels:T.nullableZ(Rt)}),we=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]),IT(t,{number:"keys",string:"names"}));class dn{static ENDPOINT="/channel/retrieve";client;constructor(e){this.client=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const r=we(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){const[n,r]=await this.client.send(dn.ENDPOINT,e,XT,QT);if(r!=null)throw r;return n.channels}}class Hs{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}=we(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}=we(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 cu{mu=new JT;requests=new Map;wrapped;debouncedRun;constructor(e,n){this.wrapped=e,this.debouncedRun=Qp(()=>{this.run()},n)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n,variant:r}=we(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 uu=async(t,e)=>{const{normalized:n}=we(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 Ye(`Could not find channels: ${JSON.stringify(s)}`);return r},ez="sy_channel_set",tz="sy_channel_delete";class Un{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;operations;requires;status;constructor({dataType:e,name:n,leaseholder:r=0,key:s=0,isIndex:a=!1,index:o=0,internal:c=!1,virtual:l=!1,frameClient:u,alias:h,status:d,expression:f="",operations:v=[],requires:$=[]}){this.key=D.parse(s),this.name=n,this.dataType=new R(e),this.leaseholder=r,this.index=D.parse(o),this.isIndex=a,this.internal=c,this.alias=h,this.virtual=l,this.expression=f,this.operations=v,this.requires=$,d!=null&&(this.status=Zt.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 Rt.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,requires:this.requires,expression:this.expression,status:this.status,operations:this.operations})}get isCalculated(){return St(this.payload)}get ontologyID(){return hu(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 nz="sy_calculation_status",rz="/channel/retrieve-group",sz=i.z.object({}),iz=i.z.object({group:Kn});let lu=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=T.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 ue("channel",e,s,r),r?s[0]:s}async delete(e){const{normalized:n,variant:r}=we(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(T.toArray(e),T.toArray(n))}createDebouncedBatchRetriever(e=10){return new Hs(new cu(new dn(this.client),e))}sugar(e){const{frameClient:n}=this;return Array.isArray(e)?e.map(r=>new Un({...r,frameClient:n})):new Un({...e,frameClient:n})}async retrieveGroup(){return(await w(this.client,rz,{},sz,iz)).group}};const St=({virtual:t,expression:e})=>t&&e!=="",az=t=>St(t)&&t.requires.length>0,hu=t=>({type:"channel",key:t.toString()}),fu=async(t,e)=>{if(!St(e))return e.index;for(const n of e.requires){const r=await t(n);if(r==null)return null;if(!r.virtual)return r.index}for(const n of e.requires){const r=await t(n);if(r==null)return null;if(St(r)){const s=await fu(t,r);if(s!=null)return s}}return null},oz=i.z.object({channels:au.array()}),cz=i.z.object({channels:Rt.array()}),uz=i.z.object({keys:D.array().optional(),names:Re.array().optional()}),lz=i.z.object({}),hz=i.z.object({keys:D.array(),names:Re.array()}),fz=i.z.object({}),dz="/channel/create",pz="/channel/delete",yz="/channel/rename";let du=class{client;cache;constructor(e,n){this.client=e,this.cache=n}async create(e){const{channels:n}=await w(this.client,dz,{channels:e.map(r=>({...r,dataType:r.dataType}))},oz,cz);return this.cache.set(n),n}async delete(e){const n=D.array().parse(e.keys??[]);await w(this.client,pz,e,uz,lz),n.length>0&&this.cache.delete(n),e.names!=null&&this.cache.delete(e.names)}async rename(e,n){await w(this.client,yz,{keys:e,names:n},hz,fz),this.cache.rename(e,n)}};const mz=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:nz,CacheRetriever:Hs,Channel:Un,Client:lu,ClusterRetriever:dn,DELETE_CHANNEL_NAME:tz,DebouncedBatchRetriever:cu,OPERATION_TYPES:ru,SET_CHANNEL_NAME:ez,Writer:du,analyzeParams:we,isCalculated:St,isLegacyCalculated:az,keyZ:D,nameZ:Re,newZ:au,ontologyID:hu,operationType:su,operationZ:Ys,paramsZ:ut,payloadZ:Rt,resolveLegacyCalculatedIndex:fu,retrieveRequired:uu,statusZ:iu},Symbol.toStringTag,{value:"Module"})),We=i.z.uuid(),pn=i.z.object({key:We,username:i.z.string().min(1,"Username is required"),firstName:i.z.string().default(""),lastName:i.z.string().default(""),rootUser:i.z.boolean().default(!0)}),pu=pn.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:i.z.string().min(1)}),gz=i.z.object({keys:We.array().optional(),usernames:i.z.string().array().optional()}),wz=i.z.object({key:We}).transform(({key:t})=>({keys:[t]})),bz=i.z.object({username:i.z.string()}).transform(({username:t})=>({usernames:[t]})),vz=i.z.object({usernames:i.z.string().array()}).transform(({usernames:t})=>({usernames:t})),Tz=i.z.union([wz,bz,vz,gz]),zz=i.z.object({users:T.nullableZ(pn)}),Ez=i.z.object({users:pu.array()}),Nz=i.z.object({users:pn.array()}),Oz=i.z.object({key:We,username:i.z.string().min(1)}),$z=i.z.object({}),Sz=i.z.object({key:We,firstName:i.z.string().optional(),lastName:i.z.string().optional()}),Iz=i.z.object({}),Az=i.z.object({keys:We.array()}),kz=i.z.object({}),xz="/user/retrieve",Zz="/user/create",Cz="/user/change-username",Rz="/user/rename",_z="/user/delete";let yu=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await w(this.client,Zz,{users:T.toArray(e)},Ez,Nz);return n?r.users:r.users[0]}async changeUsername(e,n){await w(this.client,Cz,{key:e,username:n},Oz,$z)}async retrieve(e){const n="key"in e||"username"in e,r=await w(this.client,xz,e,Tz,zz);if(!n)return r.users;if(r.users.length===0){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new Kt(`No user with ${s} found`)}if(r.users.length>1){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new Jt(`Multiple users found with ${s}`)}return r.users[0]}async rename(e,n,r){await w(this.client,Rz,{key:e,firstName:n,lastName:r},Sz,Iz)}async delete(e){await w(this.client,_z,{keys:T.toArray(e)},Az,kz)}};const jz=t=>({type:"user",key:t}),Mz=Object.freeze(Object.defineProperty({__proto__:null,Client:yu,keyZ:We,newZ:pu,ontologyID:jz,userZ:pn},Symbol.toStringTag,{value:"Module"})),Dz=i.z.object({username:i.z.string(),password:i.z.string()}),Pz=i.z.object({token:i.z.string(),user:pn}),Qi="/auth/login",Uz=3,Lz="/auth/change-password",Bz=i.z.object({username:i.z.string(),password:i.z.string(),newPassword:i.z.string().min(1)}),qz=i.z.object({}),Fz=[rs,ss];let Vz=class{token;client;credentials;authenticating;authenticated;user;retryCount;constructor(e,n){this.client=e,this.authenticated=!1,this.credentials=n,this.retryCount=0}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await w(this.client,Lz,{username:this.credentials.username,password:this.credentials.password,newPassword:e},Bz,qz),this.credentials.password=e}middleware(){const e=async(n,r)=>{if(!this.authenticated&&!n.target.endsWith(Qi)){this.authenticating??=new Promise((c,l)=>{this.client.send(Qi,this.credentials,Dz,Pz).then(([u,h])=>{if(h!=null)return c(h);this.token=u?.token,this.user=u?.user,this.authenticated=!0,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 Fz.some(o=>o.matches(a))&&this.retryCount<Uz?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(n,r)):(this.retryCount=0,[s,a])};return e}};const mu=i.z.enum(["disconnected","connecting","connected","failed"]),gu=i.z.object({status:mu,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()}),Yz=i.z.object({clusterKey:i.z.string(),nodeVersion:i.z.string().optional()}),Hz=i.z.void(),ea={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.48.0"},ta=(t,e,n)=>{const r=n?"Core":"client";return`Synnax Core version ${t!=null?`${t} `:""}is too ${n?"old":"new"} for client version ${e}.
40
+ `)}O.write("payload.value = newResult;"),O.write("return payload;");const A=O.compile();return(P,R)=>A(f,P,R)};let a;const o=$n,c=!Ic.jitless,u=c&&tw.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?Gc([],S,f,O,d,t):f):n(f,O):(f.issues.push({expected:"object",code:"invalid_type",input:S,inst:t}),f)}});function Pi(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=>!bt(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=>at(o,r,it())))}),e)}const qb=w("$ZodUnion",(t,e)=>{Y.init(t,e),D(t._zod,"optin",()=>e.options.some(s=>s._zod.optin==="optional")?"optional":void 0),D(t._zod,"optout",()=>e.options.some(s=>s._zod.optout==="optional")?"optional":void 0),D(t._zod,"values",()=>{if(e.options.every(s=>s._zod.values))return new Set(e.options.flatMap(s=>Array.from(s._zod.values)))}),D(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=>Ps(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=>Pi(l,s,t,a)):Pi(c,s,t,a)}}),Fb=w("$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(([l,u])=>Li(n,l,u)):Li(n,a,o)}});function Jr(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(Vt(t)&&Vt(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=Jr(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=Jr(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 Li(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),bt(t))return t;const r=Jr(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 Yb=w("$ZodEnum",(t,e)=>{Y.init(t,e);const n=Qg(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(s=>nw.has(typeof s)).map(s=>typeof s=="string"?Bn(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}}),Gb=w("$ZodTransform",(t,e)=>{Y.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 Ot;return n.value=s,n}});function Bi(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const Vb=w("$ZodOptional",(t,e)=>{Y.init(t,e),t._zod.optin="optional",t._zod.optout="optional",D(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),D(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ps(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=>Bi(a,n.value)):Bi(s,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),Hb=w("$ZodNullable",(t,e)=>{Y.init(t,e),D(t._zod,"optin",()=>e.innerType._zod.optin),D(t._zod,"optout",()=>e.innerType._zod.optout),D(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ps(n.source)}|null)$`):void 0}),D(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)}),Wb=w("$ZodDefault",(t,e)=>{Y.init(t,e),t._zod.optin="optional",D(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=>qi(a,e)):qi(s,e)}});function qi(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const Kb=w("$ZodPrefault",(t,e)=>{Y.init(t,e),t._zod.optin="optional",D(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))}),Jb=w("$ZodNonOptional",(t,e)=>{Y.init(t,e),D(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=>Fi(a,t)):Fi(s,t)}});function Fi(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 Xb=w("$ZodCatch",(t,e)=>{Y.init(t,e),D(t._zod,"optin",()=>e.innerType._zod.optin),D(t._zod,"optout",()=>e.innerType._zod.optout),D(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=>at(o,r,it()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(a=>at(a,r,it()))},input:n.value}),n.issues=[]),n)}}),Qb=w("$ZodPipe",(t,e)=>{Y.init(t,e),D(t._zod,"values",()=>e.in._zod.values),D(t._zod,"optin",()=>e.in._zod.optin),D(t._zod,"optout",()=>e.out._zod.optout),D(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 ev=w("$ZodReadonly",(t,e)=>{Y.init(t,e),D(t._zod,"propValues",()=>e.innerType._zod.propValues),D(t._zod,"values",()=>e.innerType._zod.values),D(t._zod,"optin",()=>e.innerType._zod.optin),D(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(Yi):Yi(s)}});function Yi(t){return t.value=Object.freeze(t.value),t}const tv=w("$ZodCustom",(t,e)=>{ne.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=>Gi(a,n,r,t));Gi(s,n,r,t)}});function Gi(t,e,n,r){if(!t){const s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),e.issues.push(Ht(s))}}class nv{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 rv(){return new nv}const En=rv();function sv(t,e){return new t({type:"string",...k(e)})}function iv(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...k(e)})}function Vi(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...k(e)})}function Vc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...k(e)})}function av(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...k(e)})}function ov(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...k(e)})}function cv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...k(e)})}function uv(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...k(e)})}function lv(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...k(e)})}function hv(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...k(e)})}function fv(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...k(e)})}function dv(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...k(e)})}function pv(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...k(e)})}function yv(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...k(e)})}function mv(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...k(e)})}function gv(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...k(e)})}function wv(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...k(e)})}function bv(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...k(e)})}function vv(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...k(e)})}function zv(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...k(e)})}function Tv(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...k(e)})}function Ov(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...k(e)})}function Ev(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...k(e)})}function Nv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...k(e)})}function Sv(t,e){return new t({type:"string",format:"date",check:"string_format",...k(e)})}function kv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...k(e)})}function Av(t,e){return new t({type:"string",format:"duration",check:"string_format",...k(e)})}function $v(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...k(e)})}function Iv(t,e){return new t({type:"boolean",...k(e)})}function Zv(t){return new t({type:"unknown"})}function xv(t,e){return new t({type:"never",...k(e)})}function Hi(t,e){return new Lc({check:"less_than",...k(e),value:t,inclusive:!1})}function pr(t,e){return new Lc({check:"less_than",...k(e),value:t,inclusive:!0})}function Wi(t,e){return new Bc({check:"greater_than",...k(e),value:t,inclusive:!1})}function yr(t,e){return new Bc({check:"greater_than",...k(e),value:t,inclusive:!0})}function Ki(t,e){return new Jw({check:"multiple_of",...k(e),value:t})}function Hc(t,e){return new Qw({check:"max_length",...k(e),maximum:t})}function Zn(t,e){return new eb({check:"min_length",...k(e),minimum:t})}function Wc(t,e){return new tb({check:"length_equals",...k(e),length:t})}function Cv(t,e){return new nb({check:"string_format",format:"regex",...k(e),pattern:t})}function Rv(t){return new rb({check:"string_format",format:"lowercase",...k(t)})}function _v(t){return new sb({check:"string_format",format:"uppercase",...k(t)})}function Mv(t,e){return new ib({check:"string_format",format:"includes",...k(e),includes:t})}function jv(t,e){return new ab({check:"string_format",format:"starts_with",...k(e),prefix:t})}function Uv(t,e){return new ob({check:"string_format",format:"ends_with",...k(e),suffix:t})}function an(t){return new cb({check:"overwrite",tx:t})}function Dv(t){return an(e=>e.normalize(t))}function Pv(){return an(t=>t.trim())}function Lv(){return an(t=>t.toLowerCase())}function Bv(){return an(t=>t.toUpperCase())}function qv(t,e,n){return new t({type:"array",element:e,...k(n)})}function Fv(t,e,n){return new t({type:"custom",check:"custom",fn:e,...k(n)})}function Yv(t){const e=Gv(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Ht(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(Ht(s))}},t(n.value,n)));return e}function Gv(t,e){const n=new ne({check:"custom",...k(e)});return n._zod.check=t,n}const Vv=w("ZodISODateTime",(t,e)=>{Tb.init(t,e),q.init(t,e)});function Hv(t){return Nv(Vv,t)}const Wv=w("ZodISODate",(t,e)=>{Ob.init(t,e),q.init(t,e)});function Kv(t){return Sv(Wv,t)}const Jv=w("ZodISOTime",(t,e)=>{Eb.init(t,e),q.init(t,e)});function Xv(t){return kv(Jv,t)}const Qv=w("ZodISODuration",(t,e)=>{Nb.init(t,e),q.init(t,e)});function ez(t){return Av(Qv,t)}const tz=(t,e)=>{_c.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>dw(t,n)},flatten:{value:n=>fw(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Kr,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Kr,2)}},isEmpty:{get(){return t.issues.length===0}}})},he=w("ZodError",tz,{Parent:Error}),nz=Bs(he),rz=qs(he),sz=qn(he),iz=Fn(he),az=mw(he),oz=gw(he),cz=ww(he),uz=bw(he),lz=vw(he),hz=zw(he),fz=Tw(he),dz=Ow(he),W=w("ZodType",(t,e)=>(Y.init(t,e),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone(ft(e,{checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]})),t.clone=(n,r)=>He(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>nz(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>sz(t,n,r),t.parseAsync=async(n,r)=>rz(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>iz(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>az(t,n,r),t.decode=(n,r)=>oz(t,n,r),t.encodeAsync=async(n,r)=>cz(t,n,r),t.decodeAsync=async(n,r)=>uz(t,n,r),t.safeEncode=(n,r)=>lz(t,n,r),t.safeDecode=(n,r)=>hz(t,n,r),t.safeEncodeAsync=async(n,r)=>fz(t,n,r),t.safeDecodeAsync=async(n,r)=>dz(t,n,r),t.refine=(n,r)=>t.check(aT(n,r)),t.superRefine=n=>t.check(oT(n)),t.overwrite=n=>t.check(an(n)),t.optional=()=>Qi(t),t.nullable=()=>ea(t),t.nullish=()=>Qi(ea(t)),t.nonoptional=n=>Qz(t,n),t.array=()=>Pz(t),t.or=n=>Ys([t,n]),t.and=n=>Fz(t,n),t.transform=n=>ta(t,Vz(n)),t.default=n=>Kz(t,n),t.prefault=n=>Xz(t,n),t.catch=n=>tT(t,n),t.pipe=n=>ta(t,n),t.readonly=()=>sT(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)),Kc=w("_ZodString",(t,e)=>{Fs.init(t,e),W.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(Cv(...r)),t.includes=(...r)=>t.check(Mv(...r)),t.startsWith=(...r)=>t.check(jv(...r)),t.endsWith=(...r)=>t.check(Uv(...r)),t.min=(...r)=>t.check(Zn(...r)),t.max=(...r)=>t.check(Hc(...r)),t.length=(...r)=>t.check(Wc(...r)),t.nonempty=(...r)=>t.check(Zn(1,...r)),t.lowercase=r=>t.check(Rv(r)),t.uppercase=r=>t.check(_v(r)),t.trim=()=>t.check(Pv()),t.normalize=(...r)=>t.check(Dv(...r)),t.toLowerCase=()=>t.check(Lv()),t.toUpperCase=()=>t.check(Bv())}),pz=w("ZodString",(t,e)=>{Fs.init(t,e),Kc.init(t,e),t.email=n=>t.check(iv(yz,n)),t.url=n=>t.check(uv(gz,n)),t.jwt=n=>t.check(Ev(xz,n)),t.emoji=n=>t.check(lv(wz,n)),t.guid=n=>t.check(Vi(Ji,n)),t.uuid=n=>t.check(Vc(Dt,n)),t.uuidv4=n=>t.check(av(Dt,n)),t.uuidv6=n=>t.check(ov(Dt,n)),t.uuidv7=n=>t.check(cv(Dt,n)),t.nanoid=n=>t.check(hv(bz,n)),t.guid=n=>t.check(Vi(Ji,n)),t.cuid=n=>t.check(fv(vz,n)),t.cuid2=n=>t.check(dv(zz,n)),t.ulid=n=>t.check(pv(Tz,n)),t.base64=n=>t.check(zv($z,n)),t.base64url=n=>t.check(Tv(Iz,n)),t.xid=n=>t.check(yv(Oz,n)),t.ksuid=n=>t.check(mv(Ez,n)),t.ipv4=n=>t.check(gv(Nz,n)),t.ipv6=n=>t.check(wv(Sz,n)),t.cidrv4=n=>t.check(bv(kz,n)),t.cidrv6=n=>t.check(vv(Az,n)),t.e164=n=>t.check(Ov(Zz,n)),t.datetime=n=>t.check(Hv(n)),t.date=n=>t.check(Kv(n)),t.time=n=>t.check(Xv(n)),t.duration=n=>t.check(ez(n))});function le(t){return sv(pz,t)}const q=w("ZodStringFormat",(t,e)=>{B.init(t,e),Kc.init(t,e)}),yz=w("ZodEmail",(t,e)=>{db.init(t,e),q.init(t,e)}),Ji=w("ZodGUID",(t,e)=>{hb.init(t,e),q.init(t,e)}),Dt=w("ZodUUID",(t,e)=>{fb.init(t,e),q.init(t,e)});function mz(t){return Vc(Dt,t)}const gz=w("ZodURL",(t,e)=>{pb.init(t,e),q.init(t,e)}),wz=w("ZodEmoji",(t,e)=>{yb.init(t,e),q.init(t,e)}),bz=w("ZodNanoID",(t,e)=>{mb.init(t,e),q.init(t,e)}),vz=w("ZodCUID",(t,e)=>{gb.init(t,e),q.init(t,e)}),zz=w("ZodCUID2",(t,e)=>{wb.init(t,e),q.init(t,e)}),Tz=w("ZodULID",(t,e)=>{bb.init(t,e),q.init(t,e)}),Oz=w("ZodXID",(t,e)=>{vb.init(t,e),q.init(t,e)}),Ez=w("ZodKSUID",(t,e)=>{zb.init(t,e),q.init(t,e)}),Nz=w("ZodIPv4",(t,e)=>{Sb.init(t,e),q.init(t,e)}),Sz=w("ZodIPv6",(t,e)=>{kb.init(t,e),q.init(t,e)}),kz=w("ZodCIDRv4",(t,e)=>{Ab.init(t,e),q.init(t,e)}),Az=w("ZodCIDRv6",(t,e)=>{$b.init(t,e),q.init(t,e)}),$z=w("ZodBase64",(t,e)=>{Ib.init(t,e),q.init(t,e)}),Iz=w("ZodBase64URL",(t,e)=>{xb.init(t,e),q.init(t,e)}),Zz=w("ZodE164",(t,e)=>{Cb.init(t,e),q.init(t,e)}),xz=w("ZodJWT",(t,e)=>{_b.init(t,e),q.init(t,e)}),Cz=w("ZodNumber",(t,e)=>{Fc.init(t,e),W.init(t,e),t.gt=(r,s)=>t.check(Wi(r,s)),t.gte=(r,s)=>t.check(yr(r,s)),t.min=(r,s)=>t.check(yr(r,s)),t.lt=(r,s)=>t.check(Hi(r,s)),t.lte=(r,s)=>t.check(pr(r,s)),t.max=(r,s)=>t.check(pr(r,s)),t.int=r=>t.check(xn(r)),t.safe=r=>t.check(xn(r)),t.positive=r=>t.check(Wi(0,r)),t.nonnegative=r=>t.check(yr(0,r)),t.negative=r=>t.check(Hi(0,r)),t.nonpositive=r=>t.check(pr(0,r)),t.multipleOf=(r,s)=>t.check(Ki(r,s)),t.step=(r,s)=>t.check(Ki(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}),Rz=w("ZodNumberFormat",(t,e)=>{Mb.init(t,e),Cz.init(t,e)});function xn(t){return $v(Rz,t)}const _z=w("ZodBoolean",(t,e)=>{jb.init(t,e),W.init(t,e)});function on(t){return Iv(_z,t)}const Mz=w("ZodUnknown",(t,e)=>{Ub.init(t,e),W.init(t,e)});function Xi(){return Zv(Mz)}const jz=w("ZodNever",(t,e)=>{Db.init(t,e),W.init(t,e)});function Uz(t){return xv(jz,t)}const Dz=w("ZodArray",(t,e)=>{Pb.init(t,e),W.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(Hc(n,r)),t.length=(n,r)=>t.check(Wc(n,r)),t.unwrap=()=>t.element});function Pz(t,e){return qv(Dz,t,e)}const Lz=w("ZodObject",(t,e)=>{Bb.init(t,e),W.init(t,e),D(t,"shape",()=>e.shape),t.keyof=()=>Yz(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Xi()}),t.loose=()=>t.clone({...t._zod.def,catchall:Xi()}),t.strict=()=>t.clone({...t._zod.def,catchall:Uz()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>ow(t,n),t.safeExtend=n=>cw(t,n),t.merge=n=>uw(t,n),t.pick=n=>iw(t,n),t.omit=n=>aw(t,n),t.partial=(...n)=>lw(Jc,t,n[0]),t.required=(...n)=>hw(Xc,t,n[0])});function te(t,e){const n={type:"object",shape:t??{},...k(e)};return new Lz(n)}const Bz=w("ZodUnion",(t,e)=>{qb.init(t,e),W.init(t,e),t.options=e.options});function Ys(t,e){return new Bz({type:"union",options:t,...k(e)})}const qz=w("ZodIntersection",(t,e)=>{Fb.init(t,e),W.init(t,e)});function Fz(t,e){return new qz({type:"intersection",left:t,right:e})}const Xr=w("ZodEnum",(t,e)=>{Yb.init(t,e),W.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 Xr({...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 Xr({...e,checks:[],...k(s),entries:a})}});function Yz(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Xr({type:"enum",entries:n,...k(e)})}const Gz=w("ZodTransform",(t,e)=>{Gb.init(t,e),W.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(Ht(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(Ht(o))}};const s=e.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function Vz(t){return new Gz({type:"transform",transform:t})}const Jc=w("ZodOptional",(t,e)=>{Vb.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Qi(t){return new Jc({type:"optional",innerType:t})}const Hz=w("ZodNullable",(t,e)=>{Hb.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ea(t){return new Hz({type:"nullable",innerType:t})}const Wz=w("ZodDefault",(t,e)=>{Wb.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Kz(t,e){return new Wz({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():xc(e)}})}const Jz=w("ZodPrefault",(t,e)=>{Kb.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Xz(t,e){return new Jz({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():xc(e)}})}const Xc=w("ZodNonOptional",(t,e)=>{Jb.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Qz(t,e){return new Xc({type:"nonoptional",innerType:t,...k(e)})}const eT=w("ZodCatch",(t,e)=>{Xb.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function tT(t,e){return new eT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const nT=w("ZodPipe",(t,e)=>{Qb.init(t,e),W.init(t,e),t.in=e.in,t.out=e.out});function ta(t,e){return new nT({type:"pipe",in:t,out:e})}const rT=w("ZodReadonly",(t,e)=>{ev.init(t,e),W.init(t,e),t.unwrap=()=>t._zod.def.innerType});function sT(t){return new rT({type:"readonly",innerType:t})}const iT=w("ZodCustom",(t,e)=>{tv.init(t,e),W.init(t,e)});function aT(t,e={}){return Fv(iT,t,e)}function oT(t){return Yv(t)}const Gn=i.z.string(),cn=t=>lt.statusZ(t),Qc=t=>cn(t).omit({labels:!0}).partial({key:!0}),Qr="sy_status_set",cT="sy_status_delete",eu=H("status"),uT=eu(""),ke=t=>t?JSON.parse(t):{},Gs=te({key:le(),type:le(),config:me.unknownZ.or(le().transform(ke))}),tu=Gs.extend({position:Es.xy}),es=te({param:le(),node:le()}),Vs=te({source:es,target:es}),lT=te({nodes:Gs.array(),edges:Vs.array()}),nu=te({nodes:tu.array(),edges:Vs.array()}),ru=te({raw:le()}),un=mz(),su=te({running:on()}),iu=cn(su),Vn=te({key:un,name:le(),graph:nu,text:ru,deploy:on(),version:le(),status:iu.optional().nullable()}),au=Vn.partial({key:!0}).omit({status:!0}),hT="arc",ou=H("arc"),fT=ou(""),dT=(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 Yt(`${t} not found matching ${JSON.stringify(e)}`);if(n.length>1)throw new Gt(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${n.length}`)}},pT="sy_arc_set",yT="sy_arc_delete",mT=te({keys:un.array().optional(),names:le().array().optional(),searchTerm:le().optional(),limit:xn().optional(),offset:xn().optional(),includeStatus:on().optional()}),gT=te({arcs:au.array()}),wT=te({keys:un.array()}),bT=te({arcs:N.nullableZ(Vn)}),vT=te({arcs:Vn.array()}),zT=te({}),ts=te({content:le()}),TT=te({key:un,includeStatus:on().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),OT=te({name:le(),includeStatus:on().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),cu=Ys([TT,OT]),ET=Ys([cu,mT]);let uu=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:N.toArray(e)},gT,vT);return n?r.arcs:r.arcs[0]}async retrieve(e){const n="key"in e||"name"in e,r=await T(this.client,"/arc/retrieve",e,ET,bT);return se("Arc",e,r.arcs,n),n?r.arcs[0]:r.arcs}async delete(e){await T(this.client,"/arc/delete",{keys:N.toArray(e)},wT,zT)}async openLSP(){return await this.streamClient.stream("/arc/lsp",ts,ts)}};const NT=Object.freeze(Object.defineProperty({__proto__:null,Client:uu,DELETE_CHANNEL_NAME:yT,ONTOLOGY_TYPE:hT,SET_CHANNEL_NAME:pT,TYPE_ONTOLOGY_ID:fT,arcZ:Vn,edgeZ:Vs,graphNodeZ:tu,graphZ:nu,handleZ:es,irNodeZ:Gs,irZ:lT,keyZ:un,lspMessageZ:ts,newZ:au,ontologyID:ou,singleRetrieveArgsZ:cu,statusDetailsZ:su,statusZ:iu,textZ:ru},Symbol.toStringTag,{value:"Module"})),na="Channel key must be a valid uint32.",U=i.z.uint32().or(i.z.string().refine(t=>!isNaN(Number(t)),{message:na}).transform(Number).refine(t=>t<jr.MAX_UINT32,{message:na})),lu=/^[a-zA-Z_][a-zA-Z0-9_]*$/,Ce=i.z.string().min(1,"Name must not be empty").regex(lu,"Name can only contain letters, digits, and underscores, and cannot start with a digit"),hu=["min","max","avg","none"],fu=i.z.enum(hu),Hs=i.z.object({type:fu,resetChannel:U.optional(),duration:g.z.optional()}),du=lt.statusZ(),Zt=i.z.object({name:i.z.string(),key:U,dataType:p.z,leaseholder:Ee.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:du.optional(),operations:N.nullableZ(Hs),requires:N.nullableZ(U)}),pu=Zt.extend({key:U.optional(),name:Ce,leaseholder:Ee.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(Hs).optional(),requires:N.nullableZ(U).optional()}),dt=i.z.union([Ee.toArray(U),Ee.toArray(Ce),Ee.toArray(Zt).transform(t=>t.map(e=>e.key))]),Ws=H("channel"),ST=Ws(0),kT=/[a-zA-Z0-9_]/,AT=(t,e=!1)=>{if(t==="")return e?"_":"";if(t.match(lu))return t;let n="";for(const r of t)r.match(kT)?n+=r:n+="_";return n[0].match(/^\d/)&&(n=`_${n}`),n},$T=new Error("request for lock canceled");var IT=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 ZT{constructor(e,n=$T){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=yu(this._queue,c=>n<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return IT(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]=[]),xT(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 xT(t,e){const n=yu(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function yu(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var CT=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 RT{constructor(e){this._semaphore=new ZT(1,e)}acquire(){return CT(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 We=sc.keyZ,ln=sc.labelZ,_T="labeled_by",MT="sy_label_set",jT="sy_label_delete",mu=ln.extend({key:We.optional()}),UT=i.object({labels:mu.array()}),DT=i.object({labels:ln.array()}),PT=i.object({keys:We.array()}),gu=i.object({id:L,labels:We.array(),replace:i.boolean().optional()}),LT=gu.omit({replace:!0}),mr=i.object({}),BT=i.object({keys:We.array().optional(),names:i.string().array().optional(),for:L.optional(),searchTerm:i.string().optional(),offset:i.int().optional(),limit:i.int().optional()}),qT=i.object({key:We}).transform(({key:t})=>({keys:[t]})),FT=i.union([qT,BT]),YT=i.object({labels:N.nullableZ(ln)});let wu=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,FT,YT);return se("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},gu,mr)}async remove(e,n){await T(this.client,"/label/remove",{id:e,labels:n},LT,mr)}async create(e){const n=Array.isArray(e),r=await T(this.client,"/label/create",{labels:N.toArray(e)},UT,DT);return n?r.labels:r.labels[0]}async delete(e){await T(this.client,"/label/delete",{keys:N.toArray(e)},PT,mr)}};const bu=H("label"),GT=bu(""),VT=Object.freeze(Object.defineProperty({__proto__:null,Client:wu,DELETE_CHANNEL_NAME:jT,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:_T,SET_CHANNEL_NAME:MT,TYPE_ONTOLOGY_ID:GT,keyZ:We,labelZ:ln,newZ:mu,ontologyID:bu},Symbol.toStringTag,{value:"Module"})),J=i.z.uuid(),Ks=i.z.string().min(1),hn=i.z.object({key:J,name:Ks,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()<=jr.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()>=jr.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)}}),vu=hn.omit({parent:!0,labels:!0}).partial({key:!0}),HT=i.z.object({nodeKey:Ee.uint12.optional(),keys:U.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),rangeKey:J.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()}),WT=i.z.object({channels:N.nullableZ(Zt)}),pe=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]),dT(t,{number:"keys",string:"names"}));class Js{client;constructor(e){this.client=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const r=pe(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,HT,WT)).channels}}class Xs{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}=pe(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}=pe(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 zu{mu=new RT;requests=new Map;wrapped;debouncedRun;constructor(e,n){this.wrapped=e,this.debouncedRun=Iy(()=>{this.run()},n)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n,variant:r}=pe(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 Tu=async(t,e)=>{const{normalized:n}=pe(e),r=await t.retrieve(n),s=[];if(n.forEach(a=>{r.find(o=>o.name===a||o.key===a)==null&&s.push(a)}),s.length>0)throw new Ge(`Could not find channels: ${JSON.stringify(s)}`);return r},KT="sy_channel_set",JT="sy_channel_delete";class Cn{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;operations;requires;status;constructor({dataType:e,name:n,leaseholder:r=0,key:s=0,isIndex:a=!1,index:o=0,internal:c=!1,virtual:l=!1,frameClient:u,alias:h,status:d,expression:f="",operations:O=[],requires:S=[]}){this.key=U.parse(s),this.name=n,this.dataType=new p(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,this.requires=S,d!=null&&(this.status=lt.create(d)),this._frameClient=u??null}get framer(){if(this._frameClient==null)throw new V("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Zt.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,requires:this.requires,expression:this.expression,status:this.status,operations:this.operations})}get isCalculated(){return kt(this.payload)}get ontologyID(){return Ws(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 XT="sy_calculation_status",QT=i.z.object({}),eO=i.z.object({group:Pn});let Ou=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}=pe(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 Xs(new zu(new Js(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 T(this.client,"/channel/retrieve-group",{},QT,eO)).group}};const kt=({virtual:t,expression:e})=>t&&e!=="",tO=t=>kt(t)&&t.requires.length>0,Eu=async(t,e)=>{if(!kt(e))return e.index;for(const n of e.requires){const r=await t(n);if(r==null)return null;if(!r.virtual)return r.index}for(const n of e.requires){const r=await t(n);if(r==null)return null;if(kt(r)){const s=await Eu(t,r);if(s!=null)return s}}return null},nO=i.z.object({channels:pu.array()}),rO=i.z.object({channels:Zt.array()}),sO=i.z.object({keys:U.array().optional(),names:Ce.array().optional()}),iO=i.z.object({}),aO=i.z.object({keys:U.array(),names:Ce.array()}),oO=i.z.object({});let Nu=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}))},nO,rO);return this.cache.set(n),n}async delete(e){const n=U.array().parse(e.keys??[]);await T(this.client,"/channel/delete",e,sO,iO),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},aO,oO),this.cache.rename(e,n)}};const cO=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:XT,CacheRetriever:Xs,Channel:Cn,Client:Ou,ClusterRetriever:Js,DELETE_CHANNEL_NAME:JT,DebouncedBatchRetriever:zu,OPERATION_TYPES:hu,SET_CHANNEL_NAME:KT,TYPE_ONTOLOGY_ID:ST,Writer:Nu,analyzeParams:pe,escapeInvalidName:AT,isCalculated:kt,isLegacyCalculated:tO,keyZ:U,nameZ:Ce,newZ:pu,ontologyID:Ws,operationType:fu,operationZ:Hs,paramsZ:dt,payloadZ:Zt,resolveLegacyCalculatedIndex:Eu,retrieveRequired:Tu,statusZ:du},Symbol.toStringTag,{value:"Module"})),uO=i.z.object({username:i.z.string(),password:i.z.string()}),lO=i.z.object({token:i.z.string(),user:sn}),ra="/auth/login",hO=3,fO=i.z.object({username:i.z.string(),password:i.z.string(),newPassword:i.z.string().min(1)}),dO=i.z.object({}),pO=[Gr,Vr];let yO=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},fO,dO),this.credentials.password=e}middleware(){const e=async(n,r)=>{if(!this.authenticated&&!n.target.endsWith(ra)){this.authenticating??=new Promise((c,l)=>{this.client.send(ra,this.credentials,uO,lO).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 pO.some(o=>o.matches(a))&&this.retryCount<hO?(this.authState={authenticated:!1},this.authenticating=void 0,this.retryCount+=1,e(n,r)):(this.retryCount=0,[s,a])};return e}};const Su=i.z.enum(["disconnected","connecting","connected","failed"]),ku=i.z.object({status:Su,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()}),mO=i.z.object({clusterKey:i.z.string(),nodeVersion:i.z.string().optional()}),gO=i.z.void(),sa={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.49.2"},ia=(t,e,n)=>{const r=n?"Core":"client";return`Synnax Core version ${t!=null?`${t} `:""}is too ${n?"old":"new"} for client version ${e}.
41
41
  This may cause compatibility issues. We recommend updating the ${r}. For more information, see
42
- https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${r}-version`};class Ln{static DEFAULT=ea;_state;pollFrequency=S.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=gu;versionWarned=!1;constructor(e,n=S.seconds(30),r,s){this._state={...ea},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 w(this.client,"/connectivity/check",void 0,Hz,Yz),r=n.nodeVersion,s=this.clientVersion,a=this.versionWarned;r==null?(this._state.clientServerCompatible=!1,a||(console.warn(ta(null,s,!0)),this.versionWarned=!0)):Si.versionsEqual(s,r,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,a||(console.warn(ta(r,s,Si.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 Wz=Object.freeze(Object.defineProperty({__proto__:null,Checker:Ln,stateZ:gu,statusZ:mu},Symbol.toStringTag,{value:"Module"})),Gz=i.z.object({keys:D.array().optional(),bounds:P.z,names:Re.array().optional()}),Kz=i.z.object({});class Jz{client;constructor(e){this.client=e}async delete(e){await w(this.client,"/frame/delete",e,Gz,Kz)}}const na=t=>{const e=T.toArray(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},ra=(t,e)=>{const n=T.toArray(t);if(n.length===e.length)return;const r=na(t);throw na===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,...T.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=>wu(o));ra(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,...T.toArray(a));this.push(s,...T.toArray(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const s=T.toArray(n),a=T.toArray(e);ra(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
42
+ https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${r}-version`};class Rn{static DEFAULT=sa;_state;pollFrequency=g.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=ku;versionWarned=!1;constructor(e,n=g.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,gO,mO),r=n.nodeVersion,s=this.clientVersion,a=this.versionWarned;r==null?(this._state.clientServerCompatible=!1,a||(console.warn(ia(null,s,!0)),this.versionWarned=!0)):xi.versionsEqual(s,r,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,a||(console.warn(ia(r,s,xi.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 wO=Object.freeze(Object.defineProperty({__proto__:null,Checker:Rn,stateZ:ku,statusZ:Su},Symbol.toStringTag,{value:"Module"})),bO=i.z.object({keys:U.array().optional(),bounds:x.z,names:Ce.array().optional()}),vO=i.z.object({});class zO{client;constructor(e){this.client=e}async delete(e){await T(this.client,"/frame/delete",e,bO,vO)}}const aa=t=>{const e=N.toArray(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},oa=(t,e)=>{const n=N.toArray(t);if(n.length===e.length)return;const r=aa(t);throw aa===null?new V("[Frame] - channel keys or names must be provided when constructing a frame."):new V(`[Frame] - ${r}s and series must be the same length.
43
+ Got ${n.length} ${r}s and ${e.length} series.`)};class 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=>Au(o));oa(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);oa(a,s),s.forEach((o,c)=>this.push(a[c],o));return}throw new V(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
44
44
  payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
45
- name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new zt("colType is not key");return this.columns??[]}get uniqueKeys(){return bi.unique(this.keys)}get names(){if(this.colType==="key")throw new zt("colType is not name");return this.columns??[]}get uniqueNames(){return bi.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>bu(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 P.ZERO;const r=p.min(...this.series.map(a=>a.timeRange.start)),s=p.max(...this.series.map(a=>a.timeRange.end));return new P(r,s)}const n=this.get(e);return n==null?P.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 Po(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)})}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 Ot(this.series.reduce((e,n)=>e.add(n.byteLength),Ot.ZERO))}get digest(){const e={};return this.keys.forEach((n,r)=>{const s=this.series[r].digest;n in e?e[n].push(s):e[n]=[s]}),e}get length(){return this.series.reduce((e,n)=>e+n.length,0)}toString(){let e=`Frame{
45
+ name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new nt("colType is not key");return this.columns??[]}get uniqueKeys(){return Ei.unique(this.keys)}get names(){if(this.colType==="key")throw new nt("colType is not name");return this.columns??[]}get uniqueNames(){return Ei.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>$u(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 qo(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 V("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...n),typeof e=="string"&&this.colType==="key")throw new V("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new V("keyVariant must match");this.columns.push(...Array.from({length:n.length},()=>e))}}concat(e){return new 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{
46
46
  `;return this.uniqueColumns.forEach(n=>{e+=` ${n}: ${this.get(n).series.map(r=>r.toString()).join(",")}
47
- `}),e+="}",e}}const ir=i.z.object({keys:i.z.union([i.z.null().transform(()=>[]),i.z.number().array().optional().default([])]),series:i.z.union([i.z.null().transform(()=>[]),ee.crudeZ.array().optional().default([])])}),wu=t=>{const{dataType:e,data:n,timeRange:r,alignment:s}=t;return new ee({data:n,dataType:e,timeRange:r,glBufferUsage:"static",alignment:s})},bu=t=>({timeRange:t.timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});var Ie=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.SetAuthority=3]="SetAuthority",t))(Ie||{});const sa=t=>t.data.byteLength/t.dataType.density.valueOf(),Xz=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)},ia=5,aa=4,oa=3,ca=2,ua=1,la=0,ze=R.TIMESTAMP.density.valueOf(),Pe=8,Ue=4,Sr=4,Ir=4,Qz=1;class vu{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(`
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(()=>[]),ee.crudeZ.array().default([])])}),Au=t=>{const{dataType:e,data:n,timeRange:r,alignment:s}=t;return new ee({data:n,dataType:e,timeRange:r,glBufferUsage:"static",alignment:s})},$u=t=>({timeRange:t.timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});var Oe=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.SetAuthority=3]="SetAuthority",t))(Oe||{});const ca=t=>t.data.byteLength/t.dataType.density.valueOf(),TO=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)},ua=5,la=4,ha=3,fa=2,da=1,pa=0,we=p.TIMESTAMP.density.valueOf(),De=8,Pe=4,gr=4,wr=4,OO=1;class Iu{contentType="application/sy-framer";states=new Map;currState;seqNum=0;constructor(e=[],n=[]){(e.length>0||n.length>0)&&this.update(e,n)}update(e,n){this.seqNum++;const r={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((s,a)=>{const o=n[a];r.keyDataTypes.set(s,o),o.isVariable&&(r.hasVariableDataTypes=!0)}),r.keys.sort(),this.states.set(this.seqNum,r),this.currState=r}throwIfNotUpdated(e){if(this.seqNum<1)throw new V(`
48
48
  The codec has not been updated with a list of channels and data types.
49
49
  Please call the update method before calling ${e}.
50
- `)}encode(e,n=0){this.throwIfNotUpdated("encode");let r=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(r=e.toPayload()),Xz(r);let s=-1,a,o,c,l=n+Qz+Ir,u=!this.currState?.hasVariableDataTypes,h=!0,d=!0,f=!0,v=!0,$=!0;r.keys.length!==this.currState?.keys.length&&(f=!1,l+=r.keys.length*Sr),r.series.forEach((A,G)=>{const Y=sa(A),me=r.keys[G],Je=this.currState?.keyDataTypes.get(me);if(Je==null)throw new H(`Channel ${me} was not provided in the list of channels when opening the writer`);if(!Je.equals(A.dataType))throw new H(`Series data type of ${A.dataType.toString()} does not match the data type of ${Je.toString()} for channel ${me}`);if(l+=A.data.byteLength,s===-1){s=Y,a=A.timeRange?.start,o=A.timeRange?.end,c=BigInt(A.alignment??0n);return}s!==Y&&(u=!1),(a?.valueOf()!==A.timeRange?.start.valueOf()||o?.valueOf()!==A.timeRange?.end.valueOf())&&(h=!1),c!==BigInt(A.alignment??0)&&(v=!1)}),d=h&&a==null&&o==null,$=v&&(c===void 0||c===0n),u?l+=Ue:l+=r.keys.length*Ue,d||(h?l+=ze*2:l+=r.keys.length*ze*2),$||(v?l+=Pe:l+=r.keys.length*Pe);const k=new Uint8Array(l),b=new DataView(k.buffer);let E=n;return k[E]=Number($)<<ia|Number(v)<<aa|Number(u)<<oa|Number(h)<<ca|Number(d)<<ua|Number(f)<<la,E++,b.setUint32(E,this.seqNum,!0),E+=Ir,u&&(b.setUint32(E,s,!0),E+=Ue),h&&!d&&(b.setBigUint64(E,a?.valueOf()??0n,!0),b.setBigUint64(E,o?.valueOf()??0n,!0),E+=ze*2),v&&!$&&(b.setBigUint64(E,c??0n,!0),E+=Pe),r.series.forEach((A,G)=>{if(f||(b.setUint32(E,r.keys[G],!0),E+=Sr),!u){let Y=A.data.byteLength;A.dataType.isVariable||(Y=sa(A)),b.setUint32(E,Y,!0),E+=Ue}k.set(new Uint8Array(A.data),E),E+=A.data.byteLength,!h&&!d&&(b.setBigUint64(E,A.timeRange?.start.valueOf()??0n,!0),b.setBigUint64(E,A.timeRange?.end.valueOf()??0n,!0),E+=ze*2),!v&&!$&&(b.setBigUint64(E,A.alignment??0n,!0),E+=Pe)}),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,l,u,h;const d=new DataView(r.buffer,r.byteOffset,r.byteLength),f=!!(r[a]>>ia&1),v=!!(r[a]>>aa&1),$=!!(r[a]>>oa&1),k=!!(r[a]>>ca&1),b=!!(r[a]>>ua&1),E=!!(r[a]>>la&1);a++;const A=d.getUint32(a,!0);a+=Ir;const G=this.states.get(A);if(G==null)return s;if($){if(a+Ue>d.byteLength)return s;o=d.getUint32(a,!0),a+=Ue}if(k&&!b){if(a+ze>d.byteLength)return s;l=new p(d.getBigUint64(a,!0)),a+=ze,u=new p(d.getBigUint64(a,!0)),a+=ze}if(v&&!f){if(a+Pe>d.byteLength)return s;h=d.getBigUint64(a,!0),a+=Pe}return E&&(s.keys=[...G.keys]),G.keys.forEach((Y,me)=>{if(!E){if(a>=d.byteLength||d.getUint32(a,!0)!==Y)return;a+=Sr,s.keys.push(Y)}const Je=G.keyDataTypes.get(Y);if(c=0,$)c=o;else{if(a+Ue>d.byteLength)return;c=d.getUint32(a,!0),a+=Ue}let wn=c;if(Je.isVariable||(wn*=Je.density.valueOf()),a+wn>d.byteLength){s.keys.splice(me,1);return}const Xe={dataType:Je,data:r.slice(a,a+wn).buffer};if(a+=wn,!k&&!b){if(a+ze*2>d.byteLength)return;const ai=d.getBigUint64(a,!0);a+=ze;const Ll=d.getBigUint64(a,!0);a+=ze,Xe.timeRange=new P({start:ai,end:Ll})}else b?Xe.timeRange=new P({start:0n,end:0n}):Xe.timeRange=new P({start:l?.valueOf()??0n,end:u?.valueOf()??0n});if(!v&&!f){if(a+Pe>d.byteLength)return;h=d.getBigUint64(a,!0),a+=Pe,Xe.alignment=h}else f?Xe.alignment=0n:Xe.alignment=h;s.series.push(Xe)}),s}}const Ws=254,eE=new Uint8Array([Ws]),tE=255,nE=new Uint8Array([tE]),Tu="application/sy-framer";class rE{contentType=Tu;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=it.JSON_CODEC}encode(e){const n=e;if(n.type=="close"||n.payload?.command!=Ie.Write){const s=this.lowPerfCodec.encode(n),a=new Uint8Array({length:s.byteLength+1});return a.set(eE,0),a.set(new Uint8Array(s),1),a}const r=this.base.encode(n.payload?.frame,1);return r.set(nE,0),r}decode(e,n){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===Ws)return this.lowPerfCodec.decode(e.slice(1),n);const a={type:"data"},o=this.base.decode(e,1);return a.payload={command:Ie.Write,frame:o},a}}class sE{contentType=Tu;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=it.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,n){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===Ws?this.lowPerfCodec.decode(e.slice(1),n):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class ar{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=new Set,this.codec=new vu}static async open(e,n){const r=new ar(e);return await r.update(n),r}async update(e){const{variant:n,normalized:r}=we(e),s=await this.retriever.retrieve(r),a=s.map(c=>c.key);if(Oi.uniqueUnorderedPrimitiveArrays(Array.from(this.keys),a)===Oi.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 Gs{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new vu}static async open(e,n){const r=new Gs(e);return await r.update(n),r}async adaptParams(e){const n=ut.parse(e);return await Promise.all(n.map(async s=>await this.adaptToKey(s)))}async update(e){const n=await uu(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(`
50
+ `)}encode(e,n=0){this.throwIfNotUpdated("encode");let r=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(r=e.toPayload()),TO(r);let s=-1,a,o,c,l=n+OO+wr,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*gr),r.series.forEach((A,P)=>{const R=ca(A),j=r.keys[P],ie=this.currState?.keyDataTypes.get(j);if(ie==null)throw new V(`Channel ${j} was not provided in the list of channels when opening the writer`);if(!ie.equals(A.dataType))throw new V(`Series data type of ${A.dataType.toString()} does not match the data type of ${ie.toString()} for channel ${j}`);if(l+=A.data.byteLength,s===-1){s=R,a=A.timeRange?.start,o=A.timeRange?.end,c=BigInt(A.alignment??0n);return}s!==R&&(u=!1),(a?.valueOf()!==A.timeRange?.start.valueOf()||o?.valueOf()!==A.timeRange?.end.valueOf())&&(h=!1),c!==BigInt(A.alignment??0)&&(O=!1)}),d=h&&a==null&&o==null,S=O&&(c===void 0||c===0n),u?l+=Pe:l+=r.keys.length*Pe,d||(h?l+=we*2:l+=r.keys.length*we*2),S||(O?l+=De:l+=r.keys.length*De);const Z=new Uint8Array(l),z=new DataView(Z.buffer);let E=n;return Z[E]=Number(S)<<ua|Number(O)<<la|Number(u)<<ha|Number(h)<<fa|Number(d)<<da|Number(f)<<pa,E++,z.setUint32(E,this.seqNum,!0),E+=wr,u&&(z.setUint32(E,s,!0),E+=Pe),h&&!d&&(z.setBigUint64(E,a?.valueOf()??0n,!0),z.setBigUint64(E,o?.valueOf()??0n,!0),E+=we*2),O&&!S&&(z.setBigUint64(E,c??0n,!0),E+=De),r.series.forEach((A,P)=>{if(f||(z.setUint32(E,r.keys[P],!0),E+=gr),!u){let R=A.data.byteLength;A.dataType.isVariable||(R=ca(A)),z.setUint32(E,R,!0),E+=Pe}Z.set(new Uint8Array(A.data),E),E+=A.data.byteLength,!h&&!d&&(z.setBigUint64(E,A.timeRange?.start.valueOf()??0n,!0),z.setBigUint64(E,A.timeRange?.end.valueOf()??0n,!0),E+=we*2),!O&&!S&&(z.setBigUint64(E,A.alignment??0n,!0),E+=De)}),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]>>ua&1),O=!!(r[a]>>la&1),S=!!(r[a]>>ha&1),Z=!!(r[a]>>fa&1),z=!!(r[a]>>da&1),E=!!(r[a]>>pa&1);a++;const A=d.getUint32(a,!0);a+=wr;const P=this.states.get(A);if(P==null)return s;if(S){if(a+Pe>d.byteLength)return s;o=d.getUint32(a,!0),a+=Pe}if(Z&&!z){if(a+we>d.byteLength)return s;l=new m(d.getBigUint64(a,!0)),a+=we,u=new m(d.getBigUint64(a,!0)),a+=we}if(O&&!f){if(a+De>d.byteLength)return s;h=d.getBigUint64(a,!0),a+=De}return E&&(s.keys=[...P.keys]),P.keys.forEach((R,j)=>{if(!E){if(a>=d.byteLength||d.getUint32(a,!0)!==R)return;a+=gr,s.keys.push(R)}const ie=P.keyDataTypes.get(R);if(c=0,S)c=o;else{if(a+Pe>d.byteLength)return;c=d.getUint32(a,!0),a+=Pe}let ae=c;if(ie.isVariable||(ae*=ie.density.valueOf()),a+ae>d.byteLength){s.keys.splice(j,1);return}const fe={dataType:ie,data:r.slice(a,a+ae).buffer};if(a+=ae,!Z&&!z){if(a+we*2>d.byteLength)return;const fi=d.getBigUint64(a,!0);a+=we;const Ql=d.getBigUint64(a,!0);a+=we,fe.timeRange=new x({start:fi,end:Ql})}else z?fe.timeRange=new x({start:0n,end:0n}):fe.timeRange=new x({start:l?.valueOf()??0n,end:u?.valueOf()??0n});if(!O&&!f){if(a+De>d.byteLength)return;h=d.getBigUint64(a,!0),a+=De,fe.alignment=h}else f?fe.alignment=0n:fe.alignment=h;s.series.push(fe)}),s}}const Qs=254,EO=new Uint8Array([Qs]),NO=255,SO=new Uint8Array([NO]),Zu="application/sy-framer";class kO{contentType=Zu;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=ot.JSON_CODEC}encode(e){const n=e;if(n.type=="close"||n.payload?.command!=Oe.Write){const s=this.lowPerfCodec.encode(n),a=new Uint8Array({length:s.byteLength+1});return a.set(EO,0),a.set(new Uint8Array(s),1),a}const r=this.base.encode(n.payload?.frame,1);return r.set(SO,0),r}decode(e,n){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===Qs)return this.lowPerfCodec.decode(e.slice(1),n);const a={type:"data"},o=this.base.decode(e,1);return a.payload={command:Oe.Write,frame:o},a}}class AO{contentType=Zu;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=ot.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,n){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===Qs?this.lowPerfCodec.decode(e.slice(1),n):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class Wn{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=new Set,this.codec=new Iu}static async open(e,n){const r=new Wn(e);return await r.update(n),r}async update(e){const{variant:n,normalized:r}=pe(e),s=await this.retriever.retrieve(r),a=s.map(c=>c.key);if(Ni.uniqueUnorderedPrimitiveArrays(Array.from(this.keys),a)===Ni.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 ei{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new Iu}static async open(e,n){const r=new ei(e);return await r.update(n),r}async adaptParams(e){const n=dt.parse(e);return await Promise.all(n.map(async s=>await this.adaptToKey(s)))}async update(e){const n=await Tu(this.retriever,e),r=n.map(u=>u.key),s=new Set(this.keys),a=new Set(r),o=!a.isSubsetOf(s),c=!s.isSubsetOf(a);return o||c?(this.adapter=new Map(n.map(u=>[u.name,u.key])),this.keys=r,this.codec.update(this.keys,n.map(u=>u.dataType)),!0):!1}async fetchChannel(e){const n=await this.retriever.retrieve(e);if(n.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return n[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}encode(e){return this.codec.encode(e.toPayload())}async adapt(e,n){if(typeof e=="string"||typeof e=="number"){if(n==null)throw new V(`
51
51
  Received a single channel name or key but no series.
52
- `);if(Array.isArray(n)){if(n.some(l=>l instanceof ee||Array.isArray(l)))throw new H(`
52
+ `);if(Array.isArray(n)){if(n.some(l=>l instanceof ee||Array.isArray(l)))throw new V(`
53
53
  Received a single channel name or key but multiple series.
54
- `);n=n}const o=await this.fetchChannel(e),c=new ee({data:n,dataType:o.dataType});return new F(o.key,c)}if(Array.isArray(e)){if(n==null)throw new H(`
54
+ `);n=n}const o=await this.fetchChannel(e),c=new ee({data:n,dataType:o.dataType});return new F(o.key,c)}if(Array.isArray(e)){if(n==null)throw new V(`
55
55
  Received an array of channel names or keys but no series.
56
- `);if(!Array.isArray(n))throw new H(`
56
+ `);if(!Array.isArray(n))throw new V(`
57
57
  Received an array of channel names or keys but no array of series.
58
- `);const o=[],c=[];for(let l=0;l<e.length;l++){const u=await this.fetchChannel(e[l]);if(l>=n.length)throw new H(`
58
+ `);const o=[],c=[];for(let l=0;l<e.length;l++){const u=await this.fetchChannel(e[l]);if(l>=n.length)throw new V(`
59
59
  Received an array of channel names or keys but not enough series.
60
- `);const h=new ee({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(`
60
+ `);const h=new ee({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 V(`
61
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 ee({data:l,dataType:u.dataType});r.push(u.key),s.push(h)}return new F(r,s)}}class zu{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(be.matches(n))return;throw n}}}closeSend(){this.stream.closeSend()}send(e){const n=this.stream.send(e);if(n!=null)throw n}}const Bn=new S(-1);var Ks=(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))(Ks||{}),Eu=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(Eu||{});const iE=i.z.object({command:i.z.enum(Ks),span:S.z.optional(),bounds:P.z.optional(),stamp:p.z.optional(),keys:D.array().optional(),chunkSize:i.z.number().optional()}),aE=i.z.object({variant:i.z.enum(Eu),ack:i.z.boolean(),command:i.z.enum(Ks),error:_e.payloadZ.optional().nullable(),frame:ir.optional()});class or{stream;adapter;value;constructor(e,n){this.stream=new zu("Iterator",e),this.value=new F,this.adapter=n}static async _open(e,n,r,s,a={}){const o=await ar.open(r,n),c=await s.stream("/frame/iterate",iE,aE),l=new or(c,o);return await l.execute({command:0,keys:Array.from(o.keys),bounds:new P(e),chunkSize:a.chunkSize??1e5}),l}async next(e=Bn){return await this.execute({command:1,span:new S(e)})}async prev(e=Bn){return await this.execute({command:2,span:new S(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new p(e)})}async seekGE(e){return await this.execute({command:6,stamp:new p(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new oE(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 oE{iter;open=!1;constructor(e){this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const cE=i.z.object({keys:i.z.number().array(),downsampleFactor:i.z.number()}),uE=i.z.object({frame:ir}),ha=i.z.object({channels:ut,downsampleFactor:i.z.number().optional().default(1),useHighPerformanceCodec:i.z.boolean().optional().default(!0)}),Js=ha.or(ut.transform(t=>ha.parse({channels:t}))),Nu=(t,e)=>async n=>{const r=Js.parse(n),s=await ar.open(t,r.channels);r.useHighPerformanceCodec&&(e=e.withCodec(new sE(s.codec)));const a=await e.stream("/frame/stream",cE,uE),o=new lE(a,s);a.send({keys:Array.from(s.keys),downsampleFactor:r.downsampleFactor});const[,c]=await a.receive();if(c!=null)throw c;return o},Ou=async(t,e,n)=>await Nu(t,e)(n);class lE{stream;adapter;downsampleFactor;constructor(e,n){this.stream=new zu("Streamer",e),this.adapter=n,this.downsampleFactor=1}get keys(){return Array.from(this.adapter.keys)}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(be.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})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class cr{wrapped_=null;breaker;opener;config;constructor(e,n,r={}){this.opener=e,this.config=Js.parse(n);const{maxRetries:s=5e3,baseInterval:a=S.seconds(1),scale:o=1}=r??{};this.breaker=new Zs.Breaker({maxRetries:s,baseInterval:a,scale:o})}static async open(e,n,r){const s=new cr(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=ut.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(be.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(be.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 $u extends iy.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 en=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(en||{});const hE=new S(-1);class fs extends Ae.sub("writer_closed"){constructor(){super("WriterClosed")}}const fE=i.z.enum(en).or(i.z.enum(["persist","stream","persistStream"]).transform(t=>{switch(t){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),Su=i.z.object({start:p.z.optional(),controlSubject:de.subjectZ.optional(),authorities:i.z.union([de.authorityZ.transform(t=>[t]),de.authorityZ.array()]).default([de.ABSOLUTE_AUTHORITY]),mode:fE.default(1),errOnUnauthorized:i.z.boolean().default(!1),enableAutoCommit:i.z.boolean().default(!0),autoIndexPersistInterval:S.z.default(S.SECOND),useHighPerformanceCodec:i.z.boolean().default(!0)}),dE=Su.extend({keys:D.array().optional()}),fa=Su.extend({channels:ut}),Iu=fa.or(ut.transform(t=>fa.parse({channels:t,start:p.now()}))),pE=i.z.object({command:i.z.enum(Ie),config:dE.optional(),frame:ir.optional(),buffer:i.z.instanceof(Uint8Array).optional()}),yE=i.z.object({command:i.z.enum(Ie),end:p.z,err:_e.payloadZ.optional()}),mE=i.z.tuple([i.z.union([i.z.record(D.or(Re),de.authorityZ),D.or(Re),de.authorityZ]),de.authorityZ.optional()]).transform(([t,e])=>{if(de.authorityZ.safeParse(t).success)return{keys:[],authorities:[t]};if(D.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 Au=class ku{stream;adapter;closeErr=null;constructor(e,n){this.stream=e,this.adapter=n}static async _open(e,n,r){const s=Iu.parse(r),a=await Gs.open(e,s.channels);s.useHighPerformanceCodec&&(n=n.withCodec(new rE(a.codec)));const o=await n.stream("/frame/write",pE,yE),c=new ku(o,a);return await c.execute({command:Ie.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:Ie.Write,frame:r.toPayload()})}async setAuthority(e,n){if(this.closeErr!=null)throw this.closeErr;const r=mE.parse([e,n]),s={keys:await this.adapter.adaptParams(r.keys),authorities:r.authorities};await this.execute({command:Ie.SetAuthority,config:s})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),p.ZERO):(await this.execute({command:Ie.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(fs.matches(this.closeErr))return null;throw this.closeErr}const[n,r]=await this.stream.receive();r!=null?this.closeErr=be.matches(r)?new fs:r:this.closeErr=_e.decode(n?.err)}}async execute(e){const n=this.stream.send(e);for(n!=null&&await this.closeInternal(n);;){const[r,s]=await this.stream.receive();s!=null&&await this.closeInternal(s);const a=_e.decode(r?.err);if(a!=null&&await this.closeInternal(a),r?.command==e.command)return r}}};const gE=t=>({type:"framer",key:t.toString()});let xu=class{streamClient;retriever;deleter;constructor(e,n,r){this.streamClient=e,this.retriever=r,this.deleter=new Jz(n)}async openIterator(e,n,r){return await or._open(e,n,this.retriever,this.streamClient,r)}async openWriter(e){return await Au._open(this.retriever,this.streamClient,e)}async openStreamer(e){return await Ou(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:en.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:S.MAX});return await o.write(a),await o.close()}const s=await this.openWriter({start:e,channels:n,mode:en.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:S.MAX});await s.write(n,r),await s.close()}async read(e,n){const{single:r}=we(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}=we(e),s=await this.readLatestNFrame(e,n);return r?s.get(e):s}async readLatestNFrame(e,n){const r=await this.openIterator(P.MAX,e,{chunkSize:n}),s=new F;if(n>0)try{await r.seekLast(),await r.prev(Bn),s.push(r.value)}finally{await r.close()}return s}async delete(e,n){const{normalized:r,variant:s}=we(e),a=new P(n);return s==="keys"?await this.deleter.delete({keys:r,bounds:a}):await this.deleter.delete({names:r,bounds:a})}};const wE=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:hE,AUTO_SPAN:Bn,Client:xu,Frame:F,HardenedStreamer:cr,Iterator:or,ObservableStreamer:$u,Writer:Au,WriterClosedError:fs,WriterCommand:Ie,WriterMode:en,createStreamOpener:Nu,frameZ:ir,ontologyID:gE,openStreamer:Ou,seriesFromPayload:wu,seriesToPayload:bu,streamerConfigZ:Js,writerConfigZ:Iu},Symbol.toStringTag,{value:"Module"})),bE=de.ABSOLUTE_AUTHORITY,vE=de.ZERO_AUTHORITY,TE=de.stateZ(i.z.number()),zE=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()})`,EE=i.z.object({transfers:i.z.array(de.transferZ(D))});class Zu extends $u{states;codec;constructor(e){super(e,n=>{const r=this.codec.decode(n.series[0].buffer,EE);return this.merge(r),[r.transfers,!0]}),this.states=new Map,this.codec=new it.JSONCodec}subjects(){const e=new Map;return this.states.forEach(n=>e.set(n.subject.key,n.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const Cu="sy_node_1_control";let Ru=class{framer;constructor(e){this.framer=e}async openStateTracker(){const e=await cr.open(async n=>await this.framer.openStreamer(n),Cu);return new Zu(e)}};const NE=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:bE,CONTROL_STATE_CHANNEL_NAME:Cu,Client:Ru,StateTracker:Zu,ZERO_AUTHORITY:vE,stateZ:TE,transferString:zE},Symbol.toStringTag,{value:"Module"}));let _u=class{tasks;racks;devices;constructor(e,n,r){this.tasks=e,this.racks=n,this.devices=r}};const OE=Object.freeze(Object.defineProperty({__proto__:null,Client:_u},Symbol.toStringTag,{value:"Module"})),Te=i.z.uint32(),ju=i.z.object({rack:Te}),Mu=Zt.statusZ(ju),ur=i.z.object({key:Te,name:i.z.string(),status:qt.nullToUndefined(Mu)}),Du=ur.partial({key:!0}),Pu=t=>t?it.JSON_CODEC.decodeString(t,ve.unknownZ):{},_t=i.z.string(),Uu=i.z.object({rack:Te,device:_t}),Lu=Zt.statusZ(Uu),lr=i.z.object({key:_t,rack:Te.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:ve.unknownZ.or(i.z.string().transform(Pu)),status:qt.nullToUndefined(Lu)}),Bu=lr.extend({properties:i.z.unknown().transform(t=>it.JSON_CODEC.encodeString(t))}),$E="sy_device_set",SE="sy_device_delete",IE="sy_device_status",AE="/hardware/device/retrieve",kE="/hardware/device/create",xE="/hardware/device/delete",ZE=i.z.object({devices:Bu.array()}),CE=i.z.object({devices:lr.array()}),RE=i.z.object({keys:_t.array()}),_E=i.z.object({}),jE=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:Te.array().optional(),searchTerm:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),includeStatus:i.z.boolean().optional()}),ME=i.z.object({devices:T.nullableZ(lr)}),DE=i.z.object({key:_t,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),PE=i.z.union([DE,jE]);let qu=class{client;constructor(e){this.client=e}async retrieve(e){const n=typeof e=="object"&&"key"in e,r=await w(this.client,AE,e,PE,ME);ue("Device",e,r.devices,n);const s=r.devices;return n?s[0]:s}async create(e){const n=!Array.isArray(e),s=(await w(this.client,kE,{devices:T.toArray(e)},ZE,CE)).devices;return n?s[0]:s}async delete(e){await w(this.client,xE,{keys:T.toArray(e)},RE,_E)}};const UE=t=>({type:"device",key:t}),LE=Object.freeze(Object.defineProperty({__proto__:null,Client:qu,DELETE_CHANNEL_NAME:SE,SET_CHANNEL_NAME:$E,STATUS_CHANNEL_NAME:IE,deviceZ:lr,keyZ:_t,newZ:Bu,ontologyID:UE,statusDetailsSchema:Uu,statusZ:Lu},Symbol.toStringTag,{value:"Module"})),BE="/hardware/rack/retrieve",qE="/hardware/rack/create",FE="/hardware/rack/delete",VE="sy_rack_status",YE="sy_rack_set",HE="sy_rack_delete",WE=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.number().optional(),offset:i.z.number().optional(),includeStatus:i.z.boolean().optional()}),GE=i.z.object({racks:T.nullableZ(ur)}),KE=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}))]),JE=WE,XE=i.z.union([KE,JE]),QE=i.z.object({racks:Du.array()}),eN=i.z.object({racks:ur.array()}),tN=i.z.object({keys:Te.array()}),nN=i.z.object({});let Fu=class{client;tasks;constructor(e,n){this.client=e,this.tasks=n}async delete(e){await w(this.client,FE,{keys:T.toArray(e)},tN,nN)}async create(e){const n=!Array.isArray(e),r=await w(this.client,qE,{racks:T.toArray(e)},QE,eN),s=this.sugar(r.racks);return n?s[0]:s}async retrieve(e){const n="key"in e||"name"in e,r=await w(this.client,BE,e,XE,GE),s=this.sugar(r.racks);return ue("Rack",e,s,n),n?s[0]:s}sugar(e){const n=!Array.isArray(e),r=T.toArray(e).map(({key:s,name:a,status:o})=>new Vu(s,a,this.tasks,o));return n?r[0]:r}};class Vu{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 rN=t=>({type:"rack",key:t.toString()}),sN=Object.freeze(Object.defineProperty({__proto__:null,Client:Fu,DELETE_CHANNEL_NAME:HE,Rack:Vu,SET_CHANNEL_NAME:YE,STATUS_CHANNEL_NAME:VE,keyZ:Te,newZ:Du,ontologyID:rN,rackZ:ur,statusDetailsSchema:ju,statusZ:Mu},Symbol.toStringTag,{value:"Module"})),je=i.z.union([i.z.string(),i.z.bigint().transform(t=>t.toString()),i.z.number().transform(t=>t.toString())]),Yu=t=>i.z.object({task:je,running:i.z.boolean(),data:t}),Xs=t=>Zt.statusZ(Yu(t)),yn=(t={typeSchema:i.z.string(),configSchema:i.z.unknown(),statusDataSchema:i.z.unknown()})=>i.z.object({key:je,name:i.z.string(),type:t.typeSchema,internal:i.z.boolean().optional(),config:i.z.string().transform(Pu).or(t.configSchema),status:Xs(t.statusDataSchema).optional().nullable(),snapshot:i.z.boolean().optional()}),Hu=t=>yn(t).omit({key:!0}).extend({key:je.transform(e=>e.toString()).optional(),config:i.z.unknown().transform(e=>it.JSON_CODEC.encodeString(e))}),iN=i.z.object({task:je,type:i.z.string(),key:i.z.string(),args:ve.unknownZ.or(i.z.string().transform(ke)).or(i.z.array(i.z.unknown())).or(i.z.null()).optional()}),aN=t=>Number(BigInt(t)>>32n),ds="sy_task_status",ps="sy_task_cmd",oN="sy_task_set",cN="sy_task_delete",Qe=new Error("Task not created"),Wu=async(t,e)=>{const n=await e.retrieveParents(Qs(t));return n.length===0?null:n[0]};class Gu{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw Qe;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw Qe;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw Qe;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 Qs(this.key)}async executeCommand(e){return await Xu({...e,frameClient:this.frameClient,task:this.key})}async executeCommandSync(e){return await Qu({...e,frameClient:this.frameClient,task:this.key,name:this.name,statusDataZ:this.schemas?.statusDataSchema})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw Qe;return this.snapshot?await Wu(this.key,this.ontologyClient):null}}const uN=i.z.object({rack:Te.optional(),keys:je.array().optional(),names:i.z.string().array().optional(),types:i.z.string().array().optional(),includeStatus:i.z.boolean().optional(),internal:i.z.boolean().optional(),snapshot:i.z.boolean().optional(),searchTerm:i.z.string().optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),Ku=i.z.union([i.z.object({key:je,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),i.z.object({name:i.z.string(),includeStatus:i.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),i.z.object({type:i.z.string(),rack:Te.optional()}).transform(({type:t,rack:e})=>({types:[t],rack:e}))]),lN=uN,hN=i.z.union([Ku,lN]),fN=t=>i.z.object({tasks:T.nullableZ(yn(t))}),dN="/hardware/task/retrieve",pN="/hardware/task/create",yN="/hardware/task/delete",mN="/hardware/task/copy",gN=t=>i.z.object({tasks:Hu(t).array()}),wN=t=>i.z.object({tasks:yn(t).array()}),bN=i.z.object({keys:je.array()}),vN=i.z.object({}),TN=i.z.object({key:je,name:i.z.string(),snapshot:i.z.boolean()}),zN=t=>i.z.object({task:yn(t)});let Ju=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=gN(n),a=wN(n),o=await w(this.client,pN,{tasks:T.toArray(e)},s,a),c=this.sugar(o.tasks,n);return r?c[0]:c}async delete(e){await w(this.client,yN,{keys:T.toArray(e)},bN,vN)}async retrieve({schemas:e,...n}){const r=Ku.safeParse(n).success,a=(await w(this.client,dN,n,hN,fN(e))).tasks,o=this.sugar(a,e);return ue("Task",n,o,r),r?o[0]:o}async copy(e,n,r){const s=zN(),a=await w(this.client,mN,{key:e,name:n,snapshot:r},TN,s);return this.sugar(a.task)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw Qe;return await Wu(e,this.ontologyClient)}sugar(e,n){const r=!Array.isArray(e),s=T.toArray(e).map(({key:a,name:o,type:c,config:l,status:u,internal:h,snapshot:d})=>new Gu({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 ei({...e,frameClient:this.frameClient}):await Xu({...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 el({...e,frameClient:this.frameClient,name:r})}const n=async()=>{const{task:r}=e;return(await this.retrieve({key:r})).name};return await Qu({frameClient:this.frameClient,name:n,...e})}};const Qs=t=>({type:"task",key:t}),Xu=async({frameClient:t,task:e,type:n,args:r})=>(await ei({frameClient:t,commands:[{args:r,task:e,type:n}]}))[0],ei=async({frameClient:t,commands:e})=>{if(t==null)throw Qe;const n=await t.openWriter(ps),r=e.map(s=>({...s,key:zp.create()}));return await n.write(ps,r),await n.close(),r.map(s=>s.key)},Qu=async({frameClient:t,task:e,type:n,timeout:r,name:s,statusDataZ:a,args:o})=>(await el({frameClient:t,commands:[{args:o,task:e,type:n}],timeout:r,statusDataZ:a,name:s}))[0],el=async({frameClient:t,commands:e,timeout:n=S.seconds(10),statusDataZ:r,name:s})=>{if(t==null)throw Qe;const a=await t.openStreamer(ds),o=await ei({frameClient:t,commands:e}),c=new S(n);let l=[],u;const h=new Promise((d,f)=>{u=setTimeout(()=>{(async()=>{const v=e.map($=>$.task);f(await EN("command",s,c,v))})()},c.milliseconds)});try{for(;;){const d=await Promise.race([a.read(),h]),f=Xs(r).parse(d.at(-1)[ds]);if(o.includes(f.key)&&(l=[...l.filter(v=>v.key!==f.key),f],l.length===o.length))return l}}finally{clearTimeout(u),a.close()}},EN=async(t,e,n,r)=>{const s=rd.capitalize(t),a=n.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=T.toArray(await e());const c=ns.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 ${ns.naturalLanguageJoin(r)} timed out after ${a}`)}},NN=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:ps,Client:Ju,DELETE_CHANNEL_NAME:cN,SET_CHANNEL_NAME:oN,STATUS_CHANNEL_NAME:ds,Task:Gu,commandZ:iN,keyZ:je,newZ:Hu,ontologyID:Qs,rackKey:aN,statusDetailsZ:Yu,statusZ:Xs,taskZ:yn},Symbol.toStringTag,{value:"Module"})),Ge=sc.keyZ,mn=sc.labelZ,ON="labeled_by",$N="sy_label_set",SN="sy_label_delete",tl=mn.extend({key:Ge.optional()}),IN=i.object({labels:tl.array()}),AN=i.object({labels:mn.array()}),kN=i.object({keys:Ge.array()}),nl=i.object({id:j,labels:Ge.array(),replace:i.boolean().optional()}),xN=nl.omit({replace:!0}),Ar=i.object({}),ZN="/label/create",CN="/label/delete",RN="/label/set",_N="/label/remove",jN="/label/retrieve",MN=i.object({keys:Ge.array().optional(),for:j.optional(),searchTerm:i.string().optional(),offset:i.number().optional(),limit:i.number().optional()}),DN=i.object({key:Ge}).transform(({key:t})=>({keys:[t]})),PN=i.union([DN,MN]),UN=i.object({labels:T.nullableZ(mn)});let rl=class{type="label";client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await w(this.client,jN,e,PN,UN);return ue("Label",e,r.labels,n),n?r.labels[0]:r.labels}async label(e,n,r={}){await w(this.client,RN,{id:e,labels:n,replace:r.replace},nl,Ar)}async remove(e,n){await w(this.client,_N,{id:e,labels:n},xN,Ar)}async create(e){const n=Array.isArray(e),r=await w(this.client,ZN,{labels:T.toArray(e)},IN,AN);return n?r.labels:r.labels[0]}async delete(e){await w(this.client,CN,{keys:T.toArray(e)},kN,Ar)}};const LN=t=>({type:"label",key:t}),BN=Object.freeze(Object.defineProperty({__proto__:null,Client:rl,DELETE_CHANNEL_NAME:SN,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:ON,SET_CHANNEL_NAME:$N,keyZ:Ge,labelZ:mn,newZ:tl,ontologyID:LN},Symbol.toStringTag,{value:"Module"})),te=i.z.uuid(),ti=i.z.string().min(1),gn=i.z.object({key:te,name:ti,timeRange:P.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:i.z.string().optional(),labels:mn.array().or(i.z.null().transform(()=>{})).optional(),get parent(){return gn.optional().nullable().transform(t=>t===void 0?null:t)}}),sl=gn.omit({parent:!0,labels:!0}).partial({key:!0}),qN="sy_range_alias_set",FN="sy_range_alias_delete",VN=i.z.object({range:te,aliases:i.z.string().array()}),YN=i.z.object({aliases:i.z.record(i.z.string(),D)}),HN=i.z.object({range:te,aliases:i.z.record(D,i.z.string())}),WN=i.z.unknown(),GN=i.z.object({range:te,channels:D.array()}),KN=i.z.unknown(),JN=i.z.object({range:te}),XN=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())}),QN=i.z.object({range:te,channels:D.array()}),eO=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())});class ce{static SET_ENDPOINT="/range/alias/set";static RESOLVE_ENDPOINT="/range/alias/resolve";static LIST_ENDPOINT="/range/alias/list";static RETRIEVE_ENDPOINT="/range/alias/retrieve";static DELETE_ENDPOINT="/range/alias/delete";frameClient;cache=new Map;client;rangeKey;constructor(e,n,r){this.rangeKey=e,this.cache=new Map,this.client=r,this.frameClient=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 w(this.client,ce.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:n},VN,YN);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 w(this.client,ce.SET_ENDPOINT,{range:this.rangeKey,aliases:e},HN,WN)}async list(){return(await w(this.client,ce.LIST_ENDPOINT,{range:this.rangeKey},JN,XN)).aliases}async retrieve(e){const n=typeof e=="number",r=await w(this.client,ce.RETRIEVE_ENDPOINT,{range:this.rangeKey,channels:T.toArray(e)},QN,eO);return n?r.aliases[e]:r.aliases}async delete(e){await w(this.client,ce.DELETE_ENDPOINT,{range:this.rangeKey,channels:T.toArray(e)},GN,KN)}}const tO=i.z.object({alias:i.z.string().optional(),channel:D,range:te}),il="---",nO=t=>`${t.range}${il}${t.channel}`,rO=t=>{const[e,n]=t.split(il);return{range:e,channel:Number(n)}},sO="sy_range_kv_set",iO="sy_range_kv_delete",ni=i.z.object({range:te,key:i.z.string(),value:i.z.string()}),aO=({range:t,key:e})=>`${t}<--->${e}`,oO=i.z.object({range:te,keys:i.z.string().array()}),cO=i.z.object({pairs:T.nullableZ(ni)}),uO=i.z.object({range:te,pairs:ni.array()}),lO=i.z.object({range:te,keys:i.z.string().array()});class tt{static GET_ENDPOINT="/range/kv/get";static SET_ENDPOINT="/range/kv/set";static DELETE_ENDPOINT="/range/kv/delete";rangeKey;client;constructor(e,n){this.rangeKey=e,this.client=n}async get(e){const n=await w(this.client,tt.GET_ENDPOINT,{range:this.rangeKey,keys:T.toArray(e)},oO,cO);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;Wa(e)?r=Object.entries(e).map(([s,a])=>({range:this.rangeKey,key:s,value:a})):r=[{range:this.rangeKey,key:e,value:n}],await w(this.client,tt.SET_ENDPOINT,{range:this.rangeKey,pairs:r},uO,i.z.unknown())}async delete(e){await w(this.client,tt.DELETE_ENDPOINT,{range:this.rangeKey,keys:T.toArray(e)},lO,i.z.unknown())}}const hO="sy_range_set",fO="sy_range_delete";class al{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:n=P.ZERO,key:r,color:s,parent:a,labels:o},{frameClient:c,kv:l,aliaser:u,channels:h,labelClient:d,ontologyClient:f,rangeClient:v}){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=v}get ontologyID(){return wt(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 Ye(`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:wt(this.key)})}async addLabel(...e){await this.labelClient.label(wt(this.key),e)}async removeLabel(...e){await this.labelClient.remove(wt(this.key),e)}static sort(e,n){return P.sort(e.timeRange,n.timeRange)}}const dO=i.z.object({keys:te.array().optional(),names:i.z.array(i.z.string()).optional(),searchTerm:i.z.string().optional(),overlapsWith:P.z.optional(),limit:i.z.number().int().optional(),offset:i.z.number().int().optional(),hasLabels:Ge.array().optional(),includeLabels:i.z.boolean().optional(),includeParent:i.z.boolean().optional()}),pO=dO.or(te.array().transform(t=>({keys:t}))).or(te.transform(t=>({keys:[t]}))).or(i.z.string().transform(t=>({names:[t]}))).or(i.z.string().array().transform(t=>({names:t}))).or(P.z.transform(t=>({overlapsWith:t}))),yO="/range/retrieve",mO=i.z.object({ranges:T.nullableZ(gn)});let ol=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(T.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(T.toArray(e))}async retrieve(e){const n=typeof e=="string",{ranges:r}=await w(this.unaryClient,yO,e,pO,mO);return ue("Range",e,r,n),n?this.sugarMany(r)[0]:this.sugarMany(r)}getKV(e){return new tt(e,this.unaryClient)}async retrieveParent(e){const n=await this.ontologyClient.retrieveParents(wt(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(cl(e))}async retrieveAlias(e,n){return await new ce(e,this.frameClient,this.unaryClient).retrieve(n)}async retrieveAliases(e,n){return await new ce(e,this.frameClient,this.unaryClient).retrieve(n)}async listAliases(e){return await new ce(e,this.frameClient,this.unaryClient).list()}async setAlias(e,n,r){await new ce(e,this.frameClient,this.unaryClient).set({[n]:r})}async deleteAlias(e,n){await new ce(e,this.frameClient,this.unaryClient).delete(n)}sugarOne(e){return new al(e,{frameClient:this.frameClient,kv:new tt(e.key,this.unaryClient),aliaser:new ce(e.key,this.frameClient,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 P(e.data?.timeRange),color:e.data?.color,labels:[],parent:null})}};const wt=t=>({type:"range",key:t}),gO=t=>({type:"range-alias",key:t}),cl=({data:t,id:{key:e},name:n})=>{const r=P.z.parse(t?.timeRange);return{key:e,name:n,timeRange:r,color:typeof t?.color=="string"?t.color:void 0,labels:[],parent:null}},wO=i.z.object({ranges:gn.array()}),bO=i.z.object({parent:j.optional(),ranges:sl.array()}),vO=i.z.object({keys:te.array()}),TO=i.z.object({}),zO=i.z.object({key:te,name:ti}),EO=i.z.object({}),NO="/range/create",OO="/range/delete",$O="/range/rename";class ul{client;constructor(e){this.client=e}async rename(e,n){await w(this.client,$O,{key:e,name:n},zO,EO)}async create(e,n){return(await w(this.client,NO,{ranges:e,...n},bO,wO)).ranges}async delete(e){await w(this.client,OO,{keys:e},vO,TO)}}const SO=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:ce,Client:ol,DELETE_ALIAS_CHANNEL_NAME:FN,DELETE_CHANNEL_NAME:fO,KV:tt,KV_DELETE_CHANNEL:iO,KV_SET_CHANNEL:sO,Range:al,SET_ALIAS_CHANNEL_NAME:qN,SET_CHANNEL_NAME:hO,Writer:ul,aliasKey:nO,aliasOntologyID:gO,aliasZ:tO,convertOntologyResourceToPayload:cl,decodeDeleteAliasChange:rO,keyZ:te,kvPairKey:aO,kvPairZ:ni,nameZ:ti,newZ:sl,ontologyID:wt,payloadZ:gn},Symbol.toStringTag,{value:"Module"})),IO=t=>i.object({parent:j.optional(),statuses:Hc(t).array()}),AO=t=>i.object({statuses:hn(t).array()}),kO=i.object({keys:rr.array()}),xO=i.object({}),ZO="/status/set",CO="/status/delete",RO="/status/retrieve",_O=i.object({keys:rr.array().optional(),searchTerm:i.string().optional(),offset:i.number().optional(),limit:i.number().optional(),includeLabels:i.boolean().optional(),hasLabels:Ge.array().optional()}),jO=i.object({key:rr,includeLabels:i.boolean().optional()}).transform(({key:t,includeLabels:e})=>({keys:[t],includeLabels:e})),MO=i.union([jO,_O]),DO=t=>i.object({statuses:T.nullableZ(hn(t))});let ll=class{type="status";client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await w(this.client,RO,e,MO,DO(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 w(this.client,ZO,{statuses:T.toArray(e),parent:n.parent},IO(n.detailsSchema),AO(n.detailsSchema))).statuses;return r?a:a[0]}async delete(e){await w(this.client,CO,{keys:T.toArray(e)},kO,xO)}};const PO=Object.freeze(Object.defineProperty({__proto__:null,Client:ll,DELETE_CHANNEL_NAME:OT,SET_CHANNEL_NAME:NT,keyZ:rr,newZ:Hc,ontologyID:$T,statusZ:hn},Symbol.toStringTag,{value:"Module"})),UO="/api/v1/";class hl{url;unary;stream;secure;constructor(e,n={},r=!1){this.secure=r,this.url=e.child(UO);const s=new it.JSONCodec;this.unary=Uf(new Pf(this.url,s,this.secure),n),this.stream=new Vf(this.url,s,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const lt=i.z.uuid(),hr=i.z.object({key:lt,name:i.z.string(),data:ve.unknownZ.or(i.z.string().transform(ke))}),fl=hr.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),xe=i.z.uuid(),fr=i.z.object({key:xe,name:i.z.string().min(1,"Name is required"),layout:ve.unknownZ.or(i.z.string().transform(ke))}),dl=fr.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),pl=fr.omit({layout:!0}).extend({layout:i.z.string().transform(ke)}),LO="/workspace/lineplot/retrieve",BO="/workspace/lineplot/create",qO="/workspace/lineplot/rename",FO="/workspace/lineplot/set-data",VO="/workspace/lineplot/delete",YO=i.z.object({key:lt,name:i.z.string()}),HO=i.z.object({key:lt,data:i.z.string()}),WO=i.z.object({keys:lt.array()}),GO=i.z.object({keys:lt.array()}),yl=i.z.object({key:lt}).transform(({key:t})=>({keys:[t]})),ml=i.z.union([yl,GO]),KO=i.z.object({linePlots:T.nullableZ(hr)}),JO=i.z.object({workspace:xe,linePlots:fl.array()}),XO=i.z.object({linePlots:hr.array()}),kr=i.z.object({});let gl=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await w(this.client,BO,{workspace:e,linePlots:T.toArray(n)},JO,XO);return r?s.linePlots:s.linePlots[0]}async rename(e,n){await w(this.client,qO,{key:e,name:n},YO,kr)}async setData(e,n){await w(this.client,FO,{key:e,data:JSON.stringify(n)},HO,kr)}async retrieve(e){const n=yl.safeParse(e).success,r=await w(this.client,LO,e,ml,KO);return ue("LinePlot",e,r.linePlots,n),n?r.linePlots[0]:r.linePlots}async delete(e){await w(this.client,VO,{keys:T.toArray(e)},WO,kr)}};const QO=t=>({type:"lineplot",key:t}),e$=Object.freeze(Object.defineProperty({__proto__:null,Client:gl,keyZ:lt,linePlotZ:hr,newZ:fl,ontologyID:QO,retrieveArgsZ:ml},Symbol.toStringTag,{value:"Module"})),ht=i.z.uuid(),dr=i.z.object({key:ht,name:i.z.string(),data:ve.unknownZ.or(i.z.string().transform(ke))}),wl=dr.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),t$="/workspace/log/retrieve",n$="/workspace/log/create",r$="/workspace/log/rename",s$="/workspace/log/set-data",i$="/workspace/log/delete",a$=i.z.object({key:ht,name:i.z.string()}),o$=i.z.object({key:ht,data:i.z.string()}),c$=i.z.object({keys:ht.array()}),u$=i.z.object({keys:ht.array()}),bl=i.z.object({key:ht}).transform(({key:t})=>({keys:[t]})),vl=i.z.union([bl,u$]),l$=i.z.object({logs:T.nullableZ(dr)}),h$=i.z.object({workspace:xe,logs:wl.array()}),f$=i.z.object({logs:dr.array()}),xr=i.z.object({});let Tl=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await w(this.client,n$,{workspace:e,logs:T.toArray(n)},h$,f$);return r?s.logs:s.logs[0]}async rename(e,n){await w(this.client,r$,{key:e,name:n},a$,xr)}async setData(e,n){await w(this.client,s$,{key:e,data:JSON.stringify(n)},o$,xr)}async retrieve(e){const n=bl.safeParse(e).success,r=await w(this.client,t$,e,vl,l$);return ue("Log",e,r.logs,n),n?r.logs[0]:r.logs}async delete(e){await w(this.client,i$,{keys:T.toArray(e)},c$,xr)}};const d$=t=>({type:"log",key:t}),p$=Object.freeze(Object.defineProperty({__proto__:null,Client:Tl,keyZ:ht,logZ:dr,newZ:wl,ontologyID:d$,retrieveArgsZ:vl},Symbol.toStringTag,{value:"Module"})),Ke=i.z.uuid(),pr=i.z.object({key:Ke,name:i.z.string(),data:ve.unknownZ.or(i.z.string().transform(ke)),snapshot:i.z.boolean()}),zl=pr.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),ri=pr.extend({data:i.z.string().transform(ke)}),jt=i.z.uuid(),El=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()}),Nl=i.z.object({key:i.z.string(),name:i.z.string(),regions:El.array()}),Ol=i.z.object({key:i.z.string(),position:Is.xy,orientation:Hd.outer}),y$=i.z.object({zoom:i.z.number().positive().default(1),position:Is.xy}),$l=i.z.object({svg:i.z.string().min(1,"SVG is required"),states:Nl.array(),variant:i.z.string().min(1,"Variant is required"),handles:Ol.array(),scale:i.z.number().positive().default(1),scaleStroke:i.z.boolean().default(!1),previewViewport:y$.default({zoom:1,position:{x:0,y:0}})}),yr=i.z.object({key:jt,version:i.z.literal(1).optional().default(1),name:i.z.string().min(1,"Name is required"),data:$l}),Sl=yr.partial({key:!0}),m$="/workspace/schematic/symbol/retrieve",g$="/workspace/schematic/symbol/create",w$="/workspace/schematic/symbol/rename",b$="/workspace/schematic/symbol/delete",v$="/workspace/schematic/symbol/retrieve_group",T$=i.z.object({symbols:Sl.array(),parent:j}),z$=i.z.object({key:jt,name:i.z.string()}),E$=i.z.object({keys:jt.array()}),N$=i.z.object({keys:jt.array().optional(),searchTerm:i.z.string().optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),O$=i.z.object({key:jt}).transform(({key:t})=>({keys:[t]})),$$=i.z.union([O$,N$]),S$=i.z.object({symbols:T.nullableZ(yr)}),I$=i.z.object({symbols:yr.array()}),da=i.z.object({}),A$=i.z.object({}),k$=i.z.object({group:Kn}),x$="sy_schematic_symbol_set",Z$="sy_schematic_symbol_delete";let Il=class{client;constructor(e){this.client=e}async create(e){const n="symbols"in e,r=n?e.symbols:[e],s=await w(this.client,g$,{symbols:r,parent:e.parent},T$,I$);return n?s.symbols:s.symbols[0]}async rename(e,n){await w(this.client,w$,{key:e,name:n},z$,da)}async retrieve(e){const n="key"in e,r=await w(this.client,m$,e,$$,S$);return ue("Schematic Symbol",e,r.symbols,n),n?r.symbols[0]:r.symbols}async delete(e){await w(this.client,b$,{keys:T.toArray(e)},E$,da)}async retrieveGroup(){return(await w(this.client,v$,{},A$,k$)).group}};const C$=t=>({type:"schematic_symbol",key:t}),R$=Object.freeze(Object.defineProperty({__proto__:null,Client:Il,DELETE_CHANNEL_NAME:Z$,SET_CHANNEL_NAME:x$,handleZ:Ol,keyZ:jt,newZ:Sl,ontologyID:C$,regionZ:El,specZ:$l,stateZ:Nl,symbolZ:yr},Symbol.toStringTag,{value:"Module"})),_$="/workspace/schematic/retrieve",j$="/workspace/schematic/create",M$="/workspace/schematic/rename",D$="/workspace/schematic/set-data",P$="/workspace/schematic/delete",U$="/workspace/schematic/copy",L$=i.z.object({key:Ke,name:i.z.string()}),B$=i.z.object({key:Ke,data:i.z.string()}),q$=i.z.object({keys:Ke.array()}),F$=i.z.object({key:Ke,name:i.z.string(),snapshot:i.z.boolean()}),V$=i.z.object({keys:Ke.array()}),Al=i.z.object({key:Ke}).transform(({key:t})=>({keys:[t]})),kl=i.z.union([Al,V$]),Y$=i.z.object({schematics:T.nullableZ(ri)}),H$=i.z.object({workspace:xe,schematics:zl.array()}),W$=i.z.object({schematics:ri.array()}),G$=i.z.object({schematic:pr}),Zr=i.z.object({});let xl=class{symbols;client;constructor(e){this.client=e,this.symbols=new Il(e)}async create(e,n){const r=Array.isArray(n),s=await w(this.client,j$,{workspace:e,schematics:T.toArray(n)},H$,W$);return r?s.schematics:s.schematics[0]}async rename(e,n){await w(this.client,M$,{key:e,name:n},L$,Zr)}async setData(e,n){await w(this.client,D$,{key:e,data:JSON.stringify(n)},B$,Zr)}async retrieve(e){const n=Al.safeParse(e).success,r=await w(this.client,_$,e,kl,Y$);return ue("Schematic",e,r.schematics,n),n?r.schematics[0]:r.schematics}async delete(e){await w(this.client,P$,{keys:T.toArray(e)},q$,Zr)}async copy(e){return(await w(this.client,U$,e,F$,G$)).schematic}};const K$=t=>({type:"schematic",key:t}),J$=Object.freeze(Object.defineProperty({__proto__:null,Client:xl,keyZ:Ke,newZ:zl,ontologyID:K$,remoteZ:ri,retrieveArgsZ:kl,schematicZ:pr,symbol:R$},Symbol.toStringTag,{value:"Module"})),ft=i.z.uuid(),si=i.z.object({key:ft,name:i.z.string(),data:ve.unknownZ.or(i.z.string().transform(ke))}),Zl=si.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),ii=si.extend({data:i.z.string().transform(ke)}),X$="/workspace/table/retrieve",Q$="/workspace/table/create",eS="/workspace/table/rename",tS="/workspace/table/set-data",nS="/workspace/table/delete",rS=i.z.object({key:ft,name:i.z.string()}),sS=i.z.object({key:ft,data:i.z.string()}),iS=i.z.object({keys:ft.array()}),aS=i.z.object({keys:ft.array()}),Cl=i.z.object({key:ft}).transform(({key:t})=>({keys:[t]})),Rl=i.z.union([Cl,aS]),oS=i.z.object({tables:T.nullableZ(ii)}),cS=i.z.object({workspace:xe,tables:Zl.array()}),uS=i.z.object({tables:ii.array()}),Cr=i.z.object({});let _l=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await w(this.client,Q$,{workspace:e,tables:T.toArray(n)},cS,uS);return r?s.tables:s.tables[0]}async rename(e,n){await w(this.client,eS,{key:e,name:n},rS,Cr)}async setData(e,n){await w(this.client,tS,{key:e,data:JSON.stringify(n)},sS,Cr)}async retrieve(e){const n=Cl.safeParse(e).success,r=await w(this.client,X$,e,Rl,oS);return ue("Table",e,r.tables,n),n?r.tables[0]:r.tables}async delete(e){await w(this.client,nS,{keys:T.toArray(e)},iS,Cr)}};const lS=t=>({type:"table",key:t}),hS=Object.freeze(Object.defineProperty({__proto__:null,Client:_l,keyZ:ft,newZ:Zl,ontologyID:lS,remoteZ:ii,retrieveArgsZ:Rl,tableZ:si},Symbol.toStringTag,{value:"Module"})),pa="/workspace/retrieve",fS="/workspace/create",dS="/workspace/rename",pS="/workspace/set-layout",yS="/workspace/delete",ya=i.z.object({keys:xe.array().optional(),searchTerm:i.z.string().optional(),author:We.optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),mS=i.z.object({workspaces:dl.array()}),gS=i.z.object({key:xe,name:i.z.string()}),wS=i.z.object({key:xe,layout:ve.unknownZ.transform(t=>JSON.stringify(t))}),bS=i.z.object({keys:xe.array()}),ma=i.z.object({workspaces:T.nullableZ(fr)}),vS=i.z.object({workspaces:pl.array()}),Rr=i.z.object({}),TS="sy_workspace_set",zS="sy_workspace_delete";class jl{schematics;lineplots;logs;tables;client;constructor(e){this.client=e,this.schematics=new xl(e),this.lineplots=new gl(e),this.logs=new Tl(e),this.tables=new _l(e)}async create(e){const n=Array.isArray(e),r=await w(this.client,fS,{workspaces:T.toArray(e)},mS,vS);return n?r.workspaces:r.workspaces[0]}async rename(e,n){await w(this.client,dS,{key:e,name:n},gS,Rr)}async setLayout(e,n){await w(this.client,pS,{key:e,layout:n},wS,Rr)}async retrieve(e){let n;const r=typeof e!="string";typeof e=="string"||Array.isArray(e)?n={keys:T.toArray(e)}:n=e;const s=await w(this.client,pa,n,ya,ma);return r?s.workspaces:s.workspaces[0]}async retrieveByAuthor(e){return(await w(this.client,pa,{author:e},ya,ma)).workspaces}async delete(e){await w(this.client,yS,{keys:T.toArray(e)},bS,Rr)}}const ES=t=>({type:"workspace",key:t}),NS=Object.freeze(Object.defineProperty({__proto__:null,Client:jl,DELETE_CHANNEL_NAME:zS,SET_CHANNEL_NAME:TS,keyZ:xe,newZ:dl,ontologyID:ES,remoteZ:pl,workspaceZ:fr},Symbol.toStringTag,{value:"Module"})),Ml=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:S.z.default(S.seconds(30)),secure:i.z.boolean().optional().default(!1),name:i.z.string().optional(),retry:Zs.breakerConfigZ.optional()});class Dl extends xu{createdAt;params;ranges;channels;auth;users;access;connectivity;ontology;workspaces;labels;statuses;hardware;control;arcs;static connectivity=Ln;transport;clientVersion="0.48.0";constructor(e){const n=Ml.parse(e),{host:r,port:s,username:a,password:o,connectivityPollFrequency:c,secure:l,retry:u}=n,h=new hl(new vt({host:r,port:Number(s)}),u,l);h.use(Tm);let d;a!=null&&o!=null&&(d=new Vz(h.unary,{username:a,password:o}),h.use(d.middleware()));const f=new Hs(new dn(h.unary)),v=new du(h.unary,f);super(h.stream,h.unary,f),this.createdAt=p.now(),this.params=n,this.auth=d,this.transport=h,this.channels=new lu(this,f,h.unary,v),this.connectivity=new Ln(h.unary,c,this.clientVersion,n.name),this.control=new Ru(this),this.ontology=new wc(h.unary,this);const $=new ul(this.transport.unary);this.labels=new rl(this.transport.unary),this.statuses=new ll(this.transport.unary),this.ranges=new ol(this,$,this.transport.unary,f,this.labels,this.ontology),this.access=new Tc(this.transport.unary),this.users=new yu(this.transport.unary),this.workspaces=new jl(this.transport.unary);const k=new qu(this.transport.unary),b=new Ju(this.transport.unary,this,this.ontology,this.ranges),E=new Fu(this.transport.unary,b);this.hardware=new _u(b,E,k),this.arcs=new nu(this.transport.unary,this.transport.stream)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stop()}}const OS=async t=>await Pl(t).check(),Pl=t=>{const{host:e,port:n,secure:r,name:s,retry:a}=t,o=Zs.breakerConfigZ.optional().parse(a),c=new vt({host:e,port:Number(n)}),l=new hl(c,o,r);return new Ln(l.unary,void 0,"0.48.0",s)},Ul={host:"localhost",port:9090,username:"synnax",password:"seldon",retry:{maxRetries:4,baseInterval:S.seconds(1),scale:1.5}},$S=t=>new Dl({...Ul,...t});exports.AuthError=Gt;exports.Channel=Un;exports.ContiguityError=wm;exports.DataType=R;exports.Density=Q;exports.DisconnectedError=gm;exports.Frame=F;exports.MultiSeries=Po;exports.MultipleFoundError=Jt;exports.NotFoundError=Kt;exports.QueryError=Ye;exports.Rate=se;exports.RouteError=is;exports.Series=ee;exports.Synnax=Dl;exports.TEST_CLIENT_PARAMS=Ul;exports.TimeRange=P;exports.TimeSpan=S;exports.TimeStamp=p;exports.UnexpectedError=zt;exports.ValidationError=H;exports.access=pg;exports.arc=VT;exports.channel=mz;exports.checkConnection=OS;exports.connection=Wz;exports.control=NE;exports.createTestClient=$S;exports.device=LE;exports.framer=wE;exports.group=Pm;exports.hardware=OE;exports.isCalculated=St;exports.label=BN;exports.lineplot=e$;exports.log=p$;exports.newConnectionChecker=Pl;exports.ontology=Xm;exports.policy=dg;exports.rack=sN;exports.ranger=SO;exports.schematic=J$;exports.status=PO;exports.synnaxParamsZ=Ml;exports.table=hS;exports.task=NN;exports.user=Mz;exports.workspace=NS;
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 ee({data:l,dataType:u.dataType});r.push(u.key),s.push(h)}return new F(r,s)}}class xu{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(ye.matches(n))return;throw n}}}closeSend(){this.stream.closeSend()}send(e){const n=this.stream.send(e);if(n!=null)throw n}}const _n=new g(-1);var ti=(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))(ti||{}),Cu=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(Cu||{});const $O=i.z.object({command:i.z.enum(ti),span:g.z.optional(),bounds:x.z.optional(),stamp:m.z.optional(),keys:U.array().optional(),chunkSize:i.z.number().optional()}),IO=i.z.object({variant:i.z.enum(Cu),ack:i.z.boolean(),command:i.z.enum(ti),error:Re.payloadZ.optional().nullable(),frame:Hn.optional()});class fn{stream;adapter;value;constructor(e,n){this.stream=new xu("Iterator",e),this.value=new F,this.adapter=n}static async _open(e,n,r,s,a={}){const o=await Wn.open(r,n),c=await s.stream("/frame/iterate",$O,IO),l=new fn(c,o);return await l.execute({command:0,keys:Array.from(o.keys),bounds:new x(e),chunkSize:a.chunkSize??1e5}),l}async next(e=_n){return await this.execute({command:1,span:new g(e)})}async prev(e=_n){return await this.execute({command:2,span:new g(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new m(e)})}async seekGE(e){return await this.execute({command:6,stamp:new m(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new ZO(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 ZO{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 xO{retriever;streamClient;constructor(e,n){this.retriever=e,this.streamClient=n}async read(e){const{channels:n,timeRange:r,channelNames:s}=e,a=await this.retriever.retrieve(n),o=new Set;a.forEach(u=>{o.add(u.key),u.index!==0&&o.add(u.index)});const c=Array.from(o).filter(u=>!a.some(h=>h.key===u));if(c.length>0){const u=await this.retriever.retrieve(c);a.push(...u)}const l=await fn._open(r,Array.from(o),this.retriever,this.streamClient);return CO({iterator:l,channelPayloads:a,headers:s})}}const CO=({iterator:t,channelPayloads:e,headers:n})=>{const r=dm.getOS()==="Windows"?`\r
64
+ `:`
65
+ `,s=new TextEncoder;let a=!1,o=!1;const c=RO(e),{columns:l,columnsByIndexKey:u,emptyGroupStrings:h}=_O(e,c,n);let d=[],f=0,O=[];const S=z=>{for(const[E]of c){const A=z.get(E);if(A.length===0)continue;const R=(u.get(E)??[]).map(j=>z.get(j.key));for(let j=0;j<A.length;j++){const ie=A.at(j,!0),ae=R.map(fe=>Zi.formatValue(fe.at(j,!0)));O.push({time:ie,values:ae,indexKey:E})}}},Z=(z,E=!1)=>{O.length>0&&(O.sort((R,j)=>Number(R.time-j.time)),f>0&&(d=d.slice(f),f=0),d=MO(d,O),O=[]);const A=[],P=d.length;for(;f<P&&A.length<z;){const R=d[f].time;if(!E&&d[P-1].time===R)break;const j=new Map;for(;f<P&&d[f].time===R;){const ae=d[f++];j.set(ae.indexKey,ae)}const ie=[];for(const[ae]of c){const fe=j.get(ae);ie.push(fe?.values.join(",")??h.get(ae)??"")}A.push(ie.join(","))}return A};return new ReadableStream({async pull(z){try{if(o||(await t.seekFirst(),o=!0),!a){const R=l.map(j=>Zi.formatValue(j.header)).join(",");z.enqueue(s.encode(`${R}${r}`)),a=!0}d.length-f+O.length<ya&&await t.next()&&S(t.value);const A=Z(ya);if(A.length>0&&z.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&&z.enqueue(s.encode(`${j.join(r)}${r}`)),await t.close(),z.close();return}S(t.value)}}catch(E){await t.close(),z.error(E)}},async cancel(){await t.close()}})},RO=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},_O=(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 nt(`Channel ${h} not found`);const f={key:h,header:n?.get(h)??n?.get(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}},MO=(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},ya=1e3,jO=i.z.object({keys:i.z.number().array(),downsampleFactor:i.z.int(),throttleRate:G.z.optional()}),UO=i.z.object({frame:Hn}),ma=i.z.object({channels:dt,downsampleFactor:i.z.int().default(1),throttleRate:G.z.default(new G(0)),useHighPerformanceCodec:i.z.boolean().default(!0)}),ni=ma.or(dt.transform(t=>ma.parse({channels:t}))),Ru=(t,e)=>async n=>{const r=ni.parse(n),s=await Wn.open(t,r.channels);r.useHighPerformanceCodec&&(e=e.withCodec(new AO(s.codec)));const a=await e.stream("/frame/stream",jO,UO),o=new DO(a,s,r.downsampleFactor,r.throttleRate);a.send({keys:Array.from(s.keys),downsampleFactor:r.downsampleFactor,throttleRate:r.throttleRate});const[,c]=await a.receive();if(c!=null)throw c;return o},_u=async(t,e,n)=>await Ru(t,e)(n);class DO{stream;adapter;downsampleFactor;throttleRate;constructor(e,n,r=1,s=new G(0)){this.stream=new xu("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(ye.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 Kn{wrapped_=null;breaker;opener;config;constructor(e,n,r={}){this.opener=e,this.config=ni.parse(n);const{maxRetries:s=5e3,baseInterval:a=g.seconds(1),scale:o=1}=r??{};this.breaker=new ks.Breaker({maxRetries:s,baseInterval:a,scale:o})}static async open(e,n,r){const s=new Kn(e,n,r);return await s.runStreamer(),s}async runStreamer(){for(;;)try{this.wrapped_!=null&&this.wrapped_.close(),this.wrapped_=await this.opener(this.config),this.breaker.reset();return}catch(e){if(this.wrapped_=null,!await this.breaker.wait())throw e;console.error("failed to open streamer",e);continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=dt.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(ye.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(ye.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 Mu extends nm.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 Wt=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(Wt||{});const PO=new g(-1);class ns extends Ne.sub("writer_closed"){constructor(){super("WriterClosed")}}const LO=i.z.enum(Wt).or(i.z.enum(["persist","stream","persistStream"]).transform(t=>{switch(t){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),ju=i.z.object({start:m.z.optional(),controlSubject:ue.subjectZ.optional(),authorities:i.z.union([ue.authorityZ.transform(t=>[t]),ue.authorityZ.array()]).default([ue.ABSOLUTE_AUTHORITY]),mode:LO.default(1),errOnUnauthorized:i.z.boolean().default(!1),enableAutoCommit:i.z.boolean().default(!0),autoIndexPersistInterval:g.z.default(g.SECOND),useHighPerformanceCodec:i.z.boolean().default(!0)}),BO=ju.extend({keys:U.array().optional()}),ga=ju.extend({channels:dt}),Uu=ga.or(dt.transform(t=>ga.parse({channels:t,start:m.now()}))),qO=i.z.object({command:i.z.enum(Oe),config:BO.optional(),frame:Hn.optional(),buffer:i.z.instanceof(Uint8Array).optional()}),FO=i.z.object({command:i.z.enum(Oe),end:m.z,err:Re.payloadZ.optional()}),YO=i.z.tuple([i.z.union([i.z.record(U.or(Ce),ue.authorityZ),U.or(Ce),ue.authorityZ]),ue.authorityZ.optional()]).transform(([t,e])=>{if(ue.authorityZ.safeParse(t).success)return{keys:[],authorities:[t]};if(U.or(Ce).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 Du=class Pu{stream;adapter;closeErr=null;constructor(e,n){this.stream=e,this.adapter=n}static async _open(e,n,r){const s=Uu.parse(r),a=await ei.open(e,s.channels);s.useHighPerformanceCodec&&(n=n.withCodec(new kO(a.codec)));const o=await n.stream("/frame/write",qO,FO),c=new Pu(o,a);return await c.execute({command:Oe.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:Oe.Write,frame:r.toPayload()})}async setAuthority(e,n){if(this.closeErr!=null)throw this.closeErr;const r=YO.parse([e,n]),s={keys:await this.adapter.adaptParams(r.keys),authorities:r.authorities};await this.execute({command:Oe.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:Oe.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(ns.matches(this.closeErr))return null;throw this.closeErr}const[n,r]=await this.stream.receive();r!=null?this.closeErr=ye.matches(r)?new ns:r:this.closeErr=Re.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=Re.decode(r?.err);if(a!=null&&await this.closeInternal(a),r?.command==e.command)return r}}};const Lu=H("framer"),GO=Lu("");let Bu=class{streamClient;retriever;deleter;reader;constructor(e,n,r){this.streamClient=e,this.retriever=r,this.deleter=new zO(n),this.reader=new xO(r,e)}async openIterator(e,n,r){return await fn._open(e,n,this.retriever,this.streamClient,r)}async openWriter(e){return await Du._open(this.retriever,this.streamClient,e)}async openStreamer(e){return await _u(this.retriever,this.streamClient,e)}async write(e,n,r){if(r==null){const a=n,o=await this.openWriter({start:e,channels:Object.keys(a),mode:Wt.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:g.MAX});return await o.write(a),await o.close()}const s=await this.openWriter({start:e,channels:n,mode:Wt.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:g.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}=pe(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}=pe(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(_n),s.push(r.value)}finally{await r.close()}return s}async delete(e,n){const{normalized:r,variant:s}=pe(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 VO=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:PO,AUTO_SPAN:_n,Client:Bu,Frame:F,HardenedStreamer:Kn,Iterator:fn,ObservableStreamer:Mu,TYPE_ONTOLOGY_ID:GO,Writer:Du,WriterClosedError:ns,WriterCommand:Oe,WriterMode:Wt,createStreamOpener:Ru,frameZ:Hn,ontologyID:Lu,openStreamer:_u,seriesFromPayload:Au,seriesToPayload:$u,streamerConfigZ:ni,writerConfigZ:Uu},Symbol.toStringTag,{value:"Module"})),HO=ue.ABSOLUTE_AUTHORITY,WO=ue.ZERO_AUTHORITY,KO=ue.stateZ(i.z.number()),JO=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()})`,XO=i.z.object({transfers:i.z.array(ue.transferZ(U))});class qu extends Mu{states;codec;constructor(e){super(e,n=>{const r=this.codec.decode(n.series[0].buffer,XO);return this.merge(r),[r.transfers,!0]}),this.states=new Map,this.codec=new ot.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 Fu="sy_node_1_control";let Yu=class{framer;constructor(e){this.framer=e}async openStateTracker(){const e=await Kn.open(async n=>await this.framer.openStreamer(n),Fu);return new qu(e)}};const QO=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:HO,CONTROL_STATE_CHANNEL_NAME:Fu,Client:Yu,StateTracker:qu,ZERO_AUTHORITY:WO,stateZ:KO,transferString:JO},Symbol.toStringTag,{value:"Module"})),ge=i.z.uint32(),Gu=i.z.object({rack:ge}),Vu=lt.statusZ(Gu),Jn=i.z.object({key:ge,name:i.z.string(),status:Ee.nullToUndefined(Vu)}),Hu=Jn.partial({key:!0}),Wu=t=>t?ot.JSON_CODEC.decodeString(t,me.unknownZ):{},xt=i.z.string(),Ku=i.z.object({rack:ge,device:xt}),Ju=lt.statusZ(Ku),Xn=i.z.object({key:xt,rack:ge.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:me.unknownZ.or(i.z.string().transform(Wu)),status:Ee.nullToUndefined(Ju)}),Xu=Xn.extend({properties:i.z.unknown().transform(t=>ot.JSON_CODEC.encodeString(t))}),eE="sy_device_set",tE="sy_device_delete",nE=i.z.object({devices:Xu.array()}),rE=i.z.object({devices:Xn.array()}),sE=i.z.object({keys:xt.array()}),iE=i.z.object({}),aE=i.z.object({keys:xt.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:ge.array().optional(),searchTerm:i.z.string().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeStatus:i.z.boolean().optional()}),oE=i.z.object({devices:N.nullableZ(Xn)}),cE=i.z.object({key:xt,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),uE=i.z.union([cE,aE]);let Qu=class{client;constructor(e){this.client=e}async retrieve(e){const n=typeof e=="object"&&"key"in e,r=await T(this.client,"/device/retrieve",e,uE,oE);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 T(this.client,"/device/create",{devices:N.toArray(e)},nE,rE)).devices;return n?s[0]:s}async delete(e){await T(this.client,"/device/delete",{keys:N.toArray(e)},sE,iE)}};const ri=H("device"),lE=ri(""),hE=t=>_e(ri(t)),fE=Object.freeze(Object.defineProperty({__proto__:null,Client:Qu,DELETE_CHANNEL_NAME:tE,SET_CHANNEL_NAME:eE,TYPE_ONTOLOGY_ID:lE,deviceZ:Xn,keyZ:xt,newZ:Xu,ontologyID:ri,statusDetailsZ:Ku,statusKey:hE,statusZ:Ju},Symbol.toStringTag,{value:"Module"})),dE="sy_rack_set",pE="sy_rack_delete",yE=i.z.object({keys:ge.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()}),mE=i.z.object({racks:N.nullableZ(Jn)}),gE=i.z.union([i.z.object({key:ge,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}))]),wE=yE,bE=i.z.union([gE,wE]),vE=i.z.object({racks:Hu.array()}),zE=i.z.object({racks:Jn.array()}),TE=i.z.object({keys:ge.array()}),OE=i.z.object({});let el=class{client;tasks;constructor(e,n){this.client=e,this.tasks=n}async delete(e){await T(this.client,"/rack/delete",{keys:N.toArray(e)},TE,OE)}async create(e){const n=!Array.isArray(e),r=await T(this.client,"/rack/create",{racks:N.toArray(e)},vE,zE),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,bE,mE),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 tl(s,a,this.tasks,o));return n?r[0]:r}};class tl{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 si=H("rack"),EE=si(0),NE=t=>_e(si(t)),SE=Object.freeze(Object.defineProperty({__proto__:null,Client:el,DELETE_CHANNEL_NAME:pE,Rack:tl,SET_CHANNEL_NAME:dE,TYPE_ONTOLOGY_ID:EE,keyZ:ge,newZ:Hu,ontologyID:si,rackZ:Jn,statusDetailsZ:Gu,statusKey:NE,statusZ:Vu},Symbol.toStringTag,{value:"Module"})),kE="sy_range_alias_set",AE="sy_range_alias_delete",$E=i.z.object({range:J,aliases:i.z.string().array()}),IE=i.z.object({aliases:i.z.record(i.z.string(),U)}),ZE=i.z.object({range:J,aliases:i.z.record(U,i.z.string())}),xE=i.z.unknown(),CE=i.z.object({range:J,channels:U.array()}),RE=i.z.unknown(),_E=i.z.object({range:J}),ME=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())}),jE=i.z.object({range:J,channels:U.array()}),UE=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())});class Je{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},$E,IE);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},ZE,xE)}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:N.toArray(e)},jE,UE);return n?r.aliases[e]:r.aliases}async delete(e){await T(this.client,"/range/alias/delete",{range:this.rangeKey,channels:N.toArray(e)},CE,RE)}}const DE=i.z.object({alias:i.z.string().optional(),channel:U,range:J}),nl="---",PE=t=>`${t.range}${nl}${t.channel}`,LE=t=>{const[e,n]=t.split(nl);return{range:e,channel:Number(n)}},BE="sy_range_kv_set",qE="sy_range_kv_delete",ii=i.z.object({range:J,key:i.z.string(),value:i.z.string()}),FE=({range:t,key:e})=>`${t}<--->${e}`,YE=i.z.object({range:J,keys:i.z.string().array()}),GE=i.z.object({pairs:N.nullableZ(ii)}),VE=i.z.object({range:J,pairs:ii.array()}),HE=i.z.object({range:J,keys:i.z.string().array()});class rs{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:N.toArray(e)},YE,GE);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},VE,i.z.unknown())}async delete(e){await T(this.client,"/range/kv/delete",{range:this.rangeKey,keys:N.toArray(e)},HE,i.z.unknown())}}const WE="sy_range_set",KE="sy_range_delete";class rl{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 Xe(this.key)}get payload(){let e=null;return this.parent!=null&&("payload"in this.parent?e=this.parent.payload:e=this.parent),{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels,parent:e}}async setAlias(e,n){const r=await this.channels.retrieve(e);if(r.length===0)throw new Ge(`Channel ${e} does not exist`);await this.aliaser.set({[r[0].key]:n})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(n=>n.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async retrieveLabels(){return await this.labelClient.retrieve({for:Xe(this.key)})}async addLabel(...e){await this.labelClient.label(Xe(this.key),e)}async removeLabel(...e){await this.labelClient.remove(Xe(this.key),e)}static sort(e,n){return x.sort(e.timeRange,n.timeRange)}}const JE=i.z.object({keys:J.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),overlapsWith:x.z.optional(),hasLabels:We.array().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeLabels:i.z.boolean().optional(),includeParent:i.z.boolean().optional()}),XE=JE.or(J.array().transform(t=>({keys:t}))).or(J.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}))),QE=i.z.object({ranges:N.nullableZ(hn)});let sl=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 T(this.unaryClient,"/range/retrieve",e,XE,QE);return se("Range",e,r,n),n?this.sugarMany(r)[0]:this.sugarMany(r)}getKV(e){return new rs(e,this.unaryClient)}async retrieveParent(e){const n=await this.ontologyClient.retrieveParents(Xe(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(il(e))}async retrieveAlias(e,n){return await new Je(e,this.unaryClient).retrieve(n)}async retrieveAliases(e,n){return await new Je(e,this.unaryClient).retrieve(n)}async listAliases(e){return await new Je(e,this.unaryClient).list()}async setAlias(e,n,r){await new Je(e,this.unaryClient).set({[n]:r})}async deleteAlias(e,n){await new Je(e,this.unaryClient).delete(n)}sugarOne(e){return new rl(e,{frameClient:this.frameClient,kv:new rs(e.key,this.unaryClient),aliaser:new Je(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 Xe=H("range"),eN=Xe(""),tN=t=>({type:"range-alias",key:t}),il=({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}},nN=i.z.object({ranges:hn.array()}),rN=i.z.object({parent:L.optional(),ranges:vu.array()}),sN=i.z.object({keys:J.array()}),iN=i.z.object({}),aN=i.z.object({key:J,name:Ks}),oN=i.z.object({});class al{client;constructor(e){this.client=e}async rename(e,n){await T(this.client,"/range/rename",{key:e,name:n},aN,oN)}async create(e,n){return(await T(this.client,"/range/create",{ranges:e,...n},rN,nN)).ranges}async delete(e){await T(this.client,"/range/delete",{keys:e},sN,iN)}}const cN=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:Je,Client:sl,DELETE_ALIAS_CHANNEL_NAME:AE,DELETE_CHANNEL_NAME:KE,KV:rs,KV_DELETE_CHANNEL:qE,KV_SET_CHANNEL:BE,Range:rl,SET_ALIAS_CHANNEL_NAME:kE,SET_CHANNEL_NAME:WE,TYPE_ONTOLOGY_ID:eN,Writer:al,aliasKey:PE,aliasOntologyID:tN,aliasZ:DE,convertOntologyResourceToPayload:il,decodeDeleteAliasChange:LE,keyZ:J,kvPairKey:FE,kvPairZ:ii,nameZ:Ks,newZ:vu,ontologyID:Xe,payloadZ:hn},Symbol.toStringTag,{value:"Module"})),uN=t=>i.object({parent:L.optional(),statuses:Qc(t).array()}),lN=t=>i.object({statuses:cn(t).array()}),hN=i.object({keys:Gn.array()}),fN=i.object({}),dN=i.object({keys:Gn.array().optional(),searchTerm:i.string().optional(),offset:i.int().optional(),limit:i.int().optional(),includeLabels:i.boolean().optional(),hasLabels:We.array().optional()}),pN=i.object({key:Gn,includeLabels:i.boolean().optional()}).transform(({key:t,includeLabels:e})=>({keys:[t],includeLabels:e})),yN=i.union([pN,dN]),mN=t=>i.object({statuses:N.nullableZ(cn(t))});let ol=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,yN,mN(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 T(this.client,"/status/set",{statuses:N.toArray(e),parent:n.parent},uN(n.detailsSchema),lN(n.detailsSchema))).statuses;return r?a:a[0]}async delete(e){await T(this.client,"/status/delete",{keys:N.toArray(e)},hN,fN)}};const gN=Object.freeze(Object.defineProperty({__proto__:null,Client:ol,DELETE_CHANNEL_NAME:cT,SET_CHANNEL_NAME:Qr,TYPE_ONTOLOGY_ID:uT,keyZ:Gn,newZ:Qc,ontologyID:eu,statusZ:cn},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())]),ai=t=>i.z.object({task:Me,running:i.z.boolean(),data:t,cmd:i.z.string().optional()}),oi=t=>lt.statusZ(ai(t)),wN=t=>ai(t).partial({task:!0}),cl=t=>lt.statusZ(wN(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(Wu).or(t.configSchema),status:oi(t.statusDataSchema).optional().nullable(),snapshot:i.z.boolean().optional()}),ul=t=>dn(t).omit({key:!0,status:!0}).extend({key:Me.transform(e=>e.toString()).optional(),config:i.z.unknown().transform(e=>ot.JSON_CODEC.encodeString(e)),status:cl(t?.statusDataSchema??i.z.unknown()).optional().nullable()}),bN=i.z.object({task:Me,type:i.z.string(),key:i.z.string(),args:me.unknownZ.or(i.z.string().transform(ke)).or(i.z.array(i.z.unknown())).or(i.z.null()).optional()}),vN=t=>Number(BigInt(t)>>32n),ss="sy_task_cmd",zN="sy_task_set",TN="sy_task_delete",Qe=new Error("Task not created"),ll=async(t,e)=>{const n=await e.retrieveParents(pn(t));return n.length===0?null:n[0]};class hl{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw Qe;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw Qe;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw Qe;return this.rangeClient_}constructor({key:e,type:n,name:r,config:s,internal:a=!1,snapshot:o=!1,status:c},l,u,h,d){this.key=e,this.name=r,this.type=n,this.config=s,this.schemas=l??{typeSchema:i.z.string(),configSchema:i.z.unknown(),statusDataSchema:i.z.unknown()},this.internal=a,this.snapshot=o,this.status=c,this.frameClient_=u,this.ontologyClient_=h,this.rangeClient_=d}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return pn(this.key)}async executeCommand(e){return await pl({...e,frameClient:this.frameClient,task:this.key})}async executeCommandSync(e){return await yl({...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 Qe;return this.snapshot?await ll(this.key,this.ontologyClient):null}}const ON=i.z.object({rack:ge.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()}),fl=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:ge.optional()}).transform(({type:t,rack:e})=>({types:[t],rack:e}))]),EN=ON,NN=i.z.union([fl,EN]),SN=t=>i.z.object({tasks:N.nullableZ(dn(t))}),kN=t=>i.z.object({tasks:ul(t).array()}),AN=t=>i.z.object({tasks:dn(t).array()}),$N=i.z.object({keys:Me.array()}),IN=i.z.object({}),ZN=i.z.object({key:Me,name:i.z.string(),snapshot:i.z.boolean()}),xN=t=>i.z.object({task:dn(t)});let dl=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=kN(n),a=AN(n),o=await T(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 T(this.client,"/task/delete",{keys:N.toArray(e)},$N,IN)}async retrieve({schemas:e,...n}){const r=fl.safeParse(n).success,a=(await T(this.client,"/task/retrieve",n,NN,SN(e))).tasks,o=this.sugar(a,e);return se("Task",n,o,r),r?o[0]:o}async copy(e,n,r){const s=xN(),a=await T(this.client,"/task/copy",{key:e,name:n,snapshot:r},ZN,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 Qe;return await ll(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 hl({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 ci({...e,frameClient:this.frameClient}):await pl({...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 ml({...e,frameClient:this.frameClient,name:r})}const n=async()=>{const{task:r}=e;return(await this.retrieve({key:r})).name};return await yl({frameClient:this.frameClient,name:n,...e})}};const pn=H("task"),CN=pn(""),RN=t=>_e(pn(t)),pl=async({frameClient:t,task:e,type:n,args:r})=>(await ci({frameClient:t,commands:[{args:r,task:e,type:n}]}))[0],ci=async({frameClient:t,commands:e})=>{if(t==null)throw Qe;const n=await t.openWriter(ss),r=e.map(s=>({...s,key:lo.create()}));return await n.write(ss,r),await n.close(),r.map(s=>s.key)},yl=async({frameClient:t,task:e,type:n,timeout:r,name:s,statusDataZ:a,args:o})=>(await ml({frameClient:t,commands:[{args:o,task:e,type:n}],timeout:r,statusDataZ:a,name:s}))[0],ml=async({frameClient:t,commands:e,timeout:n=g.seconds(10),statusDataZ:r,name:s})=>{if(t==null)throw Qe;const a=await t.openStreamer(Qr),o=await ci({frameClient:t,commands:e}),c=new g(n);let l=[],u;const h=new Promise((d,f)=>{u=setTimeout(()=>{(async()=>{const O=e.map(S=>S.task);f(await _N("command",s,c,O))})()},c.milliseconds)});try{for(;;){const d=await Promise.race([a.read(),h]),f=oi(r).safeParse(d.at(-1)[Qr]);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()}},_N=async(t,e,n,r)=>{const s=hd.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=Yr.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 ${Yr.naturalLanguageJoin(r)} timed out after ${a}`)}},MN=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:ss,Client:dl,DELETE_CHANNEL_NAME:TN,SET_CHANNEL_NAME:zN,TYPE_ONTOLOGY_ID:CN,Task:hl,commandZ:bN,keyZ:Me,newStatusZ:cl,newZ:ul,ontologyID:pn,rackKey:vN,statusDetailsZ:ai,statusKey:RN,statusZ:oi,taskZ:dn},Symbol.toStringTag,{value:"Module"}));class gl{url;unary;stream;secure;constructor(e,n={},r=!1){this.secure=r,this.url=e.child("/api/v1/");const s=new ot.JSONCodec;this.unary=Hf(new Vf(this.url,s,this.secure),n),this.stream=new Qf(this.url,s,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const pt=i.z.uuid(),Qn=i.z.object({key:pt,name:i.z.string(),data:me.unknownZ.or(i.z.string().transform(ke))}),wl=Qn.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Ae=i.z.uuid(),er=i.z.object({key:Ae,name:i.z.string().min(1,"Name is required"),layout:me.unknownZ.or(i.z.string().transform(ke))}),bl=er.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),vl=er.omit({layout:!0}).extend({layout:i.z.string().transform(ke)}),jN=i.z.object({key:pt,name:i.z.string()}),UN=i.z.object({key:pt,data:i.z.string()}),DN=i.z.object({keys:pt.array()}),PN=i.z.object({keys:pt.array()}),zl=i.z.object({key:pt}).transform(({key:t})=>({keys:[t]})),Tl=i.z.union([zl,PN]),LN=i.z.object({linePlots:N.nullableZ(Qn)}),BN=i.z.object({workspace:Ae,linePlots:wl.array()}),qN=i.z.object({linePlots:Qn.array()}),br=i.z.object({});let Ol=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/workspace/lineplot/create",{workspace:e,linePlots:N.toArray(n)},BN,qN);return r?s.linePlots:s.linePlots[0]}async rename(e,n){await T(this.client,"/workspace/lineplot/rename",{key:e,name:n},jN,br)}async setData(e,n){await T(this.client,"/workspace/lineplot/set-data",{key:e,data:JSON.stringify(n)},UN,br)}async retrieve(e){const n=zl.safeParse(e).success,r=await T(this.client,"/workspace/lineplot/retrieve",e,Tl,LN);return se("LinePlot",e,r.linePlots,n),n?r.linePlots[0]:r.linePlots}async delete(e){await T(this.client,"/workspace/lineplot/delete",{keys:N.toArray(e)},DN,br)}};const El=H("lineplot"),FN=El(""),YN=Object.freeze(Object.defineProperty({__proto__:null,Client:Ol,TYPE_ONTOLOGY_ID:FN,keyZ:pt,linePlotZ:Qn,newZ:wl,ontologyID:El,retrieveArgsZ:Tl},Symbol.toStringTag,{value:"Module"})),yt=i.z.uuid(),tr=i.z.object({key:yt,name:i.z.string(),data:me.unknownZ.or(i.z.string().transform(ke))}),Nl=tr.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),GN=i.z.object({key:yt,name:i.z.string()}),VN=i.z.object({key:yt,data:i.z.string()}),HN=i.z.object({keys:yt.array()}),WN=i.z.object({keys:yt.array()}),Sl=i.z.object({key:yt}).transform(({key:t})=>({keys:[t]})),kl=i.z.union([Sl,WN]),KN=i.z.object({logs:N.nullableZ(tr)}),JN=i.z.object({workspace:Ae,logs:Nl.array()}),XN=i.z.object({logs:tr.array()}),vr=i.z.object({});let Al=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/workspace/log/create",{workspace:e,logs:N.toArray(n)},JN,XN);return r?s.logs:s.logs[0]}async rename(e,n){await T(this.client,"/workspace/log/rename",{key:e,name:n},GN,vr)}async setData(e,n){await T(this.client,"/workspace/log/set-data",{key:e,data:JSON.stringify(n)},VN,vr)}async retrieve(e){const n=Sl.safeParse(e).success,r=await T(this.client,"/workspace/log/retrieve",e,kl,KN);return se("Log",e,r.logs,n),n?r.logs[0]:r.logs}async delete(e){await T(this.client,"/workspace/log/delete",{keys:N.toArray(e)},HN,vr)}};const $l=H("log"),QN=$l(""),eS=Object.freeze(Object.defineProperty({__proto__:null,Client:Al,TYPE_ONTOLOGY_ID:QN,keyZ:yt,logZ:tr,newZ:Nl,ontologyID:$l,retrieveArgsZ:kl},Symbol.toStringTag,{value:"Module"})),Ke=i.z.uuid(),nr=i.z.object({key:Ke,name:i.z.string(),data:me.unknownZ.or(i.z.string().transform(ke)),snapshot:i.z.boolean()}),Il=nr.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),ui=nr.extend({data:i.z.string().transform(ke)}),Ct=i.z.uuid(),Zl=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()}),xl=i.z.object({key:i.z.string(),name:i.z.string(),regions:Zl.array()}),Cl=i.z.object({key:i.z.string(),position:Es.xy,orientation:Tp.outer}),tS=i.z.object({zoom:i.z.number().positive().default(1),position:Es.xy}),Rl=i.z.object({svg:i.z.string().min(1,"SVG is required"),states:xl.array(),variant:i.z.string().min(1,"Variant is required"),handles:Cl.array(),scale:i.z.number().positive().default(1),scaleStroke:i.z.boolean().default(!1),previewViewport:tS.default({zoom:1,position:{x:0,y:0}})}),rr=i.z.object({key:Ct,version:i.z.literal(1).default(1),name:i.z.string().min(1,"Name is required"),data:Rl}),_l=rr.partial({key:!0}),nS=i.z.object({symbols:_l.array(),parent:L}),rS=i.z.object({key:Ct,name:i.z.string()}),sS=i.z.object({keys:Ct.array()}),iS=i.z.object({keys:Ct.array().optional(),searchTerm:i.z.string().optional()}),aS=i.z.object({key:Ct}).transform(({key:t})=>({keys:[t]})),oS=i.z.union([aS,iS]),cS=i.z.object({symbols:N.nullableZ(rr)}),uS=i.z.object({symbols:rr.array()}),wa=i.z.object({}),lS=i.z.object({}),hS=i.z.object({group:Pn}),fS="sy_schematic_symbol_set",dS="sy_schematic_symbol_delete";let Ml=class{client;constructor(e){this.client=e}async create(e){const n="symbols"in e,r=n?e.symbols:[e],s=await T(this.client,"/workspace/schematic/symbol/create",{symbols:r,parent:e.parent},nS,uS);return n?s.symbols:s.symbols[0]}async rename(e,n){await T(this.client,"/workspace/schematic/symbol/rename",{key:e,name:n},rS,wa)}async retrieve(e){const n="key"in e,r=await T(this.client,"/workspace/schematic/symbol/retrieve",e,oS,cS);return se("Schematic Symbol",e,r.symbols,n),n?r.symbols[0]:r.symbols}async delete(e){await T(this.client,"/workspace/schematic/symbol/delete",{keys:N.toArray(e)},sS,wa)}async retrieveGroup(){return(await T(this.client,"/workspace/schematic/symbol/retrieve_group",{},lS,hS)).group}};const pS=H("schematic_symbol"),yS=Object.freeze(Object.defineProperty({__proto__:null,Client:Ml,DELETE_CHANNEL_NAME:dS,SET_CHANNEL_NAME:fS,handleZ:Cl,keyZ:Ct,newZ:_l,ontologyID:pS,regionZ:Zl,specZ:Rl,stateZ:xl,symbolZ:rr},Symbol.toStringTag,{value:"Module"})),mS=i.z.object({key:Ke,name:i.z.string()}),gS=i.z.object({key:Ke,data:i.z.string()}),wS=i.z.object({keys:Ke.array()}),bS=i.z.object({key:Ke,name:i.z.string(),snapshot:i.z.boolean()}),vS=i.z.object({keys:Ke.array()}),jl=i.z.object({key:Ke}).transform(({key:t})=>({keys:[t]})),Ul=i.z.union([jl,vS]),zS=i.z.object({schematics:N.nullableZ(ui)}),TS=i.z.object({workspace:Ae,schematics:Il.array()}),OS=i.z.object({schematics:ui.array()}),ES=i.z.object({schematic:nr}),zr=i.z.object({});let Dl=class{symbols;client;constructor(e){this.client=e,this.symbols=new Ml(e)}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/workspace/schematic/create",{workspace:e,schematics:N.toArray(n)},TS,OS);return r?s.schematics:s.schematics[0]}async rename(e,n){await T(this.client,"/workspace/schematic/rename",{key:e,name:n},mS,zr)}async setData(e,n){await T(this.client,"/workspace/schematic/set-data",{key:e,data:JSON.stringify(n)},gS,zr)}async retrieve(e){const n=jl.safeParse(e).success,r=await T(this.client,"/workspace/schematic/retrieve",e,Ul,zS);return se("Schematic",e,r.schematics,n),n?r.schematics[0]:r.schematics}async delete(e){await T(this.client,"/workspace/schematic/delete",{keys:N.toArray(e)},wS,zr)}async copy(e){return(await T(this.client,"/workspace/schematic/copy",e,bS,ES)).schematic}};const Pl=H("schematic"),NS=Pl(""),SS=Object.freeze(Object.defineProperty({__proto__:null,Client:Dl,TYPE_ONTOLOGY_ID:NS,keyZ:Ke,newZ:Il,ontologyID:Pl,remoteZ:ui,retrieveArgsZ:Ul,schematicZ:nr,symbol:yS},Symbol.toStringTag,{value:"Module"})),mt=i.z.uuid(),li=i.z.object({key:mt,name:i.z.string(),data:me.unknownZ.or(i.z.string().transform(ke))}),Ll=li.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),hi=li.extend({data:i.z.string().transform(ke)}),kS=i.z.object({key:mt,name:i.z.string()}),AS=i.z.object({key:mt,data:i.z.string()}),$S=i.z.object({keys:mt.array()}),IS=i.z.object({keys:mt.array()}),Bl=i.z.object({key:mt}).transform(({key:t})=>({keys:[t]})),ql=i.z.union([Bl,IS]),ZS=i.z.object({tables:N.nullableZ(hi)}),xS=i.z.object({workspace:Ae,tables:Ll.array()}),CS=i.z.object({tables:hi.array()}),Tr=i.z.object({});let Fl=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/workspace/table/create",{workspace:e,tables:N.toArray(n)},xS,CS);return r?s.tables:s.tables[0]}async rename(e,n){await T(this.client,"/workspace/table/rename",{key:e,name:n},kS,Tr)}async setData(e,n){await T(this.client,"/workspace/table/set-data",{key:e,data:JSON.stringify(n)},AS,Tr)}async retrieve(e){const n=Bl.safeParse(e).success,r=await T(this.client,"/workspace/table/retrieve",e,ql,ZS);return se("Table",e,r.tables,n),n?r.tables[0]:r.tables}async delete(e){await T(this.client,"/workspace/table/delete",{keys:N.toArray(e)},$S,Tr)}};const Yl=H("table"),RS=Yl(""),_S=Object.freeze(Object.defineProperty({__proto__:null,Client:Fl,TYPE_ONTOLOGY_ID:RS,keyZ:mt,newZ:Ll,ontologyID:Yl,remoteZ:hi,retrieveArgsZ:ql,tableZ:li},Symbol.toStringTag,{value:"Module"})),MS=i.z.object({keys:Ae.array().optional(),searchTerm:i.z.string().optional(),author:Se.optional(),offset:i.z.int().optional(),limit:i.z.int().optional()}),jS=i.z.object({workspaces:bl.array()}),US=i.z.object({key:Ae,name:i.z.string()}),DS=i.z.object({key:Ae,layout:me.unknownZ.transform(t=>JSON.stringify(t))}),PS=i.z.object({keys:Ae.array()}),LS=i.z.object({workspaces:N.nullableZ(er)}),BS=i.z.object({workspaces:vl.array()}),Or=i.z.object({}),qS="sy_workspace_set",FS="sy_workspace_delete";class Gl{schematics;lineplots;logs;tables;client;constructor(e){this.client=e,this.schematics=new Dl(e),this.lineplots=new Ol(e),this.logs=new Al(e),this.tables=new Fl(e)}async create(e){const n=Array.isArray(e),r=await T(this.client,"/workspace/create",{workspaces:N.toArray(e)},jS,BS);return n?r.workspaces:r.workspaces[0]}async rename(e,n){await T(this.client,"/workspace/rename",{key:e,name:n},US,Or)}async setLayout(e,n){await T(this.client,"/workspace/set-layout",{key:e,layout:n},DS,Or)}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 T(this.client,"/workspace/retrieve",n,MS,LS);return r?s.workspaces:s.workspaces[0]}async delete(e){await T(this.client,"/workspace/delete",{keys:N.toArray(e)},PS,Or)}}const Vl=H("workspace"),YS=Vl(""),GS=Object.freeze(Object.defineProperty({__proto__:null,Client:Gl,DELETE_CHANNEL_NAME:FS,SET_CHANNEL_NAME:qS,TYPE_ONTOLOGY_ID:YS,keyZ:Ae,newZ:bl,ontologyID:Vl,remoteZ:vl,workspaceZ:er},Symbol.toStringTag,{value:"Module"})),Hl=i.z.object({host:i.z.string({error:"Host is required"}).min(1,"Host is required"),port:i.z.number({error:"Port is required"}).or(i.z.string({error:"Port is required"})),username:i.z.string().min(1,"Username is required"),password:i.z.string().min(1,"Password is required"),connectivityPollFrequency:g.z.default(g.seconds(30)),secure:i.z.boolean().default(!1),name:i.z.string().optional(),retry:ks.breakerConfigZ.optional()});class Wl extends Bu{createdAt;params;ranges;channels;auth;users;access;connectivity;ontology;workspaces;labels;statuses;tasks;racks;devices;control;arcs;static connectivity=Rn;transport;clientVersion="0.49.2";constructor(e){const n=Hl.parse(e),{host:r,port:s,username:a,password:o,connectivityPollFrequency:c,secure:l,retry:u}=n,h=new gl(new Tt({host:r,port:Number(s)}),u,l);h.use(Rm);const d=new Xs(new Js(h.unary));super(h.stream,h.unary,d),this.auth=new yO(h.unary,{username:a,password:o}),h.use(this.auth.middleware());const f=new Nu(h.unary,d);this.createdAt=m.now(),this.params=n,this.transport=h,this.channels=new Ou(this,d,h.unary,f),this.connectivity=new Rn(h.unary,c,this.clientVersion,n.name),this.control=new Yu(this),this.ontology=new gc(h.unary,this);const O=new al(this.transport.unary);this.labels=new wu(this.transport.unary),this.statuses=new ol(this.transport.unary),this.ranges=new sl(this,O,this.transport.unary,d,this.labels,this.ontology),this.access=new Ac(this.transport.unary),this.users=new Tc(this.transport.unary),this.workspaces=new Gl(this.transport.unary),this.tasks=new dl(this.transport.unary,this,this.ontology,this.ranges),this.racks=new el(this.transport.unary,this.tasks),this.devices=new Qu(this.transport.unary),this.arcs=new uu(this.transport.unary,this.transport.stream)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stop()}}const VS=async t=>await Kl(t).check(),Kl=t=>{const{host:e,port:n,secure:r,name:s,retry:a}=t,o=ks.breakerConfigZ.optional().parse(a),c=new Tt({host:e,port:Number(n)}),l=new gl(c,o,r);return new Rn(l.unary,void 0,"0.49.2",s)},Jl={host:"localhost",port:9090,username:"synnax",password:"seldon",retry:{maxRetries:4,baseInterval:g.seconds(1),scale:1.5}},Xl=t=>new Wl({...Jl,...t}),HS=async(t,e)=>{const n=lo.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(js(a.key),_s(s.key)),await t.access.roles.assign({user:r.key,role:a.key}),Xl({username:n,password:"test"})};exports.AuthError=St;exports.Channel=Cn;exports.ContiguityError=Zm;exports.DataType=p;exports.Density=C;exports.DisconnectedError=Im;exports.Frame=F;exports.MultiSeries=qo;exports.MultipleFoundError=Gt;exports.NotFoundError=Yt;exports.QueryError=Ge;exports.Rate=G;exports.RouteError=Hr;exports.Series=ee;exports.Synnax=Wl;exports.TEST_CLIENT_PARAMS=Jl;exports.TimeRange=x;exports.TimeSpan=g;exports.TimeStamp=m;exports.UnexpectedError=nt;exports.ValidationError=V;exports.access=Xg;exports.arc=NT;exports.channel=cO;exports.checkConnection=VS;exports.connection=wO;exports.control=QO;exports.createTestClient=Xl;exports.createTestClientWithPolicy=HS;exports.device=fE;exports.framer=VO;exports.group=Wm;exports.isCalculated=kt;exports.label=VT;exports.lineplot=YN;exports.log=eS;exports.newConnectionChecker=Kl;exports.ontology=sg;exports.rack=SE;exports.ranger=cN;exports.schematic=SS;exports.status=gN;exports.synnaxParamsZ=Hl;exports.table=_S;exports.task=MN;exports.user=Mg;exports.workspace=GS;