@synnaxlabs/client 0.54.0 → 0.54.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.
package/dist/client.cjs CHANGED
@@ -1,26 +1,43 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`zod`);l=c(l);var u=[`create`,`delete`,`retrieve`,`update`],d=l.z.enum(u),f=Object.defineProperty,p=(e,t)=>{let n={};for(var r in e)f(n,r,{get:e[r],enumerable:!0});return t||f(n,Symbol.toStringTag,{value:`Module`}),n},m=(e,t)=>{if(Array.isArray(t))return t.reduce((e,t)=>m(e,t),e??[]);if(e==null)return[t];let n=e.findIndex(e=>e==t),r=[...e];return n===-1?r.push(t):r[n]=t,r},h=(e,t)=>{if(Array.isArray(t))return t.reduce((e,t)=>h(e,t),e??[]);if(e==null)return[t];let n=e.findIndex(e=>e.key===t.key),r=[...e];return n===-1?r.push(t):r[n]=t,r},g=`synnax.caseconv.preserveCase`,ee=e=>{if(typeof e!=`object`||!e)return!1;if(g in e)return!0;let t=e._zod?.def;return t==null?!1:t.innerType&&ee(t.innerType)?!0:t.type===`union`&&Array.isArray(t.options)?t.options.some(ee):t.type===`pipe`?ee(t.in)||ee(t.out):!1},te=e=>{if(e==null)return;let t=e._zod?.def;if(t?.type===`array`&&t.element!=null)return t.element;if(t?.type===`union`&&Array.isArray(t.options))for(let e of t.options){let t=te(e);if(t!=null)return t}},ne=e=>{if(e==null)return null;let t=e;if(t.shape!=null)return t.shape;if(typeof t.sourceType==`function`){let e=t.sourceType();if(e?.shape!=null)return e.shape}let n=t._zod?.def;if(n==null)return null;if(n.innerType!=null)return ne(n.innerType);if(n.type===`union`&&Array.isArray(n.options))for(let e of n.options){let t=ne(e);if(t!=null)return t}return n.type===`pipe`?ne(n.in)??ne(n.out):null},re=e=>{if(e.length===0)return e;let t=e.indexOf(`_`)===-1?e:e.replace(/_[a-z]/g,e=>e[1].toUpperCase()),n=t.charCodeAt(0);return n<65||n>90||t.length>1&&t.charCodeAt(1)>=65&&t.charCodeAt(1)<=90?t:String.fromCharCode(n+32)+t.slice(1)},ie=e=>{let t=(n,r=se)=>{if(typeof n==`string`)return e(n);if(Array.isArray(n)){let e=te(r.schema),i={recursive:r.recursive,recursiveInArray:r.recursiveInArray,schema:e};return n.map(e=>t(e,i))}if(!ce(n)||r.schema!=null&&ee(r.schema))return n;let i=r.recursive??!0,a=r.recursiveInArray??i,o=r.schema,s={},c=n;if(`toJSON`in c&&typeof c.toJSON==`function`)return t(c.toJSON(),r);let l=ne(o),u={recursive:i,recursiveInArray:a,schema:void 0},d=Object.keys(c);for(let n=0;n<d.length;n++){let r=d[n],o=c[r],f=e(r),p=l==null?void 0:l[r]??l[f]??void 0;i&&(ce(o)?le(o)||(u.schema=p,o=t(o,u)):a&&Array.isArray(o)&&(u.schema=te(p),o=o.map(e=>{if(ce(e)){if(!le(e))return t(e,u)}else if(Array.isArray(e))return t({key:e},u).key;return e}))),s[f]=o}return s};return t},ae=ie(re),oe=ie(e=>e.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`)),se={recursive:!0,recursiveInArray:!0,schema:void 0},ce=e=>typeof e==`object`&&!!e&&!Array.isArray(e),le=e=>e instanceof Uint8Array||e instanceof Number||e instanceof String,ue=e=>typeof e==`object`&&!!e&&!Array.isArray(e),de=class{contentType=`application/json`;decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e,t){return this.encoder.encode(this.encodeString(e,t))}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){let n=ae(JSON.parse(e),{schema:t});return t==null?n:t.parse(n)}encodeString(e,t){let n=oe((t==null?e:t.parse(e))??{},{schema:t});return JSON.stringify(n,(e,t)=>ArrayBuffer.isView(t)?Array.from(t):typeof t==`bigint`?t.toString():t)}},fe=class{contentType=`text/csv`;encode(e){let t=this.encodeString(e);return new TextEncoder().encode(t)}decode(e,t){let n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!ue(e[0]))throw Error(`Payload must be an array of objects`);let t=Object.keys(e[0]),n=[t.join(`,`)];return e.forEach(e=>{let r=t.map(t=>JSON.stringify(e[t]??``));n.push(r.join(`,`))}),n.join(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`zod`);l=c(l);var u=[`create`,`delete`,`retrieve`,`update`],d=l.z.enum(u),f=Object.defineProperty,p=(e,t)=>{let n={};for(var r in e)f(n,r,{get:e[r],enumerable:!0});return t||f(n,Symbol.toStringTag,{value:`Module`}),n},m=(e,t)=>{if(Array.isArray(t))return t.reduce((e,t)=>m(e,t),e??[]);if(e==null)return[t];let n=e.findIndex(e=>e==t),r=[...e];return n===-1?r.push(t):r[n]=t,r},h=(e,t)=>{if(Array.isArray(t))return t.reduce((e,t)=>h(e,t),e??[]);if(e==null)return[t];let n=e.findIndex(e=>e.key===t.key),r=[...e];return n===-1?r.push(t):r[n]=t,r},g=`synnax.caseconv.preserveCase`,ee=e=>{if(typeof e!=`object`||!e)return!1;if(g in e)return!0;let t=e._zod?.def;return t==null?!1:t.innerType&&ee(t.innerType)?!0:t.type===`union`&&Array.isArray(t.options)?t.options.some(ee):t.type===`pipe`?ee(t.in)||ee(t.out):!1},te=e=>{if(e==null)return;let t=e._zod?.def;if(t?.type===`array`&&t.element!=null)return t.element;if(t?.type===`union`&&Array.isArray(t.options))for(let e of t.options){let t=te(e);if(t!=null)return t}},ne=e=>{if(e==null)return null;let t=e;if(t.shape!=null)return t.shape;if(typeof t.sourceType==`function`){let e=t.sourceType();if(e?.shape!=null)return e.shape}let n=t._zod?.def;if(n==null)return null;if(n.innerType!=null)return ne(n.innerType);if(n.type===`union`&&Array.isArray(n.options))for(let e of n.options){let t=ne(e);if(t!=null)return t}return n.type===`pipe`?ne(n.in)??ne(n.out):null},re=e=>{if(e.length===0)return e;let t=e.indexOf(`_`)===-1?e:e.replace(/_[a-z]/g,e=>e[1].toUpperCase()),n=t.charCodeAt(0);return n<65||n>90||t.length>1&&t.charCodeAt(1)>=65&&t.charCodeAt(1)<=90?t:String.fromCharCode(n+32)+t.slice(1)},ie=e=>{let t=(n,r=se)=>{if(typeof n==`string`)return e(n);if(Array.isArray(n)){let e=te(r.schema),i={recursive:r.recursive,recursiveInArray:r.recursiveInArray,schema:e};return n.map(e=>t(e,i))}if(!ce(n)||r.schema!=null&&ee(r.schema))return n;let i=r.recursive??!0,a=r.recursiveInArray??i,o=r.schema,s={},c=n;if(`toJSON`in c&&typeof c.toJSON==`function`)return t(c.toJSON(),r);let l=ne(o),u={recursive:i,recursiveInArray:a,schema:void 0},d=Object.keys(c);for(let n=0;n<d.length;n++){let r=d[n],o=c[r],f=e(r),p=l==null?void 0:l[r]??l[f]??void 0;i&&(ce(o)?le(o)||(u.schema=p,o=t(o,u)):a&&Array.isArray(o)&&(u.schema=te(p),o=o.map(e=>{if(ce(e)){if(!le(e))return t(e,u)}else if(Array.isArray(e))return t({key:e},u).key;return e}))),s[f]=o}return s};return t},ae=ie(re),oe=ie(e=>e.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`)),se={recursive:!0,recursiveInArray:!0,schema:void 0},ce=e=>typeof e==`object`&&!!e&&!Array.isArray(e),le=e=>e instanceof Uint8Array||e instanceof Number||e instanceof String,ue=e=>typeof e==`object`&&!!e&&!Array.isArray(e),de=e=>{if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},fe=(e,t)=>{let n=e;for(let e of t){if(typeof n!=`object`||!n)return{present:!1,value:void 0};let t=n;if(!(e in t))return{present:!1,value:void 0};n=t[e]}return{present:!0,value:n}},pe=(e,t)=>{let n=Array.isArray(e),r=Array.isArray(t);if(n!==r)return!1;if(n&&r){let n=e,r=t;if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++)if(!pe(n[e],r[e]))return!1;return!0}if(e==null||t==null||typeof e!=`object`||typeof t!=`object`)return e===t;if(`equals`in e)return e.equals(t);let i=Object.keys(e),a=Object.keys(t);if(i.length!==a.length)return!1;for(let n of i){let r=e[n],i=t[n];if(typeof r==`object`&&typeof i==`object`){if(!pe(r,i))return!1}else if(r!==i)return!1}return!0},me=(e,t)=>{if(typeof e!=`object`||!e)return e===t;let n=Object.keys(e),r=Object.keys(t);if(r.length>n.length)return!1;for(let n of r){let r=e[n],i=t[n];if(typeof r==`object`&&typeof i==`object`){if(!me(r,i))return!1}else if(r!==i)return!1}return!0},he=(e,...t)=>{if(t.length===0)return e;let n=t.shift();if(ue(e)&&ue(n))for(let t in n)try{ue(n[t])?(t in e||Object.assign(e,{[t]:{}}),he(e[t],n[t])):Object.assign(e,{[t]:n[t]})}catch(e){throw e instanceof TypeError?TypeError(`.${t}: ${e.message}`,{cause:e}):e}return he(e,...t)},ge=e=>Object.getOwnPropertySymbols(globalThis).includes(e),_e=(e,t)=>{let n=Symbol.for(e);if(!ge(n)){let e=t();Object.defineProperty(globalThis,n,{value:e})}return()=>globalThis[n]},ve=p({Canceled:()=>je,NONE:()=>`nil`,NotImplemented:()=>Me,UNKNOWN:()=>Ce,Unknown:()=>ke,createTyped:()=>xe,decode:()=>Oe,encode:()=>De,isTyped:()=>Se,payloadZ:()=>Ae,register:()=>Ee}),ye=`sy_x_error`,be=e=>t=>typeof t==`object`&&t&&`type`in t&&typeof t.type==`string`?t.type.startsWith(e):t instanceof Error?t.message.startsWith(e):typeof t==`string`?t.startsWith(e):!1,xe=e=>class t extends Error{static discriminator=ye;discriminator=t.discriminator;static TYPE=e;type=t.TYPE;static matches=be(e);matches=t.matches;constructor(e,n){super(e,n),this.name=t.TYPE}static sub(t){return xe(`${e}.${t}`)}},Se=e=>{if(typeof e!=`object`||!e)return!1;let t=e;if(t.discriminator!==ye)return!1;if(!(`type`in t))throw Error(`X Error is missing its type property: ${JSON.stringify(t)}`);return!0},Ce=`unknown`,we=class{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:`nil`,data:``};if(Se(e))for(let t of this.providers){let n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Ce,data:e.message};if(typeof e==`string`)return{type:Ce,data:e};try{return{type:Ce,data:JSON.stringify(e)}}catch{return{type:Ce,data:`unable to encode error information`}}}decode(e){if(e==null||e.type===`nil`)return null;if(e.type===`unknown`)return new ke(e.data);for(let t of this.providers){let n=t.decode(e);if(n!=null)return n}return new ke(e.data)}},Te=_e(`synnax-error-registry`,()=>new we),Ee=({encode:e,decode:t})=>Te().register({encode:e,decode:t}),De=e=>Te().encode(e),Oe=e=>e==null?null:Te().decode(e),ke=class extends xe(`unknown`){},Ae=l.z.object({type:l.z.string(),data:l.z.string()}),je=class extends xe(`canceled`){},Me=class extends xe(`not_implemented`){},Ne=e=>{if(e.length===0)return`<root>`;let t=``;return e.forEach((e,n)=>{typeof e==`number`?t+=`[${e}]`:n===0?t+=String(e):t+=`.${String(e)}`}),t},Pe=200,Fe=10,Ie=8,Le=(e,t={})=>{let n=t.maxStringLength??Pe,r=t.maxArrayLength??Fe,i=t.maxDepth??Ie,a=(e,t)=>{if(e===null)return null;if(e===void 0)return`[undefined]`;let o=typeof e;if(o===`string`){let t=e;return t.length>n?`${t.slice(0,n)}…(+${t.length-n} chars)`:t}if(o===`number`||o===`boolean`)return e;if(o===`bigint`)return`${e.toString()}n`;if(o===`symbol`||o===`function`)return`[${o}]`;if(Array.isArray(e)){if(t>=i)return`[Array(${e.length})]`;let n=e.slice(0,r).map(e=>a(e,t+1));return e.length>r&&n.push(`…(+${e.length-r} more)`),n}if(de(e)){if(t>=i)return`[Object]`;let n={};for(let[r,i]of Object.entries(e))n[r]=a(i,t+1);return n}if(e instanceof Date)return e.toISOString();if(e instanceof Error)return`[Error: ${e.message}]`;try{return`[${Object.prototype.toString.call(e)}]`}catch{return`[unknown]`}};return a(e,0)},Re=(e,t={})=>JSON.stringify(Le(e,t),null,2),ze=e=>typeof e==`object`&&!!e&&`value`in e,Be=class{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}},Ve=e=>typeof e==`object`&&!!e&&`toString`in e,He=e=>e==null||typeof e!=`object`&&typeof e!=`function`,Ue=`value`,We=`zod.parse`,Ge=`✗`,Ke=60,qe={maxStringLength:60,maxArrayLength:3,maxDepth:3},Je=e=>e.slice(0,-1),Ye=e=>{switch(e.code){case`invalid_type`:return`expected ${e.expected}`;case`invalid_value`:return`expected one of ${JSON.stringify(e.values)}`;case`unrecognized_keys`:return`unexpected key`;case`too_small`:{let t=e.inclusive===!1?`>`:`>=`;return`${e.origin} too small: expected ${t}${e.minimum}`}case`too_big`:{let t=e.inclusive===!1?`<`:`<=`;return`${e.origin} too large: expected ${t}${e.maximum}`}case`invalid_format`:return`expected ${e.format} format`;case`not_multiple_of`:return`expected multiple of ${e.divisor}`;case`custom`:return e.message||`custom validation failed`;default:return e.message}},Xe=(e,t,n)=>{let r=JSON.stringify(Le(t,n));return`${Ye(e)}, received ${r}`},Ze=e=>{let t=0;for(let n of e){if(n.path.length>t&&(t=n.path.length),n.code===`invalid_union`&&`errors`in n)for(let e of n.errors){let n=Ze(e);n>t&&(t=n)}if((n.code===`invalid_key`||n.code===`invalid_element`)&&`issues`in n){let e=Ze(n.issues);e>t&&(t=e)}}return t},Qe=(e,t=[])=>{let n=[];for(let r of e){let e=[...t,...r.path];if(r.code===`invalid_union`&&`errors`in r&&r.errors.length>0){let t=r.errors[0],i=Ze(t);for(let e=1;e<r.errors.length;e++){let n=Ze(r.errors[e]);n>i&&(t=r.errors[e],i=n)}n.push(...Qe(t,e));continue}if(r.code===`invalid_element`&&`issues`in r&&`key`in r&&(typeof r.key==`string`||typeof r.key==`number`)){n.push(...Qe(r.issues,[...e,r.key]));continue}if(r.code===`invalid_key`&&`issues`in r){n.push(...Qe(r.issues,e));continue}n.push({...r,path:e})}return n},$e=e=>{let t=[];for(let n of e){if(n.code===`unrecognized_keys`&&`keys`in n&&Array.isArray(n.keys)){for(let e of n.keys)t.push({...n,path:[...n.path,e]});continue}t.push(n)}return t},et=(e,t,n,r)=>{let i=`${n} `,a=`${n+Ge} `,o={...qe,...r};if(Array.isArray(e)){let e=-1;for(let n of t.keys()){let t=Number(n);Number.isInteger(t)&&t>e&&(e=t)}let n=o.maxArrayLength??3;e>=n&&(o={...o,maxArrayLength:e+2})}let s=Le(e,o);if(typeof s!=`object`||!s){let e=JSON.stringify(s),n=t.values().next().value;return[`${a}${e}${n?` × ${n.reason}`:``}`]}let c=[],l=Array.isArray(s);c.push(`${n}${l?`[`:`{`}`);let u=[];if(l){let e=s;for(let n=0;n<e.length;n++){let r=t.get(String(n));u.push({content:JSON.stringify(e[n]),mark:r&&!r.missing?r:void 0})}}else{let e=s;for(let n of Object.keys(e)){let r=t.get(n);u.push({content:`"${n}": ${JSON.stringify(e[n])}`,mark:r&&!r.missing?r:void 0})}for(let[e,n]of t.entries())n.missing&&u.push({content:`"${e}": <missing>`,mark:n})}let d=0;return u.forEach((e,t)=>{if(e.mark==null)return;let n=t<u.length-1?1:0,r=e.content.length+n;r>d&&r<=Ke&&(d=r)}),u.forEach((e,t)=>{let n=t<u.length-1?`,`:``,r=e.content+n;if(e.mark!=null){let t=` `.repeat(Math.max(2,d-r.length+2));c.push(`${a}${r}${t}× ${e.mark.reason}`)}else c.push(`${i}${r}`)}),c.push(n+(l?`]`:`}`)),c},tt=`__root__`,nt=(e,t,n)=>{let r=new Map;for(let t of e){let e=t.path.length===0?tt:`::${Ne(Je(t.path))}`,n=r.get(e);n==null?r.set(e,[t]):n.push(t)}let i=[];for(let[e,a]of r){if(e===tt){i.push(a.map(e=>` × ${Xe(e,t,n)}`).join(`
2
+ `));continue}let r=Je(a[0].path),{present:o,value:s}=fe(t,r);if(!o){i.push(a.map(e=>` at ${Ne(e.path)}\n × ${Xe(e,t,n)}`).join(`
3
+ `));continue}let c=new Map;for(let e of a){let n=String(e.path[e.path.length-1]),r=fe(t,e.path);c.set(n,{reason:Ye(e),missing:!r.present})}let l=r.length===0,u=et(s,c,l?` `:` `,n);l?i.push(u.join(`
4
+ `)):i.push([` at ${Ne(r)}`,...u].join(`
5
+ `))}return i.join(`
6
+
7
+ `)},rt=(e,t)=>{let n=Object.entries(e);return n.every(([,e])=>He(e))?n.map(([e,t])=>`${e}=${typeof t==`string`?t:String(t)}`).join(`, `):Re(e,t)},it=({issues:e,input:t,label:n,context:r,formatOptions:i})=>{let a=i??{},o=$e(Qe(e)),s=[`Failed to parse ${n} (${o.length===1?`1 issue`:`${o.length} issues`})`];return s.push(nt(o,t,a)),r!=null&&Object.keys(r).length>0&&s.push(` context: ${rt(r,a)}`),s.join(`
8
+
9
+ `)},at=class extends xe(We){issues;input;label;context;constructor({issues:e,input:t,label:n,context:r,cause:i,formatOptions:a}){super(it({issues:e,input:t,label:n,context:r,formatOptions:a}),{cause:i}),this.issues=e,this.input=t,this.label=n,this.context=r}toStatus(){let e={input:Le(this.input),issues:this.issues};return this.context!=null&&(e.context=this.context),{message:`Failed to parse ${this.label}`,description:this.message,details:e}}};Ee({encode:e=>{if(!at.matches(e))return null;let t=e,n={label:t.label,context:t.context,issues:t.issues,input:Le(t.input)};return{type:We,data:JSON.stringify(n)}},decode:e=>{if(e.type!==We)return null;let t=JSON.parse(e.data);return new at({issues:t.issues,input:t.input,label:t.label,context:t.context})}});var ot=(e,t,n={})=>{let r=e.safeParse(t);if(r.success)return r.data;throw new at({issues:r.error.issues,input:t,label:n.label??Ue,context:n.context,cause:r.error})},st=2**12-1,ct=2**16-1,lt=2**20-1,ut=-128,dt=-(2**15),ft=2**15-1,pt=-(2n**63n),mt=2n**63n-1n,ht=-(2**63),gt=2**63-1,_t=e=>(t,n)=>{if(typeof t==`bigint`){if(bt(n))return e(t,BigInt(n));let r=e(Number(t),Number(n));return typeof r==`number`?BigInt(Math.round(r)):r}return e(Number(t),Number(n))},vt=_t((e,t)=>e-t),yt=_t((e,t)=>e+t),bt=e=>typeof e==`bigint`?!0:Number.isInteger(e),xt=_t((e,t)=>e*t),St=_t((e,t)=>e/t),Ct=l.z.tuple([l.z.number(),l.z.number()]),wt=l.z.enum([`x`,`y`]),Tt=[`top`,`right`,`bottom`,`left`];l.z.enum(Tt);var Et=[`left`,`right`],Dt=l.z.enum(Et),Ot=l.z.enum([`top`,`bottom`]),kt=[`center`],At=l.z.enum(kt);l.z.enum([`top`,`right`,`bottom`,`left`,`center`]),l.z.enum([`start`,`center`,`end`]),l.z.enum([`first`,`last`]);var jt=l.z.object({clientX:l.z.number(),clientY:l.z.number()}),Mt=l.z.object({width:l.z.number(),height:l.z.number()}),Nt=l.z.object({signedWidth:l.z.number(),signedHeight:l.z.number()});l.z.object({lower:l.z.number(),upper:l.z.number()}),l.z.enum([`x`,`y`,...Tt,...kt]),l.z.union([wt,l.z.enum([...Tt,...kt]),l.z.instanceof(String)]);var Pt=(e,t,n)=>{let r={};if(typeof t==`object`&&(n=t,t=void 0),n={makeValid:!0,...n},typeof e==`number`||typeof e==`bigint`)t==null?(r.lower=typeof e==`bigint`?0n:0,r.upper=e):(r.lower=e,r.upper=t);else if(Array.isArray(e)){if(e.length!==2)throw Error(`bounds: expected array of length 2`);[r.lower,r.upper]=e}else r.lower=e.lower,r.upper=e.upper;return n?.makeValid?Ft(r):r};Object.freeze({lower:0,upper:0}),Object.freeze({lower:-1/0,upper:1/0}),Object.freeze({lower:0,upper:1}),Object.freeze({lower:-1,upper:1});var Ft=e=>e.lower>e.upper?{lower:e.upper,upper:e.lower}:e,It=(e,t)=>{let n=Pt(e);return t<n.lower?n.lower:t>=n.upper?n.upper-(typeof n.upper==`number`?1:1n):t};l.z.int().min(ut).max(127),l.z.int().min(dt).max(ft),l.z.int().min(ht).max(gt);var Lt=l.z.int().min(0).max(255);l.z.int().min(0).max(st),l.z.int().min(0).max(ct),l.z.int().min(0).max(lt);var Rt=class{contentType=`application/json`;decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e,t){return this.encoder.encode(this.encodeString(e,t))}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){let n=ae(JSON.parse(e),{schema:t});return t==null?n:ot(t,n)}encodeString(e,t){let n=oe((t==null?e:ot(t,e))??{},{schema:t});return JSON.stringify(n,(e,t)=>ArrayBuffer.isView(t)?Array.from(t):typeof t==`bigint`?t.toString():t)}},zt=class{contentType=`text/csv`;encode(e){let t=this.encodeString(e);return new TextEncoder().encode(t)}decode(e,t){let n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!ue(e[0]))throw Error(`Payload must be an array of objects`);let t=Object.keys(e[0]),n=[t.join(`,`)];return e.forEach(e=>{let r=t.map(t=>JSON.stringify(e[t]??``));n.push(r.join(`,`))}),n.join(`
2
10
  `)}decodeString(e,t){let[n,...r]=e.trim().split(`
3
- `).map(e=>e.trim());if(n.length===0)return t==null?{}:t.parse({});let i=n.split(`,`).map(e=>e.trim()),a={};return i.forEach(e=>{a[e]=[]}),r.forEach(e=>{let t=e.split(`,`).map(e=>e.trim());i.forEach((e,n)=>{let r=this.parseValue(t[n]);r!=null&&a[e].push(r)})}),t==null?a:t.parse(a)}parseValue(e){if(e==null||e.length===0)return null;let t=Number(e);return isNaN(t)?e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e:t}},pe=class{contentType=`text/plain`;encode(e){if(typeof e!=`string`)throw Error(`TextCodec.encode payload must be a string`);return new TextEncoder().encode(e)}decode(e,t){let n=new TextDecoder().decode(e);return t==null?n:t.parse(n)}},me=new de;new fe,new pe;var he=e=>typeof e==`object`&&!!e&&`value`in e,ge=class{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}},_e=e=>typeof e==`object`&&!!e&&`toString`in e,ve=(e,t=!1)=>{let n=_e(e)?`stringer`:typeof e,r;switch(n){case`string`:r=(e,t)=>e.localeCompare(t);break;case`stringer`:r=(e,t)=>e.toString().localeCompare(t.toString());break;case`number`:r=(e,t)=>Number(e)-Number(t);break;case`bigint`:r=(e,t)=>BigInt(e)-BigInt(t)>0n?1:-1;break;case`boolean`:r=(e,t)=>Number(e)-Number(t);break;case`undefined`:r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return t?ye(r):r},ye=e=>(t,n)=>e(n,t),be=(e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i--;)r+=e[Math.random()*e.length|0];return r},xe=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,Se=`0123456789${xe}`,Ce=be(xe,1),we=be(Se,10),Te=()=>`${Ce()}${we()}`,Ee=(e,t)=>n=>n instanceof t||typeof n==`object`&&!!n&&`discriminator`in n&&n.discriminator===e,De=2**12-1,Oe=2**16-1,ke=2**20-1,Ae=-128,je=-(2**15),Me=2**15-1,Ne=-(2n**63n),Pe=2n**63n-1n,Fe=-(2**63),Ie=2**63-1,Le=e=>(t,n)=>{if(typeof t==`bigint`){if(Be(n))return e(t,BigInt(n));let r=e(Number(t),Number(n));return typeof r==`number`?BigInt(Math.round(r)):r}return e(Number(t),Number(n))},Re=Le((e,t)=>e-t),ze=Le((e,t)=>e+t),Be=e=>typeof e==`bigint`?!0:Number.isInteger(e),Ve=Le((e,t)=>e*t),He=Le((e,t)=>e/t),Ue=l.z.tuple([l.z.number(),l.z.number()]),We=l.z.enum([`x`,`y`]),Ge=[`top`,`right`,`bottom`,`left`];l.z.enum(Ge);var Ke=[`left`,`right`],qe=l.z.enum(Ke),Je=l.z.enum([`top`,`bottom`]),Ye=[`center`],Xe=l.z.enum(Ye);l.z.enum([`top`,`right`,`bottom`,`left`,`center`]),l.z.enum([`start`,`center`,`end`]),l.z.enum([`first`,`last`]);var Ze=l.z.object({clientX:l.z.number(),clientY:l.z.number()}),Qe=l.z.object({width:l.z.number(),height:l.z.number()}),$e=l.z.object({signedWidth:l.z.number(),signedHeight:l.z.number()});l.z.object({lower:l.z.number(),upper:l.z.number()}),l.z.enum([`x`,`y`,...Ge,...Ye]),l.z.union([We,l.z.enum([...Ge,...Ye]),l.z.instanceof(String)]);var et=(e,t,n)=>{let r={};if(typeof t==`object`&&(n=t,t=void 0),n={makeValid:!0,...n},typeof e==`number`||typeof e==`bigint`)t==null?(r.lower=typeof e==`bigint`?0n:0,r.upper=e):(r.lower=e,r.upper=t);else if(Array.isArray(e)){if(e.length!==2)throw Error(`bounds: expected array of length 2`);[r.lower,r.upper]=e}else r.lower=e.lower,r.upper=e.upper;return n?.makeValid?tt(r):r};Object.freeze({lower:0,upper:0}),Object.freeze({lower:-1/0,upper:1/0}),Object.freeze({lower:0,upper:1}),Object.freeze({lower:-1,upper:1});var tt=e=>e.lower>e.upper?{lower:e.upper,upper:e.lower}:e,nt=(e,t)=>{let n=et(e);return t<n.lower?n.lower:t>=n.upper?n.upper-(typeof n.upper==`number`?1:1n):t};l.z.object({x:qe.or(Xe),y:Je.or(Xe)});var rt=l.z.object({x:qe,y:Je}),it=Object.freeze({x:`left`,y:`top`}),at=Object.freeze({x:`right`,y:`top`}),ot=Object.freeze({x:`left`,y:`bottom`}),st=Object.freeze({x:`right`,y:`bottom`}),ct=Object.freeze({x:`center`,y:`center`}),lt=Object.freeze({x:`center`,y:`top`}),ut=Object.freeze({x:`center`,y:`bottom`}),dt=Object.freeze({x:`right`,y:`center`}),ft=Object.freeze({x:`left`,y:`center`});Object.freeze([ft,dt,lt,ut,it,at,ot,st,ct]);var pt=(e,t)=>e.x===t.x&&e.y===t.y,mt=e=>[e.x,e.y];l.z.enum([`top`,`right`,`bottom`,`left`]);var ht=l.z.object({x:l.z.number(),y:l.z.number()}),gt=l.z.union([l.z.number(),ht,Ue,Qe,$e,Ze]),_t=(e,t)=>{if(typeof e==`string`){if(t===void 0)throw Error(`The y coordinate must be given.`);return e===`x`?{x:t,y:0}:{x:0,y:t}}return typeof e==`number`?{x:e,y:t??e}:Array.isArray(e)?{x:e[0],y:e[1]}:`signedWidth`in e?{x:e.signedWidth,y:e.signedHeight}:`clientX`in e?{x:e.clientX,y:e.clientY}:`width`in e?{x:e.width,y:e.height}:{x:e.x,y:e.y}},vt=Object.freeze({x:0,y:0});Object.freeze({x:1,y:1}),Object.freeze({x:1/0,y:1/0}),Object.freeze({x:NaN,y:NaN});var yt=(e,t)=>{let n=_t(e);return{x:n.x+t,y:n.y}},bt=(e,t)=>{let n=_t(e);return{x:n.x,y:n.y+t}},xt=(e,t,n,...r)=>{if(typeof t==`string`){if(typeof n!=`number`)throw Error(`The value must be a number.`);return t===`x`?yt(e,n):bt(e,n)}if(typeof t==`object`&&`x`in t&&typeof t.x==`string`){let r=_t(n),i=_t(e);return t.x===`left`?r.x=-r.x:t.x===`center`&&(r.x=0),t.y===`top`?r.y=-r.y:t.y===`center`&&(r.y=0),{x:i.x+r.x,y:i.y+r.y}}return[e,t,n??vt,...r].reduce((e,t)=>{let n=_t(t);return{x:e.x+n.x,y:e.y+n.y}},vt)},St=l.z.union([l.z.number(),l.z.string()]);l.z.object({top:St,left:St,width:St,height:St}),l.z.object({left:l.z.number(),top:l.z.number(),right:l.z.number(),bottom:l.z.number()}),l.z.object({one:ht,two:ht,root:rt});var Ct=(e,t,n=0,r=0,i)=>{let a={one:{...vt},two:{...vt},root:i??it};if(typeof e==`number`){if(typeof t!=`number`)throw Error(`Box constructor called with invalid arguments`);return a.one={x:e,y:t},a.two={x:a.one.x+n,y:a.one.y+r},a}return`one`in e&&`two`in e&&`root`in e?{...e,root:i??e.root}:(`getBoundingClientRect`in e&&(e=e.getBoundingClientRect()),`left`in e?(a.one={x:e.left,y:e.top},a.two={x:e.right,y:e.bottom},a):(a.one=e,t==null?a.two={x:a.one.x+n,y:a.one.y+r}:typeof t==`number`?a.two={x:a.one.x+t,y:a.one.y+n}:`width`in t?a.two={x:a.one.x+t.width,y:a.one.y+t.height}:`signedWidth`in t?a.two={x:a.one.x+t.signedWidth,y:a.one.y+t.signedHeight}:a.two=t,a))},wt=(e,t)=>{let n=Ct(e);return{x:t.x===`center`?kt(n).x:Tt(n,t.x),y:t.y===`center`?kt(n).y:Tt(n,t.y)}},Tt=(e,t)=>{let n=Ct(e),r=mt(n.root).includes(t)?Math.min:Math.max;return Ke.includes(t)?r(n.one.x,n.two.x):r(n.one.y,n.two.y)},Et=e=>{let t=Ct(e);return t.two.x-t.one.x},Dt=e=>{let t=Ct(e);return t.two.y-t.one.y},Ot=e=>wt(e,it),kt=e=>xt(Ot(e),{x:Et(e)/2,y:Dt(e)/2}),At=e=>{let t=Ct(e);return{lower:t.one.x,upper:t.two.x}},jt=e=>{let t=Ct(e);return{lower:t.one.y,upper:t.two.y}},Mt=e=>typeof e!=`object`||!e?!1:`one`in e&&`two`in e&&`root`in e;l.z.union([Qe,$e,ht,Ue]);var Nt=(e,t,n)=>t!==void 0&&e<t?t:n!==void 0&&e>n?n:e;l.z.object({offset:gt,scale:gt}),l.z.object({offset:l.z.number(),scale:l.z.number()});var Pt=e=>(t,n,r,i)=>n===`dimension`?[t,r]:[t,i?r-e:r+e],Ft=e=>(t,n,r,i)=>[t,i?r/e:r*e],It=e=>(t,n,r)=>{if(t===null)return[e,r];let{lower:i,upper:a}=t,{lower:o,upper:s}=e,c=a-i,l=s-o;return n===`dimension`?[e,l/c*r]:[e,(r-i)*(l/c)+o]},Lt=e=>(t,n,r)=>[e,r],Rt=()=>(e,t,n)=>{if(e===null)throw Error(`cannot invert without bounds`);if(t===`dimension`)return[e,n];let{lower:r,upper:i}=e;return[e,i-(n-r)]},zt=e=>(t,n,r)=>{let{lower:i,upper:a}=e;return r=Nt(r,i,a),[t,r]},Bt=class e{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(t){return new e().translate(t)}static magnify(t){return new e().magnify(t)}static scale(t,n){return new e().scale(t,n)}translate(e){let t=this.new(),n=Pt(e);return n.type=`translate`,t.ops.push(n),t}magnify(e){let t=this.new(),n=Ft(e);return n.type=`magnify`,t.ops.push(n),t}scale(e,t){let n=et(e,t),r=this.new(),i=It(n);return i.type=`scale`,r.ops.push(i),r}clamp(e,t){let n=et(e,t),r=this.new(),i=zt(n);return i.type=`clamp`,r.ops.push(i),r}reBound(e,t){let n=et(e,t),r=this.new(),i=Lt(n);return i.type=`re-bound`,r.ops.push(i),r}invert(){let e=Rt();e.type=`invert`;let t=this.new();return t.ops.push(e),t}pos(e){return this.exec(`position`,e)}dim(e){return this.exec(`dimension`,e)}new(){let t=new e;return t.ops=this.ops.slice(),t.reversed=this.reversed,t}exec(e,t){return this.currBounds=null,this.ops.reduce(([t,n],r)=>r(t,e,n,this.reversed),[null,t])[1]}reverse(){let e=this.new();e.ops.reverse();let t=[];return e.ops.forEach((n,r)=>{if(n.type===`scale`||t.some(([e,t])=>r>=e&&r<=t))return;let i=e.ops.findIndex((e,t)=>e.type===`scale`&&t>r);i!==-1&&t.push([r,i])}),t.forEach(([t,n])=>{let r=e.ops.slice(t,n);r.unshift(e.ops[n]),e.ops.splice(t,n-t+1,...r)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new e};(class e{x;y;currRoot;constructor(e=new Bt,t=new Bt,n=null){this.x=e,this.y=t,this.currRoot=n}static translate(t,n){return new e().translate(t,n)}static translateX(t){return new e().translateX(t)}static translateY(t){return new e().translateY(t)}static clamp(t){return new e().clamp(t)}static magnify(t){return new e().magnify(t)}static scale(t){return new e().scale(t)}static reBound(t){return new e().reBound(t)}translate(e,t){let n=_t(e,t),r=this.copy();return r.x=this.x.translate(n.x),r.y=this.y.translate(n.y),r}translateX(e){let t=this.copy();return t.x=this.x.translate(e),t}translateY(e){let t=this.copy();return t.y=this.y.translate(e),t}magnify(e){let t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){let t=this.copy();if(Mt(e)){let n=this.currRoot;return t.currRoot=e.root,n!=null&&!pt(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(At(e)),t.y=t.y.scale(jt(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){let t=this.copy();return t.x=this.x.reBound(At(e)),t.y=this.y.reBound(jt(e)),t}clamp(e){let t=this.copy();return t.x=this.x.clamp(At(e)),t.y=this.y.clamp(jt(e)),t}copy(){let t=new e;return t.currRoot=this.currRoot,t.x=this.x,t.y=this.y,t}reverse(){let 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 Ct(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 e}),ht.extend({root:rt,units:l.default.object({x:l.default.enum([`px`,`decimal`]),y:l.default.enum([`px`,`decimal`])})}).partial({root:!0,units:!0});var Vt=l.z.enum([`static`,`dynamic`]),Ht=365,Ut=30,Wt=l.z.union([l.z.tuple([l.z.int()]),l.z.tuple([l.z.int(),l.z.int().min(1).max(12)]),l.z.tuple([l.z.int(),l.z.int().min(1).max(12),l.z.int().min(1).max(31)])]),Gt=(e,t)=>{let n=new _(t);if(![v.DAY,v.HOUR,v.MINUTE,v.SECOND,v.MILLISECOND,v.MICROSECOND,v.NANOSECOND].some(e=>e.equals(n)))throw Error(`Invalid argument for remainder. Must be an even TimeSpan or Timestamp`);let r=e.valueOf()%n.valueOf();return e instanceof _?new _(r):new v(r)},_=class e extends ge{constructor(t,n=`UTC`){if(t==null)super(e.now().valueOf());else if(t instanceof Date)super(BigInt(t.getTime())*e.MILLISECOND.valueOf());else if(typeof t==`string`)super(e.parseDateTimeString(t,n).valueOf());else if(Array.isArray(t))super(e.parseDate(t));else{let r=0n;t instanceof Number&&(t=t.valueOf()),n===`local`&&(r=e.utcOffset.valueOf()),typeof t==`number`&&(isFinite(t)?t=t===Ie?Pe:Math.trunc(t):(isNaN(t)&&(t=0),t=t===1/0?e.MAX:e.MIN)),he(t)&&(t=t.value),super(BigInt(t.valueOf())+r)}}static parseDate([t=1970,n=1,r=1]){let i=new Date(t,n-1,r,0,0,0,0);return new e(BigInt(i.getTime())*e.MILLISECOND.valueOf()).truncate(e.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(t,n=`UTC`){let[r,i,a]=t.split(`:`),o=`00`,s=`00`;a!=null&&([o,s]=a.split(`.`));let c=e.hours(parseInt(r??`00`,10)).add(e.minutes(parseInt(i??`00`,10))).add(e.seconds(parseInt(o??`00`,10))).add(e.milliseconds(parseInt(s??`00`,10)));return n===`local`&&(c=c.add(e.utcOffset)),c.valueOf()}static parseDateTimeString(t,n=`UTC`){if(!t.includes(`/`)&&!t.includes(`-`))return e.parseTimeString(t,n);if(t.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let r=t,i=0;if(t.includes(`.`)){let e=t.split(`.`);r=e[0];let n=e[1]||`0`;i=parseInt(n.padEnd(3,`0`).slice(0,3),10)}let a=n===`local`?new Date(r.replace(`T`,` `)):new Date(`${r}Z`);return BigInt(a.getTime())*e.MILLISECOND.valueOf()+BigInt(i)*e.MILLISECOND.valueOf()}let r=new Date(t);return t.includes(`:`)||r.setUTCHours(0,0,0,0),new e(BigInt(r.getTime())*e.MILLISECOND.valueOf(),n).valueOf()}toISOString(t=`UTC`){if(t===`UTC`)return this.date().toISOString();let n=this.date(),r=new v(BigInt(n.getTimezoneOffset())*e.MINUTE.valueOf());return this.sub(r).date().toISOString()}timeString(e=!1,t=`UTC`){let n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){let e=this.date();return`${e.toLocaleString(`default`,{month:`short`})} ${e.toLocaleString(`default`,{day:`numeric`})}`}static get utcOffset(){return new v(BigInt(new Date().getTimezoneOffset())*e.MINUTE.valueOf())}static since(t){return new e().span(t)}date(){return new Date(this.milliseconds)}equals(t){return this.valueOf()===new e(t).valueOf()}span(e){return this.range(e).span}range(e){return new qt(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(t){return this.valueOf()>new e(t).valueOf()}afterEq(t){return this.valueOf()>=new e(t).valueOf()}before(t){return this.valueOf()<new e(t).valueOf()}beforeEq(t){return this.valueOf()<=new e(t).valueOf()}add(t){return new e(ze(this.valueOf(),new v(t).valueOf()))}sub(t){return new e(Re(this.valueOf(),new v(t).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(e.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(e.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}get localYear(){return this.date().getFullYear()}setYear(t){let n=this.date();return n.setUTCFullYear(t),new e(n)}setLocalYear(t){let n=this.date();return n.setFullYear(t),new e(n)}get month(){return this.date().getUTCMonth()}get localMonth(){return this.date().getMonth()}setMonth(t){let n=this.date();return n.setUTCMonth(t),new e(n)}setLocalMonth(t){let n=this.date();return n.setMonth(t),new e(n)}get day(){return this.date().getUTCDate()}get localDay(){return this.date().getDate()}setDay(t){let n=this.date();return n.setUTCDate(t),new e(n)}setLocalDay(t){let n=this.date();return n.setDate(t),new e(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(t){let n=this.date();return n.setHours(t),new e(n)}setHour(t){let n=this.date();return n.setUTCHours(t),new e(n)}get minute(){return this.date().getUTCMinutes()}get localMinute(){return this.date().getMinutes()}setMinute(t){let n=this.date();return n.setUTCMinutes(t),new e(n)}setLocalMinute(t){let n=this.date();return n.setMinutes(t),new e(n)}get second(){return this.date().getUTCSeconds()}get localSecond(){return this.date().getSeconds()}setSecond(t){let n=this.date();return n.setUTCSeconds(t),new e(n)}setLocalSecond(t){let n=this.date();return n.setSeconds(t),new e(n)}get millisecond(){return this.date().getUTCMilliseconds()}get localMillisecond(){return this.date().getMilliseconds()}setMillisecond(t){let n=this.date();return n.setUTCMilliseconds(t),new e(n)}setLocalMillisecond(t){let n=this.date();return n.setMilliseconds(t),new e(n)}toString(e=`ISO`,t=`UTC`){switch(e){case`ISODate`:return this.toISOString(t).slice(0,10);case`ISOTime`:return this.toISOString(t).slice(11,23);case`time`:return this.timeString(!1,t);case`preciseTime`:return this.timeString(!0,t);case`date`:return this.dateString();case`preciseDate`:return`${this.dateString()} ${this.timeString(!0,t)}`;case`dateTime`:return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}remainder(e){return Gt(this,e)}get isToday(){return this.truncate(v.DAY).equals(e.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 e(new Date)}static max(...t){let n=e.MIN;for(let r of t){let t=new e(r);t.after(n)&&(n=t)}return n}static min(...t){let n=e.MAX;for(let r of t){let t=new e(r);t.before(n)&&(n=t)}return n}static nanoseconds(t,n=`UTC`){return new e(t,n)}static NANOSECOND=e.nanoseconds(1);static microseconds(t,n=`UTC`){return e.nanoseconds(t*1e3,n)}static MICROSECOND=e.microseconds(1);static milliseconds(t,n=`UTC`){return e.microseconds(t*1e3,n)}static MILLISECOND=e.milliseconds(1);static seconds(t,n=`UTC`){return e.milliseconds(t*1e3,n)}static SECOND=e.seconds(1);static minutes(t,n=`UTC`){return e.seconds(t*60,n)}static MINUTE=e.minutes(1);static hours(t,n=`UTC`){return e.minutes(t*60,n)}static HOUR=e.hours(1);static days(t,n=`UTC`){return e.hours(t*24,n)}static DAY=e.days(1);static MAX=new e(Pe);static MIN=new e(0);static ZERO=new e(0);static z=l.z.union([l.z.instanceof(e),l.z.object({value:l.z.bigint()}).transform(t=>new e(t.value)),l.z.string().transform(t=>new e(BigInt(t))),l.z.number().transform(t=>new e(t)),l.z.bigint().transform(t=>new e(t)),l.z.date().transform(t=>new e(t)),l.z.custom(e=>e instanceof v).transform(t=>new e(t)),Wt.transform(t=>new e(t))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}},v=class e extends ge{constructor(e){typeof e==`number`&&(e=Math.trunc(e.valueOf())),he(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(t){return t instanceof e?t:t instanceof Kt?t.period:t instanceof _?new e(t):(he(t)&&(t=t.value),[`number`,`bigint`].includes(typeof t)?e.seconds(t):new e(t))}static fromMilliseconds(t){return t instanceof e?t:t instanceof Kt?t.period:t instanceof _?new e(t):(he(t)&&(t=t.value),[`number`,`bigint`].includes(typeof t)?e.milliseconds(t):new e(t))}valueOf(){return this.value}lessThan(t){return this.valueOf()<new e(t).valueOf()}greaterThan(t){return this.valueOf()>new e(t).valueOf()}lessThanOrEqual(t){return this.valueOf()<=new e(t).valueOf()}greaterThanOrEqual(t){return this.valueOf()>=new e(t).valueOf()}remainder(e){return Gt(this,e)}truncate(t){return new e(BigInt(Math.trunc(Number(this.valueOf()/t.valueOf())))*t.valueOf())}toString(t=`full`){if(t===`semantic`)return this.toSemanticString();let n=this.truncate(e.DAY),r=this.truncate(e.HOUR),i=this.truncate(e.MINUTE),a=this.truncate(e.SECOND),o=this.truncate(e.MILLISECOND),s=this.truncate(e.MICROSECOND),c=this.truncate(e.NANOSECOND),l=n,u=r.sub(n),d=i.sub(r),f=a.sub(i),p=o.sub(a),m=s.sub(o),h=c.sub(s),g=``;return l.isZero||(g+=`${l.days}d `),u.isZero||(g+=`${u.hours}h `),d.isZero||(g+=`${d.minutes}m `),f.isZero||(g+=`${f.seconds}s `),p.isZero||(g+=`${p.milliseconds}ms `),m.isZero||(g+=`${m.microseconds}µs `),h.isZero||(g+=`${h.nanoseconds}ns`),g.trim()}toSemanticString(){let t=new e(this.valueOf()<0n?-this.valueOf():this.valueOf()),n=this.valueOf()<0n;if(t.valueOf()===0n)return`0s`;if(t.lessThan(e.SECOND))return`< 1s`;let r=t.days,i=t.hours,a=t.minutes,o=t.seconds,s=Math.floor(r/Ht),c=Math.floor(r/Ut),l=Math.floor(r/7),u=Math.floor(r),d=Math.floor(i),f=Math.floor(a),p=Math.floor(o),m=n?`-`:``;if(s>=1){let e=`${s}y`;if(s<2){let t=Math.floor(r%Ht/Ut);t>0&&(e+=` ${t}mo`)}return m+e}if(l>=1&&r<Ut&&r%7==0){let e=`${l}w`,t=Math.floor(r%7),n=Math.floor(i-l*7*24);return l<2&&(t>0?e+=` ${t}d`:n>0&&n<24&&(e+=` ${n}h`)),m+e}if(c>=1){let e=`${c}mo`;if(c<3){let t=Math.floor(r%Ut);t>0&&(e+=` ${t}d`)}return m+e}if(l>=1){let e=`${l}w`,t=Math.floor(r%7),n=Math.floor(i-l*7*24);return l<2&&(t>0?e+=` ${t}d`:n>0&&n<24&&(e+=` ${n}h`)),m+e}if(u>=1){let e=`${u}d`,t=Math.floor(i-u*24);return u<2&&t>0&&(e+=` ${t}h`),m+e}if(d>=1){let e=`${d}h`;if(d<3){let t=Math.floor(a-d*60);t>0&&(e+=` ${t}m`)}return m+e}if(f>=1){let e=`${f}m`;if(f<5){let t=Math.floor(o-f*60);t>0&&(e+=` ${t}s`)}return m+e}return`${m}${p}s`}mult(t){return new e(Ve(this.valueOf(),t))}div(t){return new e(He(this.valueOf(),t))}get days(){return Number(this.valueOf())/Number(e.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(e.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(e.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(e.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(e.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(e.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(t){return this.valueOf()===new e(t).valueOf()}add(t){return new e(this.valueOf()+new e(t).valueOf())}sub(t){return new e(this.valueOf()-new e(t).valueOf())}static nanoseconds(t=1){return new e(t)}static NANOSECOND=e.nanoseconds(1);static microseconds(t=1){return e.nanoseconds(Ve(t,1e3))}static MICROSECOND=e.microseconds(1);static milliseconds(t=1){return e.microseconds(Ve(t,1e3))}static MILLISECOND=e.milliseconds(1);static seconds(t=1){return e.milliseconds(Ve(t,1e3))}static SECOND=e.seconds(1);static minutes(t=1){return e.seconds(Ve(t,60))}static MINUTE=e.minutes(1);static hours(t){return e.minutes(Ve(t,60))}static HOUR=e.hours(1);static days(t){return e.hours(Ve(t,24))}static DAY=e.days(1);static MAX=new e(Pe);static MIN=new e(0);static ZERO=new e(0);static z=l.z.union([l.z.object({value:l.z.bigint()}).transform(t=>new e(t.value)),l.z.string().transform(t=>new e(BigInt(t))),l.z.number().transform(t=>new e(t)),l.z.bigint().transform(t=>new e(t)),l.z.instanceof(e),l.z.instanceof(_).transform(t=>new e(t)),l.z.custom(e=>e instanceof Kt).transform(t=>new e(t))])},Kt=class e extends ge{constructor(e){he(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(t){return this.valueOf()===new e(t).valueOf()}get period(){return v.seconds(1/this.valueOf())}sampleCount(e){return new v(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new y(t).valueOf()}span(e){return v.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/new y(t).valueOf())}add(t){return new e(ze(this.valueOf(),new e(t).valueOf()))}sub(t){return new e(Re(this.valueOf(),new e(t).valueOf()))}mult(t){return new e(Ve(this.valueOf(),t))}div(t){return new e(He(this.valueOf(),t))}static hz(t){return new e(t)}static khz(t){return e.hz(t*1e3)}static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)])},y=class e extends ge{constructor(e){he(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new Jt(e*this.valueOf())}add(t){return new e(ze(this.valueOf(),new e(t).valueOf()))}sub(t){return new e(Re(this.valueOf(),new e(t).valueOf()))}mult(t){return new e(Ve(this.valueOf(),t))}div(t){return new e(He(this.valueOf(),t))}static UNKNOWN=new e(0);static BIT128=new e(16);static BIT64=new e(8);static BIT32=new e(4);static BIT16=new e(2);static BIT8=new e(1);static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)])},qt=class e{start;end;constructor(e,t){typeof e==`object`&&`start`in e?(this.start=new _(e.start),this.end=new _(e.end)):(this.start=new _(e),this.end=new _(t))}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 e(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=v.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),r=this.end.sub(e.end).valueOf();return n<0&&(n=-n),r<0&&(r=-r),n<=t.valueOf()&&r<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString(`preciseDate`)} - ${this.span.toString()}`}overlapsWith(e,t=v.ZERO){e=e.makeValid();let n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;let r=_.max(n.start,e.start),i=_.min(n.end,e.end);return i.before(r)?!1:new v(i.sub(r)).greaterThanOrEqual(t)}contains(t){return t instanceof e?this.contains(t.start)&&this.contains(t.end):this.start.beforeEq(t)&&this.end.after(t)}boundBy(t){let n=new e(this.start,this.end);return t.start.after(this.start)&&(n.start=t.start),t.start.after(this.end)&&(n.end=t.start),t.end.before(this.end)&&(n.end=t.end),t.end.before(this.start)&&(n.start=t.end),n}static max(...t){return new e(_.min(...t.map(e=>e.start)),_.max(...t.map(e=>e.end)))}static MAX=new e(_.MIN,_.MAX);static ZERO=new e(_.ZERO,_.ZERO);static z=l.z.union([l.z.object({start:_.z,end:_.z}).transform(t=>new e(t.start,t.end)),l.z.instanceof(e)]);static boundedZ=e.z.refine(({isValid:e})=>e,{message:`Time range start time must be before or equal to time range end time`}).refine(({end:e})=>e.valueOf()<=Pe,{message:`Time range end time must be less than or equal to the maximum value of an int64`}).refine(({start:e})=>e.valueOf()>=Ne,{message:`Time range start time must be greater than or equal to the minimum value of an int64`});static sort(e,t){return _.sort(e.start,t.start)||_.sort(e.end,t.end)}static merge(...t){return e.max(...t.map(t=>new e(t).makeValid()))}},b=class e extends ge{constructor(t){if(he(t)&&(t=t.value),t instanceof e||typeof t==`string`||typeof t.valueOf()==`string`)super(t.valueOf());else{let n=e.ARRAY_CONSTRUCTOR_DATA_TYPES.get(t.constructor.name);if(n==null)throw Error(`unable to find data type for ${t.toString()}`);super(n.valueOf())}}get Array(){let t=e.ARRAY_CONSTRUCTORS.get(this.toString());if(t==null)throw Error(`unable to find array constructor for ${this.valueOf()}`);return t}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(e=>this.equals(e))}toString(t=!1){return t?e.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(e.JSON)||this.equals(e.STRING)||this.equals(e.BYTES)}get isNumeric(){return!this.isVariable&&!this.equals(e.UUID)}get isInteger(){let e=this.toString();return e.startsWith(`int`)||e.startsWith(`uint`)}get isFloat(){return this.toString().startsWith(`float`)}get density(){let t=e.DENSITIES.get(this.toString());if(t==null)throw Error(`unable to find density for ${this.valueOf()}`);return t}get isUnsignedInteger(){return this.equals(e.UINT8)||this.equals(e.UINT16)||this.equals(e.UINT32)||this.equals(e.UINT64)}get isSignedInteger(){return this.equals(e.INT8)||this.equals(e.INT16)||this.equals(e.INT32)||this.equals(e.INT64)}canSafelyCastTo(t){return this.equals(t)?!0:!this.isNumeric||!t.isNumeric||this.isVariable||t.isVariable||this.isUnsignedInteger&&t.isSignedInteger?!1:this.isFloat?t.isFloat&&this.density.valueOf()<=t.density.valueOf():this.equals(e.INT32)&&t.equals(e.FLOAT64)||this.equals(e.INT8)&&t.equals(e.FLOAT32)?!0:this.isInteger&&t.isInteger?this.density.valueOf()<=t.density.valueOf()&&this.isUnsignedInteger===t.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return e.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new e(`unknown`);static FLOAT64=new e(`float64`);static FLOAT32=new e(`float32`);static INT64=new e(`int64`);static INT32=new e(`int32`);static INT16=new e(`int16`);static INT8=new e(`int8`);static UINT64=new e(`uint64`);static UINT32=new e(`uint32`);static UINT16=new e(`uint16`);static UINT8=new e(`uint8`);static TIMESTAMP=new e(`timestamp`);static UUID=new e(`uuid`);static STRING=new e(`string`);static JSON=new e(`json`);static BYTES=new e(`bytes`);static ARRAY_CONSTRUCTORS=new Map([[e.UINT8.toString(),Uint8Array],[e.UINT16.toString(),Uint16Array],[e.UINT32.toString(),Uint32Array],[e.UINT64.toString(),BigUint64Array],[e.FLOAT32.toString(),Float32Array],[e.FLOAT64.toString(),Float64Array],[e.INT8.toString(),Int8Array],[e.INT16.toString(),Int16Array],[e.INT32.toString(),Int32Array],[e.INT64.toString(),BigInt64Array],[e.TIMESTAMP.toString(),BigInt64Array],[e.STRING.toString(),Uint8Array],[e.JSON.toString(),Uint8Array],[e.UUID.toString(),Uint8Array],[e.BYTES.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,e.UINT8],[Uint16Array.name,e.UINT16],[Uint32Array.name,e.UINT32],[BigUint64Array.name,e.UINT64],[Float32Array.name,e.FLOAT32],[Float64Array.name,e.FLOAT64],[Int8Array.name,e.INT8],[Int16Array.name,e.INT16],[Int32Array.name,e.INT32],[BigInt64Array.name,e.INT64]]);static DENSITIES=new Map([[e.UINT8.toString(),y.BIT8],[e.UINT16.toString(),y.BIT16],[e.UINT32.toString(),y.BIT32],[e.UINT64.toString(),y.BIT64],[e.FLOAT32.toString(),y.BIT32],[e.FLOAT64.toString(),y.BIT64],[e.INT8.toString(),y.BIT8],[e.INT16.toString(),y.BIT16],[e.INT32.toString(),y.BIT32],[e.INT64.toString(),y.BIT64],[e.TIMESTAMP.toString(),y.BIT64],[e.STRING.toString(),y.UNKNOWN],[e.JSON.toString(),y.UNKNOWN],[e.UUID.toString(),y.BIT128],[e.BYTES.toString(),y.UNKNOWN]]);static ALL=[e.UNKNOWN,e.UINT8,e.UINT16,e.UINT32,e.UINT64,e.INT8,e.INT16,e.INT32,e.INT64,e.FLOAT32,e.FLOAT64,e.TIMESTAMP,e.UUID,e.STRING,e.JSON,e.BYTES];static SHORT_STRINGS=new Map([[e.UINT8.toString(),`u8`],[e.UINT16.toString(),`u16`],[e.UINT32.toString(),`u32`],[e.UINT64.toString(),`u64`],[e.INT8.toString(),`i8`],[e.INT16.toString(),`i16`],[e.INT32.toString(),`i32`],[e.INT64.toString(),`i64`],[e.FLOAT32.toString(),`f32`],[e.FLOAT64.toString(),`f64`],[e.TIMESTAMP.toString(),`ts`],[e.UUID.toString(),`uuid`],[e.STRING.toString(),`str`],[e.JSON.toString(),`json`],[e.BYTES.toString(),`bytes`]]);static BIG_INT_TYPES=[e.INT64,e.UINT64,e.TIMESTAMP];static z=l.z.union([l.z.string().transform(t=>new e(t)),l.z.instanceof(e)])},Jt=class e extends ge{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(t){return he(t)&&(t=t.value),new e(ze(this.valueOf(),t.valueOf()))}sub(t){return he(t)&&(t=t.value),new e(Re(this.valueOf(),t.valueOf()))}mult(t){return new e(Ve(this.valueOf(),t))}div(t){return new e(He(this.valueOf(),t))}truncate(t){return new e(Math.trunc(this.valueOf()/new e(t).valueOf())*new e(t).valueOf())}remainder(t){return e.bytes(this.valueOf()%new e(t).valueOf())}get gigabytes(){return this.valueOf()/e.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/e.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/e.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/e.TERABYTE.valueOf()}toString(){let t=this.truncate(e.TERABYTE),n=this.truncate(e.GIGABYTE),r=this.truncate(e.MEGABYTE),i=this.truncate(e.KILOBYTE),a=this.truncate(e.BYTE),o=t,s=n.sub(t),c=r.sub(n),l=i.sub(r),u=a.sub(i),d=``;return o.isZero||(d+=`${o.terabytes}TB `),s.isZero||(d+=`${s.gigabytes}GB `),c.isZero||(d+=`${c.megabytes}MB `),l.isZero||(d+=`${l.kilobytes}KB `),(!u.isZero||d===``)&&(d+=`${u.valueOf()}B`),d.trim()}static bytes(t=1){return new e(t)}static BYTE=new e(1);static kilobytes(t=1){return e.bytes(new e(t).valueOf()*1e3)}static KILOBYTE=e.kilobytes(1);static megabytes(t=1){return e.kilobytes(new e(t).valueOf()*1e3)}static MEGABYTE=e.megabytes(1);static gigabytes(t=1){return e.megabytes(new e(t).valueOf()*1e3)}static GIGABYTE=e.gigabytes(1);static terabytes(t){return e.gigabytes(new e(t).valueOf()*1e3)}static TERABYTE=e.terabytes(1);static ZERO=new e(0);static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)]);get isZero(){return this.valueOf()===0}};l.z.object({start:l.z.number(),end:l.z.number()}),l.z.union([l.z.instanceof(Uint8Array),l.z.instanceof(Uint16Array),l.z.instanceof(Uint32Array),l.z.instanceof(BigUint64Array),l.z.instanceof(Float32Array),l.z.instanceof(Float64Array),l.z.instanceof(Int8Array),l.z.instanceof(Int16Array),l.z.instanceof(Int32Array),l.z.instanceof(BigInt64Array)]);var Yt=e=>{let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===`bigint`||e instanceof _||e instanceof v||e instanceof Date},Xt=(e,t,n,r=0)=>e.usesBigInt&&!t.usesBigInt?Number(n)-Number(r):!e.usesBigInt&&t.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Re(n,r);qt.z,_.z,v.z,Kt.z,Jt.z,b.z,qt.boundedZ;var Zt=/^(?:[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 Qt(e){return typeof e==`string`&&Zt.test(e)}var x=[];for(let e=0;e<256;++e)x.push((e+256).toString(16).slice(1));function $t(e,t=0){return(x[e[t+0]]+x[e[t+1]]+x[e[t+2]]+x[e[t+3]]+`-`+x[e[t+4]]+x[e[t+5]]+`-`+x[e[t+6]]+x[e[t+7]]+`-`+x[e[t+8]]+x[e[t+9]]+`-`+x[e[t+10]]+x[e[t+11]]+x[e[t+12]]+x[e[t+13]]+x[e[t+14]]+x[e[t+15]]).toLowerCase()}function en(e,t=0){let n=$t(e,t);if(!Qt(n))throw TypeError(`Stringified UUID is invalid`);return n}typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var tn=(e,t)=>en(e,t),nn=-1,rn={[Symbol.iterator]:()=>rn,next:()=>({done:!0,value:void 0})},an=l.z.string().transform(e=>new Uint8Array(atob(e).split(``).map(e=>e.charCodeAt(0))).buffer),on=l.z.union([l.z.null(),l.z.undefined()]).transform(()=>new Uint8Array().buffer),sn=10,cn=(e,t)=>{if(e===`number`&&!t.isNumeric)throw Error(`cannot convert series of type ${t.toString()} to number`);if(e===`bigint`&&!t.usesBigInt)throw Error(`cannot convert series of type ${t.toString()} to bigint`)},ln=`sy_x_telem_series`,un=class e{key;discriminator=ln;dataType;sampleOffset;gl;_data;timeRange=qt.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=nn;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=l.z.object({timeRange:qt.z.optional(),dataType:b.z,alignment:l.z.coerce.bigint().optional(),data:l.z.union([an,on,l.z.instanceof(ArrayBuffer),l.z.instanceof(Uint8Array)]),glBufferUsage:Vt.default(`static`).optional()});static z=e.crudeZ.transform(t=>new e(t));constructor(e){dn(e)&&(e={data:e}),e.data??=[];let{dataType:t,timeRange:n,sampleOffset:r=0,glBufferUsage:i=`static`,alignment:a=0n,alignmentMultiple:o=1n,key:s=Te(),data:c}=e;if(fn(c)){let e=c;this.key=e.key,this.dataType=e.dataType,this.sampleOffset=e.sampleOffset,this.gl=e.gl,this._data=e._data,this.timeRange=e.timeRange,this.alignment=e.alignment,this.alignmentMultiple=e.alignmentMultiple,this.cachedMin=e.cachedMin,this.cachedMax=e.cachedMax,this.writePos=e.writePos,this._refCount=e._refCount,this.cachedLength=e.cachedLength;return}let l=Yt(c),u=Array.isArray(c);if(t!=null)this.dataType=new b(t);else if(c instanceof ArrayBuffer)throw Error(`cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.`);else if(u||l){let e=c;if(!l){if(c.length===0)throw Error(`cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.`);e=c[0]}if(typeof e==`string`)this.dataType=b.STRING;else if(typeof e==`number`)this.dataType=b.FLOAT64;else if(typeof e==`bigint`)this.dataType=b.INT64;else if(typeof e==`boolean`)this.dataType=b.UINT8;else if(e instanceof _||e instanceof Date||e instanceof _)this.dataType=b.TIMESTAMP;else if(typeof e==`object`)this.dataType=b.JSON;else throw Error(`cannot infer data type of ${typeof e} when constructing a Series from a JS array`)}else this.dataType=new b(c);if(!u&&!l)this._data=c;else if(u&&c.length===0)this._data=new this.dataType.Array([]).buffer;else{let e=l?[c]:c,t=e[0];(t instanceof _||t instanceof Date||t instanceof v)&&(e=e.map(e=>new _(e).valueOf())),this.dataType.equals(b.STRING)?(this.cachedLength=e.length,this._data=new TextEncoder().encode(`${e.join(`
4
- `)}\n`).buffer):this.dataType.equals(b.JSON)?(this.cachedLength=e.length,this._data=new TextEncoder().encode(`${e.map(e=>me.encodeString(e)).join(`
5
- `)}\n`).buffer):this.dataType.usesBigInt&&typeof t==`number`?this._data=new this.dataType.Array(e.map(e=>BigInt(Math.round(e)))).buffer:!this.dataType.usesBigInt&&typeof t==`bigint`?this._data=new this.dataType.Array(e.map(Number)).buffer:this._data=new this.dataType.Array(e).buffer}this.key=s,this.alignment=a,this.alignmentMultiple=o,this.sampleOffset=r??0,this.timeRange=n??qt.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:t,dataType:n,...r}){if(t===0)throw Error(`[Series] - cannot allocate an array of length 0`);let i=new e({data:new new b(n).Array(t).buffer,dataType:n,...r});return i.writePos=0,i}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 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===nn)return 0;let t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===nn)return 0;let t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this.cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.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===nn?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 Error(`cannot parse non-JSON series as JSON`);return this.toStrings().map(t=>e.parse(me.decodeString(t)))}get byteCapacity(){return new Jt(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===nn?this.byteCapacity:this.dataType.isVariable?new Jt(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength==null?this.dataType.isVariable?this.calculateCachedLength():this.writePos===nn?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos:this.cachedLength}calculateCachedLength(){if(!this.dataType.isVariable)throw Error(`cannot calculate length of a non-variable length data type`);let e=0,t=[0];return this.data.forEach((n,r)=>{n===sn&&(e++,t.push(r+1))}),this._cachedIndexes=t,this.cachedLength=e,e}convert(t,n=0){if(this.dataType.equals(t))return this;let r=new t.Array(this.length);for(let e=0;e<this.length;e++)r[e]=Xt(this.dataType,t,this.data[e],n);return new e({data:r.buffer,dataType:t,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){return this.length===0?-1/0:(this.dataType.equals(b.TIMESTAMP)?this.cachedMax=this.data[this.data.length-1]:(this.dataType.usesBigInt,this.cachedMax=this.data.reduce((e,t)=>e>t?e:t)),this.cachedMax)}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw Error(`cannot calculate maximum on a variable length data type`);return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),ze(this.cachedMax,this.sampleOffset))}calcRawMin(){return this.length===0?1/0:(this.dataType.equals(b.TIMESTAMP)?this.cachedMin=this.data[0]:(this.dataType.usesBigInt,this.cachedMin=this.data.reduce((e,t)=>e<t?e:t)),this.cachedMin)}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw Error(`cannot calculate minimum on a variable length data type`);return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),ze(this.cachedMin,this.sampleOffset))}get bounds(){return et(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){let t=e.cachedMin??e.calcRawMin();t<this.cachedMin&&(this.cachedMin=t)}if(this.cachedMax!=null){let t=e.cachedMax??e.calcRawMax();t>this.cachedMax&&(this.cachedMax=t)}}atAlignment(e,t){let n=Number((e-this.alignment)/this.alignmentMultiple);if(n<0||n>=this.length){if(t===!0)throw Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(b.UUID))return this.atUUID(e,t);e<0&&(e=this.length+e);let n=this.data[e];if(n==null){if(t===!0)throw Error(`[series] - no value at index ${e}`);return}return ze(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);let n=tn(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){let n=0,r=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],r=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let t=0;t<this.data.length;t++)if(this.data[t]===sn){if(e===0){r=t;break}n=t+1,e--}if(r===0&&(r=this.data.length),n>=r||e>0){if(t)throw Error(`[series] - no value at index ${e}`);return}}let i=this.data.slice(n,r);return this.dataType.equals(b.STRING)?new TextDecoder().decode(i):ae(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let t=0,n=this.length-1,r=ve(e);for(;t<=n;){let i=Math.floor((t+n)/2),a=r(this.at(i,!0),e);if(a===0)return i;a<0?t=i+1:n=i-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(b.FLOAT32)&&!this.dataType.equals(b.UINT8))throw Error(`Only FLOAT32 and UINT8 arrays can be used in WebGL`);let{buffer:t,bufferUsage:n,prevBuffer:r}=this.gl;if(t??(this.gl.buffer=e.createBuffer()),this.writePos!==r)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==nn){r===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);let t=this.dataType.density.size(r).valueOf(),n=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,t,n.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n===`static`?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=nn}as(e){return cn(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:vn(this.alignmentBounds.lower),upper:vn(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 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){let e=new mn(this);return this.dataType.equals(b.JSON)?new hn(e):e}return this.dataType.equals(b.UUID)?new gn(this):new _n(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new pn(this,e,t??this.length)}subAlignmentIterator(e,t){let n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),r=Math.ceil(Number(t-this.alignment)/Number(this.alignmentMultiple));return new pn(this,n,r)}subBytes(t,n){return t>=0&&(n==null||n>=this.byteLength.valueOf())?this:new e({data:this.data.subarray(t,n),dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}sliceSub(t,n,r){if(n<=0&&(r==null||r>=this.length))return this;let i;return i=t?this.data.subarray(n,r):this.data.slice(n,r),new e({data:i,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(t){return new e({data:this.buffer,dataType:this.dataType,timeRange:qt.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:`static`,alignment:t})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(e=>e.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=`,`;e+=`...,`;for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=`,`)}return e+=`])`,e}},dn=e=>e==null?!1:Array.isArray(e)||e instanceof ArrayBuffer||ArrayBuffer.isView(e)&&!(e instanceof DataView)||e instanceof un?!0:Yt(e),fn=Ee(ln,un),pn=class{series;end;index;constructor(e,t,n){this.series=e;let r=et(0,e.length+1);this.end=nt(r,n),this.index=nt(r,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},mn=class{series;index;decoder;constructor(e){if(!e.dataType.isVariable)throw Error(`cannot create a variable series iterator for a non-variable series`);this.series=e,this.index=0,this.decoder=new TextDecoder}next(){let e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==sn;)this.index++;let n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}},hn=class e{wrapped;static schema=l.z.record(l.z.string(),l.z.unknown());constructor(e){this.wrapped=e}next(){let t=this.wrapped.next();return t.done===!0?{done:!0,value:void 0}:{done:!1,value:me.decodeString(t.value,e.schema)}}},gn=class{series;index;data;density;constructor(e){if(!e.dataType.equals(b.UUID))throw 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};let e=tn(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}},_n=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)}}},vn=e=>({domain:e>>32n,sample:e&4294967295n}),yn=async e=>await new Promise(t=>setTimeout(t,v.fromMilliseconds(e).milliseconds)),bn=p({Breaker:()=>xn,breakerConfigZ:()=>Sn}),xn=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??yn},this.retries=0,this.interval=new v(this.config.baseInterval)}async wait(){let{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),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}},Sn=l.z.object({baseInterval:v.z.optional(),maxRetries:l.z.number().optional(),scale:l.z.number().optional()});l.z.int().min(Ae).max(127),l.z.int().min(je).max(Me),l.z.int().min(Fe).max(Ie);var Cn=l.z.int().min(0).max(255);l.z.int().min(0).max(De),l.z.int().min(0).max(Oe),l.z.int().min(0).max(ke);var wn=(e,t)=>{let n=Array.isArray(e),r=Array.isArray(t);if(n!==r)return!1;if(n&&r){let n=e,r=t;if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++)if(!wn(n[e],r[e]))return!1;return!0}if(e==null||t==null||typeof e!=`object`||typeof t!=`object`)return e===t;if(`equals`in e)return e.equals(t);let i=Object.keys(e),a=Object.keys(t);if(i.length!==a.length)return!1;for(let n of i){let r=e[n],i=t[n];if(typeof r==`object`&&typeof i==`object`){if(!wn(r,i))return!1}else if(r!==i)return!1}return!0},Tn=(e,t)=>{if(typeof e!=`object`||!e)return e===t;let n=Object.keys(e),r=Object.keys(t);if(r.length>n.length)return!1;for(let n of r){let r=e[n],i=t[n];if(typeof r==`object`&&typeof i==`object`){if(!Tn(r,i))return!1}else if(r!==i)return!1}return!0},En=(e,...t)=>{if(t.length===0)return e;let n=t.shift();if(ue(e)&&ue(n))for(let t in n)try{ue(n[t])?(t in e||Object.assign(e,{[t]:{}}),En(e[t],n[t])):Object.assign(e,{[t]:n[t]})}catch(e){throw e instanceof TypeError?TypeError(`.${t}: ${e.message}`,{cause:e}):e}return En(e,...t)},Dn=l.z.string().regex(/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i),On=Cn,kn=l.z.number().min(0).max(1),An=l.z.tuple([On,On,On,kn]),jn=l.z.tuple([On,On,On]),Mn=l.z.object({rgba255:An}),Nn=l.z.object({r:On,g:On,b:On,a:kn}),Pn=l.z.number().min(0).max(360),Fn=l.z.number().min(0).max(100),In=l.z.number().min(0).max(100),Ln=l.z.tuple([Pn,Fn,In,kn]),Rn=l.z.union([Dn,jn,An,Ln,Mn,Nn]),zn=Rn.transform(e=>Bn(e)),Bn=(e,t=1)=>{if(e=Rn.parse(e),typeof e==`string`)return Vn(e,t);if(Array.isArray(e)){if(e.length<3||e.length>4)throw Error(`Invalid color: [${e.join(`, `)}]`);return e.length===3?[...e,t]:e}return`a`in e&&`r`in e?[e.r,e.g,e.b,e.a]:e.rgba255},Vn=(e,t=1)=>(e=Dn.parse(e),e=Un(e),[Hn(e,0),Hn(e,2),Hn(e,4),e.length===8?Hn(e,6)/255:t]),Hn=(e,t)=>parseInt(e.slice(t,t+2),16),Un=e=>e.startsWith(`#`)?e.slice(1):e;Bn(`#000000`),Bn(`#ffffff`);var Wn=l.z.object({key:l.z.string(),color:Rn,position:l.z.number(),switched:l.z.boolean().optional()});l.z.array(Wn);var Gn=l.z.object({key:l.z.string(),name:l.z.string(),color:zn});l.z.object({key:l.z.string(),name:l.z.string(),swatches:l.z.array(Gn)});var Kn=function(e){return e[e.exclusive=0]=`exclusive`,e[e.shared=1]=`shared`,e}({});l.z.enum(Kn),l.z.object({key:l.z.string(),name:l.z.string(),group:l.z.uint32().optional()});var qn=e=>Object.getOwnPropertySymbols(globalThis).includes(e),Jn=(e,t)=>{let n=Symbol.for(e);if(!qn(n)){let e=t();Object.defineProperty(globalThis,n,{value:e})}return()=>globalThis[n]},Yn=p({Canceled:()=>cr,NONE:()=>`nil`,NotImplemented:()=>lr,UNKNOWN:()=>er,Unknown:()=>or,createTyped:()=>Qn,decode:()=>ar,encode:()=>ir,isTyped:()=>$n,payloadZ:()=>sr,register:()=>rr}),Xn=`sy_x_error`,Zn=e=>t=>typeof t==`object`&&t&&`type`in t&&typeof t.type==`string`?t.type.startsWith(e):t instanceof Error?t.message.startsWith(e):typeof t==`string`?t.startsWith(e):!1,Qn=e=>class t extends Error{static discriminator=Xn;discriminator=t.discriminator;static TYPE=e;type=t.TYPE;static matches=Zn(e);matches=t.matches;constructor(e,n){super(e,n),this.name=t.TYPE}static sub(t){return Qn(`${e}.${t}`)}},$n=e=>{if(typeof e!=`object`||!e)return!1;let t=e;if(t.discriminator!==Xn)return!1;if(!(`type`in t))throw Error(`X Error is missing its type property: ${JSON.stringify(t)}`);return!0},er=`unknown`,tr=class{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:`nil`,data:``};if($n(e))for(let t of this.providers){let n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:er,data:e.message};if(typeof e==`string`)return{type:er,data:e};try{return{type:er,data:JSON.stringify(e)}}catch{return{type:er,data:`unable to encode error information`}}}decode(e){if(e==null||e.type===`nil`)return null;if(e.type===`unknown`)return new or(e.data);for(let t of this.providers){let n=t.decode(e);if(n!=null)return n}return new or(e.data)}},nr=Jn(`synnax-error-registry`,()=>new tr),rr=({encode:e,decode:t})=>nr().register({encode:e,decode:t}),ir=e=>nr().encode(e),ar=e=>e==null?null:nr().decode(e),or=class extends Qn(`unknown`){},sr=l.z.object({type:l.z.string(),data:l.z.string()}),cr=class extends Qn(`canceled`){},lr=class extends Qn(`not_implemented`){};l.z.string().regex(/^(?:$|(?:\/(?:[^~/]|~0|~1)*)+)$/,`must be a valid JSON pointer (RFC 6901)`),l.z.union([l.z.string(),l.z.number(),l.z.boolean(),l.z.null()]),l.z.enum([`string`,`number`,`boolean`,`null`]),l.z.object({key:l.z.string(),value:l.z.string()});var ur=l.z.uuid();l.z.object({key:ur,name:l.z.string().min(1),color:zn}).partial({key:!0}),l.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/),l.z.enum([`standard`,`scientific`,`engineering`]),l.z.union([l.z.string(),l.z.number()]),typeof process<`u`&&process.versions!=null&&process.versions.node!=null||typeof window>`u`||window.document;var dr=[`macOS`,`Windows`,`Linux`],fr=[`macos`,`windows`,`linux`],pr={macos:`macOS`,windows:`Windows`,linux:`Linux`};l.z.enum(dr).or(l.z.enum(fr).transform(e=>pr[e])),l.z.object({stack:l.z.string(),error:l.z.instanceof(Error)}),l.z.enum([`success`,`info`,`warning`,`error`,`loading`,`disabled`]),l.z.literal(`success`),l.z.literal(`info`),l.z.literal(`warning`),l.z.literal(`error`),l.z.literal(`loading`),l.z.literal(`disabled`);var mr=(...e)=>e.map(hr).join(``),hr=e=>(e.endsWith(`/`)||(e+=`/`),e.startsWith(`/`)&&(e=e.slice(1)),e),gr=e=>e.endsWith(`/`)?e.slice(0,-1):e,_r=(e,t=``)=>e===null?``:`?${Object.entries(e).filter(([,e])=>e==null?!1:Array.isArray(e)?e.length>0:!0).map(([e,n])=>`${t}${e}=${n}`).join(`&`)}`,vr=class e{protocol;host;port;path;constructor({host:e,port:t,protocol:n=``,pathPrefix:r=``}){this.protocol=n,this.host=e,this.port=t,this.path=hr(r)}replace(t){return new e({host:t.host??this.host,port:t.port??this.port,protocol:t.protocol??this.protocol,pathPrefix:t.pathPrefix??this.path})}child(t){return new e({...this,pathPrefix:mr(this.path,t)})}toString(){return gr(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new e({host:`unknown`,port:0})},yr=class extends Yn.createTyped(`freighter`){},br=class extends yr.sub(`eof`){constructor(){super(`EOF`)}},xr=class extends yr.sub(`stream_closed`){constructor(){super(`StreamClosed`)}},Sr=class extends yr.sub(`unreachable`){url;constructor(e={}){let{message:t=`Unreachable`,url:n=vr.UNKNOWN}=e;super(t),this.url=n}};Yn.register({encode:e=>{if(!e.type.startsWith(yr.TYPE))return null;if(br.matches(e))return{type:br.TYPE,data:`EOF`};if(xr.matches(e))return{type:xr.TYPE,data:`StreamClosed`};if(Sr.matches(e))return{type:Sr.TYPE,data:`Unreachable`};throw Error(`Unknown error type: ${e.type}: ${e.message}`)},decode:e=>{if(!e.type.startsWith(yr.TYPE))return null;switch(e.type){case br.TYPE:return new br;case xr.TYPE:return new xr;case Sr.TYPE:return new Sr;default:throw new Yn.Unknown(`Unknown error type: ${e.data}`)}}});var Cr=class{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0,r=async e=>{if(n===this.middleware.length)return await t(e);let i=this.middleware[n];return n++,await i(e,r)};return await r(e)}},wr=`Content-Type`,Tr=new Set([`ECONNREFUSED`,`ECONNRESET`,`ETIMEDOUT`,`EPIPE`,`UND_ERR_CONNECT_TIMEOUT`,`UND_ERR_SOCKET`]),Er=e=>{let t=e?.cause?.code??e?.code??e?.errno;if(typeof t==`string`&&Tr.has(t))return!0;if(e.name===`TypeError`){let t=String(e.message||``).toLowerCase();if(/load failed|failed to fetch|networkerror|network error/.test(t))return typeof navigator<`u`&&navigator.onLine,!0}return e?.name===`AbortError`||e?.code,!1},Dr=400,Or=class extends Cr{endpoint;encoder;constructor(e,t,n=!1){return super(),this.endpoint=e.replace({protocol:n?`https`:`http`}),this.encoder=t,new Proxy(this,{get:(e,t,n)=>t===`endpoint`?this.endpoint:Reflect.get(e,t,n)})}get headers(){return{[wr]:this.encoder.contentType}}async send(e,t,n,r){let i=null,a=this.endpoint.child(e),o={};o.method=`POST`,o.body=this.encoder.encode(t,n);let[,s]=await this.executeMiddleware({target:a.toString(),protocol:this.endpoint.protocol,params:{},role:`client`},async e=>{let t={...e,params:{}};o.headers={...this.headers,...e.params};let n;try{n=await fetch(e.target,o)}catch(e){if(!(e instanceof Error))throw e;return[t,Er(e)?new Sr({url:a}):e]}let s=await n.arrayBuffer();if(n?.ok)return r!=null&&(i=this.encoder.decode(s,r)),[t,null];try{if(n.status!==Dr)return[t,Error(n.statusText)];let e=this.encoder.decode(s,Yn.payloadZ);return[t,Yn.decode(e)]}catch(e){return[t,Error(`[freighter] - failed to decode error: ${n.statusText}: ${e.message}`)]}});if(s!=null)return[null,s];if(i==null)throw Error(`Response must be defined`);return[i,null]}},kr=(e,t)=>{class n{wrapped;constructor(e){this.wrapped=e}use(...e){this.wrapped.use(...e)}async send(e,n,r,i){let a=new bn.Breaker(t);do{let[t,o]=await this.wrapped.send(e,n,r,i);if(o==null)return[t,null];if(!Sr.matches(o))return[null,o];if(console.warn(`[freighter] ${a.retryMessage}`,o),!await a.wait())return[t,o]}while(!0)}}return new n(e)},S=async(e,t,n,r,i)=>{let[a,o]=await e.send(t,n,r,i);if(o!=null)throw o;return a},Ar=l.z.object({type:l.z.enum([`data`,`close`,`open`]),payload:l.z.unknown(),error:l.z.optional(Yn.payloadZ)}),jr=class{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,t,n,r){this.codec=t,this.reqSchema=n,this.resSchema=r,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){let e=await this.receiveMsg();if(e.type!==`open`){if(e.error==null)throw Error(`Message error must be defined`);return Yn.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new br;if(this.sendClosed)throw new xr;return this.ws.send(this.codec.encode({type:`data`,payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];let e=await this.receiveMsg();if(e.type===`close`){if(e.error==null||(this.serverClosed=Yn.decode(e.error),this.serverClosed==null))throw 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;let e={type:`close`};try{this.ws.send(this.codec.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((e,t)=>this.receiveCallbacksQueue.push({resolve:e,reject:t}))}addMessage(e){let t=this.receiveCallbacksQueue.shift();t==null?this.receiveDataQueue.push(e):t.resolve(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,Ar))}onClose(e){this.addMessage({type:`close`,error:{type:e.code===Nr?br.TYPE:xr.TYPE,data:``}})}},Mr=`freighterctx`,Nr=1e3,Pr=class e extends Cr{baseUrl;encoder;secure;static MESSAGE_TYPE=`arraybuffer`;constructor(e,t,n=!1){super(),this.secure=n,this.baseUrl=e.replace({protocol:n?`wss`:`ws`}),this.encoder=t}withCodec(t){let n=new e(this.baseUrl,t,this.secure);return n.use(...this.middleware),n}async stream(t,n,r){let i,[,a]=await this.executeMiddleware({target:t,protocol:`websocket`,params:{},role:`client`},async a=>{let o=new WebSocket(this.buildURL(t,a)),s={...a,params:{}};o.binaryType=e.MESSAGE_TYPE;let c=await this.wrapSocket(o,n,r);return c instanceof Error?[s,c]:(i=c,[s,null])});if(a!=null)throw a;return i}buildURL(e,t){let n=_r({[wr]:this.encoder.contentType,...t.params},Mr);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(r=>{e.onopen=()=>{let i=new jr(e,this.encoder,t,n);i.receiveOpenAck().then(e=>{r(e??i)}).catch(e=>r(e))},e.onerror=e=>{r(Error(e.message))}})}},Fr=Object.defineProperty,C=(e,t)=>{let n={};for(var r in e)Fr(n,r,{get:e[r],enumerable:!0});return t||Fr(n,Symbol.toStringTag,{value:`Module`}),n},Ir=e=>l.default.union([l.default.union([l.default.null(),l.default.undefined()]).transform(()=>[]),e.array()]),Lr=e=>Array.isArray(e)?e:e==null?[]:[e],Rr=(e,t)=>{if(Array.isArray(t))return t.reduce((e,t)=>Rr(e,t),e??[]);if(e==null)return[t];let n=e.findIndex(e=>e==t),r=[...e];return n===-1?r.push(t):r[n]=t,r},zr=((e,t)=>{if(e!=null)return Array.isArray(t)?e.filter(e=>!t.includes(e)):e.filter(e=>e!=t)}),Br=(e,t)=>{if(Array.isArray(t))return t.reduce((e,t)=>Br(e,t),e??[]);if(e==null)return[t];let n=e.findIndex(e=>e.key===t.key),r=[...e];return n===-1?r.push(t):r[n]=t,r},Vr=((e,t)=>{if(e!=null)return Array.isArray(t)?e.filter(e=>!t.includes(e.key)):e.filter(e=>e.key!==t)}),w=C({nullishToEmpty:()=>Ir,remove:()=>zr,removeKeyed:()=>Vr,toArray:()=>Lr,upsert:()=>Rr,upsertKeyed:()=>Br}),Hr=C({camelToSnake:()=>Zr,capitalize:()=>Qr,preserveCase:()=>Wr,snakeToCamel:()=>Xr,toKebab:()=>ni,toProperNoun:()=>ri}),Ur=`synnax.caseconv.preserveCase`,Wr=e=>(e[Ur]=!0,e),Gr=e=>{if(typeof e!=`object`||!e)return!1;if(Ur in e)return!0;let t=e._zod?.def;return t==null?!1:t.innerType&&Gr(t.innerType)?!0:t.type===`union`&&Array.isArray(t.options)?t.options.some(Gr):t.type===`pipe`?Gr(t.in)||Gr(t.out):!1},Kr=e=>{if(e==null)return;let t=e._zod?.def;if(t?.type===`array`&&t.element!=null)return t.element;if(t?.type===`union`&&Array.isArray(t.options))for(let e of t.options){let t=Kr(e);if(t!=null)return t}},qr=e=>{if(e==null)return null;let t=e;if(t.shape!=null)return t.shape;if(typeof t.sourceType==`function`){let e=t.sourceType();if(e?.shape!=null)return e.shape}let n=t._zod?.def;if(n==null)return null;if(n.innerType!=null)return qr(n.innerType);if(n.type===`union`&&Array.isArray(n.options))for(let e of n.options){let t=qr(e);if(t!=null)return t}return n.type===`pipe`?qr(n.in)??qr(n.out):null},Jr=e=>{if(e.length===0)return e;let t=e.indexOf(`_`)===-1?e:e.replace(/_[a-z]/g,e=>e[1].toUpperCase()),n=t.charCodeAt(0);return n<65||n>90||t.length>1&&t.charCodeAt(1)>=65&&t.charCodeAt(1)<=90?t:String.fromCharCode(n+32)+t.slice(1)},Yr=e=>{let t=(n,r=$r)=>{if(typeof n==`string`)return e(n);if(Array.isArray(n)){let e=Kr(r.schema),i={recursive:r.recursive,recursiveInArray:r.recursiveInArray,schema:e};return n.map(e=>t(e,i))}if(!ei(n)||r.schema!=null&&Gr(r.schema))return n;let i=r.recursive??!0,a=r.recursiveInArray??i,o=r.schema,s={},c=n;if(`toJSON`in c&&typeof c.toJSON==`function`)return t(c.toJSON(),r);let l=qr(o),u={recursive:i,recursiveInArray:a,schema:void 0},d=Object.keys(c);for(let n=0;n<d.length;n++){let r=d[n],o=c[r],f=e(r),p=l==null?void 0:l[r]??l[f]??void 0;i&&(ei(o)?ti(o)||(u.schema=p,o=t(o,u)):a&&Array.isArray(o)&&(u.schema=Kr(p),o=o.map(e=>{if(ei(e)){if(!ti(e))return t(e,u)}else if(Array.isArray(e))return t({key:e},u).key;return e}))),s[f]=o}return s};return t},Xr=Yr(Jr),Zr=Yr(e=>e.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`)),Qr=e=>e.length===0?e:e[0].toUpperCase()+e.slice(1),$r={recursive:!0,recursiveInArray:!0,schema:void 0},ei=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ti=e=>e instanceof Uint8Array||e instanceof Number||e instanceof String,ni=Yr(e=>e.replace(/[\s_]+/g,`-`).replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}-${n.toLowerCase()}`).toLowerCase()),ri=Yr(e=>{if(e.length===0)return e;let t=e.replace(/[_-]/g,` `);return t=t.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t} ${n}`),t=t.replace(/([A-Z]+)([A-Z][a-z])/g,(e,t,n)=>`${t} ${n}`),t=t.replace(/\s+/g,` `).trim(),t=t.replace(/\b\w/g,e=>e.toUpperCase()),t}),ii=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ai=C({CSVCodec:()=>si,CSV_CODEC:()=>ui,ENCODERS:()=>fi,JSONCodec:()=>oi,JSON_CODEC:()=>li,TEXT_CODEC:()=>di,TextCodec:()=>ci}),oi=class{contentType=`application/json`;decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e,t){return this.encoder.encode(this.encodeString(e,t))}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){let n=Xr(JSON.parse(e),{schema:t});return t==null?n:t.parse(n)}encodeString(e,t){let n=Zr((t==null?e:t.parse(e))??{},{schema:t});return JSON.stringify(n,(e,t)=>ArrayBuffer.isView(t)?Array.from(t):typeof t==`bigint`?t.toString():t)}},si=class{contentType=`text/csv`;encode(e){let t=this.encodeString(e);return new TextEncoder().encode(t)}decode(e,t){let n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!ii(e[0]))throw Error(`Payload must be an array of objects`);let t=Object.keys(e[0]),n=[t.join(`,`)];return e.forEach(e=>{let r=t.map(t=>JSON.stringify(e[t]??``));n.push(r.join(`,`))}),n.join(`
11
+ `).map(e=>e.trim());if(n.length===0)return t==null?{}:t.parse({});let i=n.split(`,`).map(e=>e.trim()),a={};return i.forEach(e=>{a[e]=[]}),r.forEach(e=>{let t=e.split(`,`).map(e=>e.trim());i.forEach((e,n)=>{let r=this.parseValue(t[n]);r!=null&&a[e].push(r)})}),t==null?a:t.parse(a)}parseValue(e){if(e==null||e.length===0)return null;let t=Number(e);return isNaN(t)?e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e:t}},Bt=class{contentType=`text/plain`;encode(e){if(typeof e!=`string`)throw Error(`TextCodec.encode payload must be a string`);return new TextEncoder().encode(e)}decode(e,t){let n=new TextDecoder().decode(e);return t==null?n:t.parse(n)}},Vt=new Rt;new zt,new Bt;var Ht=(e,t=!1)=>{let n=Ve(e)?`stringer`:typeof e,r;switch(n){case`string`:r=(e,t)=>e.localeCompare(t);break;case`stringer`:r=(e,t)=>e.toString().localeCompare(t.toString());break;case`number`:r=(e,t)=>Number(e)-Number(t);break;case`bigint`:r=(e,t)=>BigInt(e)-BigInt(t)>0n?1:-1;break;case`boolean`:r=(e,t)=>Number(e)-Number(t);break;case`undefined`:r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return t?Ut(r):r},Ut=e=>(t,n)=>e(n,t),Wt=(e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i--;)r+=e[Math.random()*e.length|0];return r},Gt=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,Kt=`0123456789${Gt}`,qt=Wt(Gt,1),Jt=Wt(Kt,10),Yt=()=>`${qt()}${Jt()}`,Xt=(e,t)=>n=>n instanceof t||typeof n==`object`&&!!n&&`discriminator`in n&&n.discriminator===e;l.z.object({x:Dt.or(At),y:Ot.or(At)});var Zt=l.z.object({x:Dt,y:Ot}),Qt=Object.freeze({x:`left`,y:`top`}),$t=Object.freeze({x:`right`,y:`top`}),en=Object.freeze({x:`left`,y:`bottom`}),tn=Object.freeze({x:`right`,y:`bottom`}),nn=Object.freeze({x:`center`,y:`center`}),rn=Object.freeze({x:`center`,y:`top`}),an=Object.freeze({x:`center`,y:`bottom`}),on=Object.freeze({x:`right`,y:`center`}),sn=Object.freeze({x:`left`,y:`center`});Object.freeze([sn,on,rn,an,Qt,$t,en,tn,nn]);var cn=(e,t)=>e.x===t.x&&e.y===t.y,ln=e=>[e.x,e.y];l.z.enum([`top`,`right`,`bottom`,`left`]);var un=l.z.object({x:l.z.number(),y:l.z.number()}),dn=l.z.union([l.z.number(),un,Ct,Mt,Nt,jt]),fn=(e,t)=>{if(typeof e==`string`){if(t===void 0)throw Error(`The y coordinate must be given.`);return e===`x`?{x:t,y:0}:{x:0,y:t}}return typeof e==`number`?{x:e,y:t??e}:Array.isArray(e)?{x:e[0],y:e[1]}:`signedWidth`in e?{x:e.signedWidth,y:e.signedHeight}:`clientX`in e?{x:e.clientX,y:e.clientY}:`width`in e?{x:e.width,y:e.height}:{x:e.x,y:e.y}},pn=Object.freeze({x:0,y:0});Object.freeze({x:1,y:1}),Object.freeze({x:1/0,y:1/0}),Object.freeze({x:NaN,y:NaN});var mn=(e,t)=>{let n=fn(e);return{x:n.x+t,y:n.y}},hn=(e,t)=>{let n=fn(e);return{x:n.x,y:n.y+t}},gn=(e,t,n,...r)=>{if(typeof t==`string`){if(typeof n!=`number`)throw Error(`The value must be a number.`);return t===`x`?mn(e,n):hn(e,n)}if(typeof t==`object`&&`x`in t&&typeof t.x==`string`){let r=fn(n),i=fn(e);return t.x===`left`?r.x=-r.x:t.x===`center`&&(r.x=0),t.y===`top`?r.y=-r.y:t.y===`center`&&(r.y=0),{x:i.x+r.x,y:i.y+r.y}}return[e,t,n??pn,...r].reduce((e,t)=>{let n=fn(t);return{x:e.x+n.x,y:e.y+n.y}},pn)},_n=l.z.union([l.z.number(),l.z.string()]);l.z.object({top:_n,left:_n,width:_n,height:_n}),l.z.object({left:l.z.number(),top:l.z.number(),right:l.z.number(),bottom:l.z.number()}),l.z.object({one:un,two:un,root:Zt});var vn=(e,t,n=0,r=0,i)=>{let a={one:{...pn},two:{...pn},root:i??Qt};if(typeof e==`number`){if(typeof t!=`number`)throw Error(`Box constructor called with invalid arguments`);return a.one={x:e,y:t},a.two={x:a.one.x+n,y:a.one.y+r},a}return`one`in e&&`two`in e&&`root`in e?{...e,root:i??e.root}:(`getBoundingClientRect`in e&&(e=e.getBoundingClientRect()),`left`in e?(a.one={x:e.left,y:e.top},a.two={x:e.right,y:e.bottom},a):(a.one=e,t==null?a.two={x:a.one.x+n,y:a.one.y+r}:typeof t==`number`?a.two={x:a.one.x+t,y:a.one.y+n}:`width`in t?a.two={x:a.one.x+t.width,y:a.one.y+t.height}:`signedWidth`in t?a.two={x:a.one.x+t.signedWidth,y:a.one.y+t.signedHeight}:a.two=t,a))},yn=(e,t)=>{let n=vn(e);return{x:t.x===`center`?wn(n).x:bn(n,t.x),y:t.y===`center`?wn(n).y:bn(n,t.y)}},bn=(e,t)=>{let n=vn(e),r=ln(n.root).includes(t)?Math.min:Math.max;return Et.includes(t)?r(n.one.x,n.two.x):r(n.one.y,n.two.y)},xn=e=>{let t=vn(e);return t.two.x-t.one.x},Sn=e=>{let t=vn(e);return t.two.y-t.one.y},Cn=e=>yn(e,Qt),wn=e=>gn(Cn(e),{x:xn(e)/2,y:Sn(e)/2}),Tn=e=>{let t=vn(e);return{lower:t.one.x,upper:t.two.x}},En=e=>{let t=vn(e);return{lower:t.one.y,upper:t.two.y}},Dn=e=>typeof e!=`object`||!e?!1:`one`in e&&`two`in e&&`root`in e;l.z.union([Mt,Nt,un,Ct]);var On=(e,t,n)=>t!==void 0&&e<t?t:n!==void 0&&e>n?n:e;l.z.object({offset:dn,scale:dn}),l.z.object({offset:l.z.number(),scale:l.z.number()});var kn=e=>(t,n,r,i)=>n===`dimension`?[t,r]:[t,i?r-e:r+e],An=e=>(t,n,r,i)=>[t,i?r/e:r*e],jn=e=>(t,n,r)=>{if(t===null)return[e,r];let{lower:i,upper:a}=t,{lower:o,upper:s}=e,c=a-i,l=s-o;return n===`dimension`?[e,l/c*r]:[e,(r-i)*(l/c)+o]},Mn=e=>(t,n,r)=>[e,r],Nn=()=>(e,t,n)=>{if(e===null)throw Error(`cannot invert without bounds`);if(t===`dimension`)return[e,n];let{lower:r,upper:i}=e;return[e,i-(n-r)]},Pn=e=>(t,n,r)=>{let{lower:i,upper:a}=e;return r=On(r,i,a),[t,r]},Fn=class e{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(t){return new e().translate(t)}static magnify(t){return new e().magnify(t)}static scale(t,n){return new e().scale(t,n)}translate(e){let t=this.new(),n=kn(e);return n.type=`translate`,t.ops.push(n),t}magnify(e){let t=this.new(),n=An(e);return n.type=`magnify`,t.ops.push(n),t}scale(e,t){let n=Pt(e,t),r=this.new(),i=jn(n);return i.type=`scale`,r.ops.push(i),r}clamp(e,t){let n=Pt(e,t),r=this.new(),i=Pn(n);return i.type=`clamp`,r.ops.push(i),r}reBound(e,t){let n=Pt(e,t),r=this.new(),i=Mn(n);return i.type=`re-bound`,r.ops.push(i),r}invert(){let e=Nn();e.type=`invert`;let t=this.new();return t.ops.push(e),t}pos(e){return this.exec(`position`,e)}dim(e){return this.exec(`dimension`,e)}new(){let t=new e;return t.ops=this.ops.slice(),t.reversed=this.reversed,t}exec(e,t){return this.currBounds=null,this.ops.reduce(([t,n],r)=>r(t,e,n,this.reversed),[null,t])[1]}reverse(){let e=this.new();e.ops.reverse();let t=[];return e.ops.forEach((n,r)=>{if(n.type===`scale`||t.some(([e,t])=>r>=e&&r<=t))return;let i=e.ops.findIndex((e,t)=>e.type===`scale`&&t>r);i!==-1&&t.push([r,i])}),t.forEach(([t,n])=>{let r=e.ops.slice(t,n);r.unshift(e.ops[n]),e.ops.splice(t,n-t+1,...r)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new e};(class e{x;y;currRoot;constructor(e=new Fn,t=new Fn,n=null){this.x=e,this.y=t,this.currRoot=n}static translate(t,n){return new e().translate(t,n)}static translateX(t){return new e().translateX(t)}static translateY(t){return new e().translateY(t)}static clamp(t){return new e().clamp(t)}static magnify(t){return new e().magnify(t)}static scale(t){return new e().scale(t)}static reBound(t){return new e().reBound(t)}translate(e,t){let n=fn(e,t),r=this.copy();return r.x=this.x.translate(n.x),r.y=this.y.translate(n.y),r}translateX(e){let t=this.copy();return t.x=this.x.translate(e),t}translateY(e){let t=this.copy();return t.y=this.y.translate(e),t}magnify(e){let t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){let t=this.copy();if(Dn(e)){let n=this.currRoot;return t.currRoot=e.root,n!=null&&!cn(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Tn(e)),t.y=t.y.scale(En(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){let t=this.copy();return t.x=this.x.reBound(Tn(e)),t.y=this.y.reBound(En(e)),t}clamp(e){let t=this.copy();return t.x=this.x.clamp(Tn(e)),t.y=this.y.clamp(En(e)),t}copy(){let t=new e;return t.currRoot=this.currRoot,t.x=this.x,t.y=this.y,t}reverse(){let 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 vn(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 e}),un.extend({root:Zt,units:l.default.object({x:l.default.enum([`px`,`decimal`]),y:l.default.enum([`px`,`decimal`])})}).partial({root:!0,units:!0});var In=l.z.enum([`static`,`dynamic`]),Ln=365,Rn=30,zn=l.z.union([l.z.tuple([l.z.int()]),l.z.tuple([l.z.int(),l.z.int().min(1).max(12)]),l.z.tuple([l.z.int(),l.z.int().min(1).max(12),l.z.int().min(1).max(31)])]),Bn=(e,t)=>{let n=new _(t);if(![v.DAY,v.HOUR,v.MINUTE,v.SECOND,v.MILLISECOND,v.MICROSECOND,v.NANOSECOND].some(e=>e.equals(n)))throw Error(`Invalid argument for remainder. Must be an even TimeSpan or Timestamp`);let r=e.valueOf()%n.valueOf();return e instanceof _?new _(r):new v(r)},_=class e extends Be{constructor(t,n=`UTC`){if(t==null)super(e.now().valueOf());else if(t instanceof Date)super(BigInt(t.getTime())*e.MILLISECOND.valueOf());else if(typeof t==`string`)super(e.parseDateTimeString(t,n).valueOf());else if(Array.isArray(t))super(e.parseDate(t));else{let r=0n;t instanceof Number&&(t=t.valueOf()),n===`local`&&(r=e.utcOffset.valueOf()),typeof t==`number`&&(isFinite(t)?t=t===gt?mt:Math.trunc(t):(isNaN(t)&&(t=0),t=t===1/0?e.MAX:e.MIN)),ze(t)&&(t=t.value),super(BigInt(t.valueOf())+r)}}static parseDate([t=1970,n=1,r=1]){let i=new Date(t,n-1,r,0,0,0,0);return new e(BigInt(i.getTime())*e.MILLISECOND.valueOf()).truncate(e.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(t,n=`UTC`){let[r,i,a]=t.split(`:`),o=`00`,s=`00`;a!=null&&([o,s]=a.split(`.`));let c=e.hours(parseInt(r??`00`,10)).add(e.minutes(parseInt(i??`00`,10))).add(e.seconds(parseInt(o??`00`,10))).add(e.milliseconds(parseInt(s??`00`,10)));return n===`local`&&(c=c.add(e.utcOffset)),c.valueOf()}static parseDateTimeString(t,n=`UTC`){if(!t.includes(`/`)&&!t.includes(`-`))return e.parseTimeString(t,n);if(t.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let r=t,i=0;if(t.includes(`.`)){let e=t.split(`.`);r=e[0];let n=e[1]||`0`;i=parseInt(n.padEnd(3,`0`).slice(0,3),10)}let a=n===`local`?new Date(r.replace(`T`,` `)):new Date(`${r}Z`);return BigInt(a.getTime())*e.MILLISECOND.valueOf()+BigInt(i)*e.MILLISECOND.valueOf()}let r=new Date(t);return t.includes(`:`)||r.setUTCHours(0,0,0,0),new e(BigInt(r.getTime())*e.MILLISECOND.valueOf(),n).valueOf()}toISOString(t=`UTC`){if(t===`UTC`)return this.date().toISOString();let n=this.date(),r=new v(BigInt(n.getTimezoneOffset())*e.MINUTE.valueOf());return this.sub(r).date().toISOString()}timeString(e=!1,t=`UTC`){let n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){let e=this.date();return`${e.toLocaleString(`default`,{month:`short`})} ${e.toLocaleString(`default`,{day:`numeric`})}`}static get utcOffset(){return new v(BigInt(new Date().getTimezoneOffset())*e.MINUTE.valueOf())}static since(t){return new e().span(t)}date(){return new Date(this.milliseconds)}equals(t){return this.valueOf()===new e(t).valueOf()}span(e){return this.range(e).span}range(e){return new Hn(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(t){return this.valueOf()>new e(t).valueOf()}afterEq(t){return this.valueOf()>=new e(t).valueOf()}before(t){return this.valueOf()<new e(t).valueOf()}beforeEq(t){return this.valueOf()<=new e(t).valueOf()}add(t){return new e(yt(this.valueOf(),new v(t).valueOf()))}sub(t){return new e(vt(this.valueOf(),new v(t).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(e.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(e.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}get localYear(){return this.date().getFullYear()}setYear(t){let n=this.date();return n.setUTCFullYear(t),new e(n)}setLocalYear(t){let n=this.date();return n.setFullYear(t),new e(n)}get month(){return this.date().getUTCMonth()}get localMonth(){return this.date().getMonth()}setMonth(t){let n=this.date();return n.setUTCMonth(t),new e(n)}setLocalMonth(t){let n=this.date();return n.setMonth(t),new e(n)}get day(){return this.date().getUTCDate()}get localDay(){return this.date().getDate()}setDay(t){let n=this.date();return n.setUTCDate(t),new e(n)}setLocalDay(t){let n=this.date();return n.setDate(t),new e(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(t){let n=this.date();return n.setHours(t),new e(n)}setHour(t){let n=this.date();return n.setUTCHours(t),new e(n)}get minute(){return this.date().getUTCMinutes()}get localMinute(){return this.date().getMinutes()}setMinute(t){let n=this.date();return n.setUTCMinutes(t),new e(n)}setLocalMinute(t){let n=this.date();return n.setMinutes(t),new e(n)}get second(){return this.date().getUTCSeconds()}get localSecond(){return this.date().getSeconds()}setSecond(t){let n=this.date();return n.setUTCSeconds(t),new e(n)}setLocalSecond(t){let n=this.date();return n.setSeconds(t),new e(n)}get millisecond(){return this.date().getUTCMilliseconds()}get localMillisecond(){return this.date().getMilliseconds()}setMillisecond(t){let n=this.date();return n.setUTCMilliseconds(t),new e(n)}setLocalMillisecond(t){let n=this.date();return n.setMilliseconds(t),new e(n)}toString(e=`ISO`,t=`UTC`){switch(e){case`ISODate`:return this.toISOString(t).slice(0,10);case`ISOTime`:return this.toISOString(t).slice(11,23);case`time`:return this.timeString(!1,t);case`preciseTime`:return this.timeString(!0,t);case`date`:return this.dateString();case`preciseDate`:return`${this.dateString()} ${this.timeString(!0,t)}`;case`dateTime`:return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}remainder(e){return Bn(this,e)}get isToday(){return this.truncate(v.DAY).equals(e.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 e(new Date)}static max(...t){let n=e.MIN;for(let r of t){let t=new e(r);t.after(n)&&(n=t)}return n}static min(...t){let n=e.MAX;for(let r of t){let t=new e(r);t.before(n)&&(n=t)}return n}static nanoseconds(t,n=`UTC`){return new e(t,n)}static NANOSECOND=e.nanoseconds(1);static microseconds(t,n=`UTC`){return e.nanoseconds(t*1e3,n)}static MICROSECOND=e.microseconds(1);static milliseconds(t,n=`UTC`){return e.microseconds(t*1e3,n)}static MILLISECOND=e.milliseconds(1);static seconds(t,n=`UTC`){return e.milliseconds(t*1e3,n)}static SECOND=e.seconds(1);static minutes(t,n=`UTC`){return e.seconds(t*60,n)}static MINUTE=e.minutes(1);static hours(t,n=`UTC`){return e.minutes(t*60,n)}static HOUR=e.hours(1);static days(t,n=`UTC`){return e.hours(t*24,n)}static DAY=e.days(1);static MAX=new e(mt);static MIN=new e(0);static ZERO=new e(0);static z=l.z.union([l.z.instanceof(e),l.z.object({value:l.z.bigint()}).transform(t=>new e(t.value)),l.z.string().transform(t=>new e(BigInt(t))),l.z.number().transform(t=>new e(t)),l.z.bigint().transform(t=>new e(t)),l.z.date().transform(t=>new e(t)),l.z.custom(e=>e instanceof v).transform(t=>new e(t)),zn.transform(t=>new e(t))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}},v=class e extends Be{constructor(e){typeof e==`number`&&(e=Math.trunc(e.valueOf())),ze(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(t){return t instanceof e?t:t instanceof Vn?t.period:t instanceof _?new e(t):(ze(t)&&(t=t.value),[`number`,`bigint`].includes(typeof t)?e.seconds(t):new e(t))}static fromMilliseconds(t){return t instanceof e?t:t instanceof Vn?t.period:t instanceof _?new e(t):(ze(t)&&(t=t.value),[`number`,`bigint`].includes(typeof t)?e.milliseconds(t):new e(t))}valueOf(){return this.value}lessThan(t){return this.valueOf()<new e(t).valueOf()}greaterThan(t){return this.valueOf()>new e(t).valueOf()}lessThanOrEqual(t){return this.valueOf()<=new e(t).valueOf()}greaterThanOrEqual(t){return this.valueOf()>=new e(t).valueOf()}remainder(e){return Bn(this,e)}truncate(t){return new e(BigInt(Math.trunc(Number(this.valueOf()/t.valueOf())))*t.valueOf())}toString(t=`full`){if(t===`semantic`)return this.toSemanticString();let n=this.truncate(e.DAY),r=this.truncate(e.HOUR),i=this.truncate(e.MINUTE),a=this.truncate(e.SECOND),o=this.truncate(e.MILLISECOND),s=this.truncate(e.MICROSECOND),c=this.truncate(e.NANOSECOND),l=n,u=r.sub(n),d=i.sub(r),f=a.sub(i),p=o.sub(a),m=s.sub(o),h=c.sub(s),g=``;return l.isZero||(g+=`${l.days}d `),u.isZero||(g+=`${u.hours}h `),d.isZero||(g+=`${d.minutes}m `),f.isZero||(g+=`${f.seconds}s `),p.isZero||(g+=`${p.milliseconds}ms `),m.isZero||(g+=`${m.microseconds}µs `),h.isZero||(g+=`${h.nanoseconds}ns`),g.trim()}toSemanticString(){let t=new e(this.valueOf()<0n?-this.valueOf():this.valueOf()),n=this.valueOf()<0n;if(t.valueOf()===0n)return`0s`;if(t.lessThan(e.SECOND))return`< 1s`;let r=t.days,i=t.hours,a=t.minutes,o=t.seconds,s=Math.floor(r/Ln),c=Math.floor(r/Rn),l=Math.floor(r/7),u=Math.floor(r),d=Math.floor(i),f=Math.floor(a),p=Math.floor(o),m=n?`-`:``;if(s>=1){let e=`${s}y`;if(s<2){let t=Math.floor(r%Ln/Rn);t>0&&(e+=` ${t}mo`)}return m+e}if(l>=1&&r<Rn&&r%7==0){let e=`${l}w`,t=Math.floor(r%7),n=Math.floor(i-l*7*24);return l<2&&(t>0?e+=` ${t}d`:n>0&&n<24&&(e+=` ${n}h`)),m+e}if(c>=1){let e=`${c}mo`;if(c<3){let t=Math.floor(r%Rn);t>0&&(e+=` ${t}d`)}return m+e}if(l>=1){let e=`${l}w`,t=Math.floor(r%7),n=Math.floor(i-l*7*24);return l<2&&(t>0?e+=` ${t}d`:n>0&&n<24&&(e+=` ${n}h`)),m+e}if(u>=1){let e=`${u}d`,t=Math.floor(i-u*24);return u<2&&t>0&&(e+=` ${t}h`),m+e}if(d>=1){let e=`${d}h`;if(d<3){let t=Math.floor(a-d*60);t>0&&(e+=` ${t}m`)}return m+e}if(f>=1){let e=`${f}m`;if(f<5){let t=Math.floor(o-f*60);t>0&&(e+=` ${t}s`)}return m+e}return`${m}${p}s`}mult(t){return new e(xt(this.valueOf(),t))}div(t){return new e(St(this.valueOf(),t))}get days(){return Number(this.valueOf())/Number(e.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(e.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(e.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(e.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(e.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(e.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(t){return this.valueOf()===new e(t).valueOf()}add(t){return new e(this.valueOf()+new e(t).valueOf())}sub(t){return new e(this.valueOf()-new e(t).valueOf())}static nanoseconds(t=1){return new e(t)}static NANOSECOND=e.nanoseconds(1);static microseconds(t=1){return e.nanoseconds(xt(t,1e3))}static MICROSECOND=e.microseconds(1);static milliseconds(t=1){return e.microseconds(xt(t,1e3))}static MILLISECOND=e.milliseconds(1);static seconds(t=1){return e.milliseconds(xt(t,1e3))}static SECOND=e.seconds(1);static minutes(t=1){return e.seconds(xt(t,60))}static MINUTE=e.minutes(1);static hours(t){return e.minutes(xt(t,60))}static HOUR=e.hours(1);static days(t){return e.hours(xt(t,24))}static DAY=e.days(1);static MAX=new e(mt);static MIN=new e(0);static ZERO=new e(0);static z=l.z.union([l.z.object({value:l.z.bigint()}).transform(t=>new e(t.value)),l.z.string().transform(t=>new e(BigInt(t))),l.z.number().transform(t=>new e(t)),l.z.bigint().transform(t=>new e(t)),l.z.instanceof(e),l.z.instanceof(_).transform(t=>new e(t)),l.z.custom(e=>e instanceof Vn).transform(t=>new e(t))])},Vn=class e extends Be{constructor(e){ze(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(t){return this.valueOf()===new e(t).valueOf()}get period(){return v.seconds(1/this.valueOf())}sampleCount(e){return new v(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new y(t).valueOf()}span(e){return v.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/new y(t).valueOf())}add(t){return new e(yt(this.valueOf(),new e(t).valueOf()))}sub(t){return new e(vt(this.valueOf(),new e(t).valueOf()))}mult(t){return new e(xt(this.valueOf(),t))}div(t){return new e(St(this.valueOf(),t))}static hz(t){return new e(t)}static khz(t){return e.hz(t*1e3)}static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)])},y=class e extends Be{constructor(e){ze(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new Un(e*this.valueOf())}add(t){return new e(yt(this.valueOf(),new e(t).valueOf()))}sub(t){return new e(vt(this.valueOf(),new e(t).valueOf()))}mult(t){return new e(xt(this.valueOf(),t))}div(t){return new e(St(this.valueOf(),t))}static UNKNOWN=new e(0);static BIT128=new e(16);static BIT64=new e(8);static BIT32=new e(4);static BIT16=new e(2);static BIT8=new e(1);static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)])},Hn=class e{start;end;constructor(e,t){typeof e==`object`&&`start`in e?(this.start=new _(e.start),this.end=new _(e.end)):(this.start=new _(e),this.end=new _(t))}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 e(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=v.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),r=this.end.sub(e.end).valueOf();return n<0&&(n=-n),r<0&&(r=-r),n<=t.valueOf()&&r<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString(`preciseDate`)} - ${this.span.toString()}`}overlapsWith(e,t=v.ZERO){e=e.makeValid();let n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;let r=_.max(n.start,e.start),i=_.min(n.end,e.end);return i.before(r)?!1:new v(i.sub(r)).greaterThanOrEqual(t)}contains(t){return t instanceof e?this.contains(t.start)&&this.contains(t.end):this.start.beforeEq(t)&&this.end.after(t)}boundBy(t){let n=new e(this.start,this.end);return t.start.after(this.start)&&(n.start=t.start),t.start.after(this.end)&&(n.end=t.start),t.end.before(this.end)&&(n.end=t.end),t.end.before(this.start)&&(n.start=t.end),n}static max(...t){return new e(_.min(...t.map(e=>e.start)),_.max(...t.map(e=>e.end)))}static MAX=new e(_.MIN,_.MAX);static ZERO=new e(_.ZERO,_.ZERO);static z=l.z.union([l.z.object({start:_.z,end:_.z}).transform(t=>new e(t.start,t.end)),l.z.instanceof(e)]);static boundedZ=e.z.refine(({isValid:e})=>e,{message:`Time range start time must be before or equal to time range end time`}).refine(({end:e})=>e.valueOf()<=mt,{message:`Time range end time must be less than or equal to the maximum value of an int64`}).refine(({start:e})=>e.valueOf()>=pt,{message:`Time range start time must be greater than or equal to the minimum value of an int64`});static sort(e,t){return _.sort(e.start,t.start)||_.sort(e.end,t.end)}static merge(...t){return e.max(...t.map(t=>new e(t).makeValid()))}},b=class e extends Be{constructor(t){if(ze(t)&&(t=t.value),t instanceof e||typeof t==`string`||typeof t.valueOf()==`string`)super(t.valueOf());else{let n=e.ARRAY_CONSTRUCTOR_DATA_TYPES.get(t.constructor.name);if(n==null)throw Error(`unable to find data type for ${t.toString()}`);super(n.valueOf())}}get Array(){let t=e.ARRAY_CONSTRUCTORS.get(this.toString());if(t==null)throw Error(`unable to find array constructor for ${this.valueOf()}`);return t}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(e=>this.equals(e))}toString(t=!1){return t?e.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(e.JSON)||this.equals(e.STRING)||this.equals(e.BYTES)}get isNumeric(){return!this.isVariable&&!this.equals(e.UUID)}get isInteger(){let e=this.toString();return e.startsWith(`int`)||e.startsWith(`uint`)}get isFloat(){return this.toString().startsWith(`float`)}get density(){let t=e.DENSITIES.get(this.toString());if(t==null)throw Error(`unable to find density for ${this.valueOf()}`);return t}get isUnsignedInteger(){return this.equals(e.UINT8)||this.equals(e.UINT16)||this.equals(e.UINT32)||this.equals(e.UINT64)}get isSignedInteger(){return this.equals(e.INT8)||this.equals(e.INT16)||this.equals(e.INT32)||this.equals(e.INT64)}canSafelyCastTo(t){return this.equals(t)?!0:!this.isNumeric||!t.isNumeric||this.isVariable||t.isVariable||this.isUnsignedInteger&&t.isSignedInteger?!1:this.isFloat?t.isFloat&&this.density.valueOf()<=t.density.valueOf():this.equals(e.INT32)&&t.equals(e.FLOAT64)||this.equals(e.INT8)&&t.equals(e.FLOAT32)?!0:this.isInteger&&t.isInteger?this.density.valueOf()<=t.density.valueOf()&&this.isUnsignedInteger===t.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return e.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new e(`unknown`);static FLOAT64=new e(`float64`);static FLOAT32=new e(`float32`);static INT64=new e(`int64`);static INT32=new e(`int32`);static INT16=new e(`int16`);static INT8=new e(`int8`);static UINT64=new e(`uint64`);static UINT32=new e(`uint32`);static UINT16=new e(`uint16`);static UINT8=new e(`uint8`);static TIMESTAMP=new e(`timestamp`);static UUID=new e(`uuid`);static STRING=new e(`string`);static JSON=new e(`json`);static BYTES=new e(`bytes`);static ARRAY_CONSTRUCTORS=new Map([[e.UINT8.toString(),Uint8Array],[e.UINT16.toString(),Uint16Array],[e.UINT32.toString(),Uint32Array],[e.UINT64.toString(),BigUint64Array],[e.FLOAT32.toString(),Float32Array],[e.FLOAT64.toString(),Float64Array],[e.INT8.toString(),Int8Array],[e.INT16.toString(),Int16Array],[e.INT32.toString(),Int32Array],[e.INT64.toString(),BigInt64Array],[e.TIMESTAMP.toString(),BigInt64Array],[e.STRING.toString(),Uint8Array],[e.JSON.toString(),Uint8Array],[e.UUID.toString(),Uint8Array],[e.BYTES.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,e.UINT8],[Uint16Array.name,e.UINT16],[Uint32Array.name,e.UINT32],[BigUint64Array.name,e.UINT64],[Float32Array.name,e.FLOAT32],[Float64Array.name,e.FLOAT64],[Int8Array.name,e.INT8],[Int16Array.name,e.INT16],[Int32Array.name,e.INT32],[BigInt64Array.name,e.INT64]]);static DENSITIES=new Map([[e.UINT8.toString(),y.BIT8],[e.UINT16.toString(),y.BIT16],[e.UINT32.toString(),y.BIT32],[e.UINT64.toString(),y.BIT64],[e.FLOAT32.toString(),y.BIT32],[e.FLOAT64.toString(),y.BIT64],[e.INT8.toString(),y.BIT8],[e.INT16.toString(),y.BIT16],[e.INT32.toString(),y.BIT32],[e.INT64.toString(),y.BIT64],[e.TIMESTAMP.toString(),y.BIT64],[e.STRING.toString(),y.UNKNOWN],[e.JSON.toString(),y.UNKNOWN],[e.UUID.toString(),y.BIT128],[e.BYTES.toString(),y.UNKNOWN]]);static ALL=[e.UNKNOWN,e.UINT8,e.UINT16,e.UINT32,e.UINT64,e.INT8,e.INT16,e.INT32,e.INT64,e.FLOAT32,e.FLOAT64,e.TIMESTAMP,e.UUID,e.STRING,e.JSON,e.BYTES];static SHORT_STRINGS=new Map([[e.UINT8.toString(),`u8`],[e.UINT16.toString(),`u16`],[e.UINT32.toString(),`u32`],[e.UINT64.toString(),`u64`],[e.INT8.toString(),`i8`],[e.INT16.toString(),`i16`],[e.INT32.toString(),`i32`],[e.INT64.toString(),`i64`],[e.FLOAT32.toString(),`f32`],[e.FLOAT64.toString(),`f64`],[e.TIMESTAMP.toString(),`ts`],[e.UUID.toString(),`uuid`],[e.STRING.toString(),`str`],[e.JSON.toString(),`json`],[e.BYTES.toString(),`bytes`]]);static BIG_INT_TYPES=[e.INT64,e.UINT64,e.TIMESTAMP];static z=l.z.union([l.z.string().transform(t=>new e(t)),l.z.instanceof(e)])},Un=class e extends Be{constructor(e){ze(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return ze(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return ze(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(t){return ze(t)&&(t=t.value),new e(yt(this.valueOf(),t.valueOf()))}sub(t){return ze(t)&&(t=t.value),new e(vt(this.valueOf(),t.valueOf()))}mult(t){return new e(xt(this.valueOf(),t))}div(t){return new e(St(this.valueOf(),t))}truncate(t){return new e(Math.trunc(this.valueOf()/new e(t).valueOf())*new e(t).valueOf())}remainder(t){return e.bytes(this.valueOf()%new e(t).valueOf())}get gigabytes(){return this.valueOf()/e.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/e.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/e.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/e.TERABYTE.valueOf()}toString(){let t=this.truncate(e.TERABYTE),n=this.truncate(e.GIGABYTE),r=this.truncate(e.MEGABYTE),i=this.truncate(e.KILOBYTE),a=this.truncate(e.BYTE),o=t,s=n.sub(t),c=r.sub(n),l=i.sub(r),u=a.sub(i),d=``;return o.isZero||(d+=`${o.terabytes}TB `),s.isZero||(d+=`${s.gigabytes}GB `),c.isZero||(d+=`${c.megabytes}MB `),l.isZero||(d+=`${l.kilobytes}KB `),(!u.isZero||d===``)&&(d+=`${u.valueOf()}B`),d.trim()}static bytes(t=1){return new e(t)}static BYTE=new e(1);static kilobytes(t=1){return e.bytes(new e(t).valueOf()*1e3)}static KILOBYTE=e.kilobytes(1);static megabytes(t=1){return e.kilobytes(new e(t).valueOf()*1e3)}static MEGABYTE=e.megabytes(1);static gigabytes(t=1){return e.megabytes(new e(t).valueOf()*1e3)}static GIGABYTE=e.gigabytes(1);static terabytes(t){return e.gigabytes(new e(t).valueOf()*1e3)}static TERABYTE=e.terabytes(1);static ZERO=new e(0);static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)]);get isZero(){return this.valueOf()===0}};l.z.object({start:l.z.number(),end:l.z.number()}),l.z.union([l.z.instanceof(Uint8Array),l.z.instanceof(Uint16Array),l.z.instanceof(Uint32Array),l.z.instanceof(BigUint64Array),l.z.instanceof(Float32Array),l.z.instanceof(Float64Array),l.z.instanceof(Int8Array),l.z.instanceof(Int16Array),l.z.instanceof(Int32Array),l.z.instanceof(BigInt64Array)]);var Wn=e=>{let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===`bigint`||e instanceof _||e instanceof v||e instanceof Date},Gn=(e,t,n,r=0)=>e.usesBigInt&&!t.usesBigInt?Number(n)-Number(r):!e.usesBigInt&&t.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):vt(n,r);Hn.z,_.z,v.z,Vn.z,Un.z,b.z,Hn.boundedZ;var Kn=/^(?:[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 qn(e){return typeof e==`string`&&Kn.test(e)}var x=[];for(let e=0;e<256;++e)x.push((e+256).toString(16).slice(1));function Jn(e,t=0){return(x[e[t+0]]+x[e[t+1]]+x[e[t+2]]+x[e[t+3]]+`-`+x[e[t+4]]+x[e[t+5]]+`-`+x[e[t+6]]+x[e[t+7]]+`-`+x[e[t+8]]+x[e[t+9]]+`-`+x[e[t+10]]+x[e[t+11]]+x[e[t+12]]+x[e[t+13]]+x[e[t+14]]+x[e[t+15]]).toLowerCase()}function Yn(e,t=0){let n=Jn(e,t);if(!qn(n))throw TypeError(`Stringified UUID is invalid`);return n}typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var Xn=(e,t)=>Yn(e,t),Zn=-1,Qn={[Symbol.iterator]:()=>Qn,next:()=>({done:!0,value:void 0})},$n=l.z.string().transform(e=>new Uint8Array(atob(e).split(``).map(e=>e.charCodeAt(0))).buffer),er=l.z.union([l.z.null(),l.z.undefined()]).transform(()=>new Uint8Array().buffer),tr=10,nr=(e,t)=>{if(e===`number`&&!t.isNumeric)throw Error(`cannot convert series of type ${t.toString()} to number`);if(e===`bigint`&&!t.usesBigInt)throw Error(`cannot convert series of type ${t.toString()} to bigint`)},rr=`sy_x_telem_series`,ir=class e{key;discriminator=rr;dataType;sampleOffset;gl;_data;timeRange=Hn.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Zn;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=l.z.object({timeRange:Hn.z.optional(),dataType:b.z,alignment:l.z.coerce.bigint().optional(),data:l.z.union([$n,er,l.z.instanceof(ArrayBuffer),l.z.instanceof(Uint8Array)]),glBufferUsage:In.default(`static`).optional()});static z=e.crudeZ.transform(t=>new e(t));constructor(e){ar(e)&&(e={data:e}),e.data??=[];let{dataType:t,timeRange:n,sampleOffset:r=0,glBufferUsage:i=`static`,alignment:a=0n,alignmentMultiple:o=1n,key:s=Yt(),data:c}=e;if(or(c)){let e=c;this.key=e.key,this.dataType=e.dataType,this.sampleOffset=e.sampleOffset,this.gl=e.gl,this._data=e._data,this.timeRange=e.timeRange,this.alignment=e.alignment,this.alignmentMultiple=e.alignmentMultiple,this.cachedMin=e.cachedMin,this.cachedMax=e.cachedMax,this.writePos=e.writePos,this._refCount=e._refCount,this.cachedLength=e.cachedLength;return}let l=Wn(c),u=Array.isArray(c);if(t!=null)this.dataType=new b(t);else if(c instanceof ArrayBuffer)throw Error(`cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.`);else if(u||l){let e=c;if(!l){if(c.length===0)throw Error(`cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.`);e=c[0]}if(typeof e==`string`)this.dataType=b.STRING;else if(typeof e==`number`)this.dataType=b.FLOAT64;else if(typeof e==`bigint`)this.dataType=b.INT64;else if(typeof e==`boolean`)this.dataType=b.UINT8;else if(e instanceof _||e instanceof Date||e instanceof _)this.dataType=b.TIMESTAMP;else if(typeof e==`object`)this.dataType=b.JSON;else throw Error(`cannot infer data type of ${typeof e} when constructing a Series from a JS array`)}else this.dataType=new b(c);if(!u&&!l)this._data=c;else if(u&&c.length===0)this._data=new this.dataType.Array([]).buffer;else{let e=l?[c]:c,t=e[0];(t instanceof _||t instanceof Date||t instanceof v)&&(e=e.map(e=>new _(e).valueOf())),this.dataType.equals(b.STRING)?(this.cachedLength=e.length,this._data=new TextEncoder().encode(`${e.join(`
12
+ `)}\n`).buffer):this.dataType.equals(b.JSON)?(this.cachedLength=e.length,this._data=new TextEncoder().encode(`${e.map(e=>Vt.encodeString(e)).join(`
13
+ `)}\n`).buffer):this.dataType.usesBigInt&&typeof t==`number`?this._data=new this.dataType.Array(e.map(e=>BigInt(Math.round(e)))).buffer:!this.dataType.usesBigInt&&typeof t==`bigint`?this._data=new this.dataType.Array(e.map(Number)).buffer:this._data=new this.dataType.Array(e).buffer}this.key=s,this.alignment=a,this.alignmentMultiple=o,this.sampleOffset=r??0,this.timeRange=n??Hn.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:t,dataType:n,...r}){if(t===0)throw Error(`[Series] - cannot allocate an array of length 0`);let i=new e({data:new new b(n).Array(t).buffer,dataType:n,...r});return i.writePos=0,i}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 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===Zn)return 0;let t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===Zn)return 0;let t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this.cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.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===Zn?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
14
+ `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(b.JSON))throw Error(`cannot parse non-JSON series as JSON`);return this.toStrings().map(t=>e.parse(Vt.decodeString(t)))}get byteCapacity(){return new Un(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Zn?this.byteCapacity:this.dataType.isVariable?new Un(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength==null?this.dataType.isVariable?this.calculateCachedLength():this.writePos===Zn?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos:this.cachedLength}calculateCachedLength(){if(!this.dataType.isVariable)throw Error(`cannot calculate length of a non-variable length data type`);let e=0,t=[0];return this.data.forEach((n,r)=>{n===tr&&(e++,t.push(r+1))}),this._cachedIndexes=t,this.cachedLength=e,e}convert(t,n=0){if(this.dataType.equals(t))return this;let r=new t.Array(this.length);for(let e=0;e<this.length;e++)r[e]=Gn(this.dataType,t,this.data[e],n);return new e({data:r.buffer,dataType:t,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){return this.length===0?-1/0:(this.dataType.equals(b.TIMESTAMP)?this.cachedMax=this.data[this.data.length-1]:(this.dataType.usesBigInt,this.cachedMax=this.data.reduce((e,t)=>e>t?e:t)),this.cachedMax)}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw Error(`cannot calculate maximum on a variable length data type`);return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),yt(this.cachedMax,this.sampleOffset))}calcRawMin(){return this.length===0?1/0:(this.dataType.equals(b.TIMESTAMP)?this.cachedMin=this.data[0]:(this.dataType.usesBigInt,this.cachedMin=this.data.reduce((e,t)=>e<t?e:t)),this.cachedMin)}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw Error(`cannot calculate minimum on a variable length data type`);return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),yt(this.cachedMin,this.sampleOffset))}get bounds(){return Pt(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){let t=e.cachedMin??e.calcRawMin();t<this.cachedMin&&(this.cachedMin=t)}if(this.cachedMax!=null){let t=e.cachedMax??e.calcRawMax();t>this.cachedMax&&(this.cachedMax=t)}}atAlignment(e,t){let n=Number((e-this.alignment)/this.alignmentMultiple);if(n<0||n>=this.length){if(t===!0)throw Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(b.UUID))return this.atUUID(e,t);e<0&&(e=this.length+e);let n=this.data[e];if(n==null){if(t===!0)throw Error(`[series] - no value at index ${e}`);return}return yt(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);let n=Xn(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){let n=0,r=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],r=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let t=0;t<this.data.length;t++)if(this.data[t]===tr){if(e===0){r=t;break}n=t+1,e--}if(r===0&&(r=this.data.length),n>=r||e>0){if(t)throw Error(`[series] - no value at index ${e}`);return}}let i=this.data.slice(n,r);return this.dataType.equals(b.STRING)?new TextDecoder().decode(i):ae(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let t=0,n=this.length-1,r=Ht(e);for(;t<=n;){let i=Math.floor((t+n)/2),a=r(this.at(i,!0),e);if(a===0)return i;a<0?t=i+1:n=i-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(b.FLOAT32)&&!this.dataType.equals(b.UINT8))throw Error(`Only FLOAT32 and UINT8 arrays can be used in WebGL`);let{buffer:t,bufferUsage:n,prevBuffer:r}=this.gl;if(t??(this.gl.buffer=e.createBuffer()),this.writePos!==r)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Zn){r===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);let t=this.dataType.density.size(r).valueOf(),n=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,t,n.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n===`static`?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Zn}as(e){return nr(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:fr(this.alignmentBounds.lower),upper:fr(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return Pt(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 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){let e=new cr(this);return this.dataType.equals(b.JSON)?new lr(e):e}return this.dataType.equals(b.UUID)?new ur(this):new dr(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new sr(this,e,t??this.length)}subAlignmentIterator(e,t){let n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),r=Math.ceil(Number(t-this.alignment)/Number(this.alignmentMultiple));return new sr(this,n,r)}subBytes(t,n){return t>=0&&(n==null||n>=this.byteLength.valueOf())?this:new e({data:this.data.subarray(t,n),dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}sliceSub(t,n,r){if(n<=0&&(r==null||r>=this.length))return this;let i;return i=t?this.data.subarray(n,r):this.data.slice(n,r),new e({data:i,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(t){return new e({data:this.buffer,dataType:this.dataType,timeRange:Hn.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:`static`,alignment:t})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(e=>e.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=`,`;e+=`...,`;for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=`,`)}return e+=`])`,e}},ar=e=>e==null?!1:Array.isArray(e)||e instanceof ArrayBuffer||ArrayBuffer.isView(e)&&!(e instanceof DataView)||e instanceof ir?!0:Wn(e),or=Xt(rr,ir),sr=class{series;end;index;constructor(e,t,n){this.series=e;let r=Pt(0,e.length+1);this.end=It(r,n),this.index=It(r,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},cr=class{series;index;decoder;constructor(e){if(!e.dataType.isVariable)throw Error(`cannot create a variable series iterator for a non-variable series`);this.series=e,this.index=0,this.decoder=new TextDecoder}next(){let e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==tr;)this.index++;let n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}},lr=class e{wrapped;static schema=l.z.record(l.z.string(),l.z.unknown());constructor(e){this.wrapped=e}next(){let t=this.wrapped.next();return t.done===!0?{done:!0,value:void 0}:{done:!1,value:Vt.decodeString(t.value,e.schema)}}},ur=class{series;index;data;density;constructor(e){if(!e.dataType.equals(b.UUID))throw 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};let e=Xn(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}},dr=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)}}},fr=e=>({domain:e>>32n,sample:e&4294967295n}),pr=async e=>await new Promise(t=>setTimeout(t,v.fromMilliseconds(e).milliseconds)),mr=p({Breaker:()=>hr,breakerConfigZ:()=>gr}),hr=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??pr},this.retries=0,this.interval=new v(this.config.baseInterval)}async wait(){let{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),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}},gr=l.z.object({baseInterval:v.z.optional(),maxRetries:l.z.number().optional(),scale:l.z.number().optional()}),_r=l.z.string().regex(/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i),vr=Lt,yr=l.z.number().min(0).max(1),br=l.z.tuple([vr,vr,vr,yr]),xr=l.z.tuple([vr,vr,vr]),Sr=l.z.object({rgba255:br}),Cr=l.z.object({r:vr,g:vr,b:vr,a:yr}),wr=l.z.number().min(0).max(360),Tr=l.z.number().min(0).max(100),Er=l.z.number().min(0).max(100),Dr=l.z.tuple([wr,Tr,Er,yr]),Or=l.z.union([_r,xr,br,Dr,Sr,Cr]),kr=Or.transform(e=>Ar(e)),Ar=(e,t=1)=>{if(e=Or.parse(e),typeof e==`string`)return jr(e,t);if(Array.isArray(e)){if(e.length<3||e.length>4)throw Error(`Invalid color: [${e.join(`, `)}]`);return e.length===3?[...e,t]:e}return`a`in e&&`r`in e?[e.r,e.g,e.b,e.a]:e.rgba255},jr=(e,t=1)=>(e=_r.parse(e),e=Nr(e),[Mr(e,0),Mr(e,2),Mr(e,4),e.length===8?Mr(e,6)/255:t]),Mr=(e,t)=>parseInt(e.slice(t,t+2),16),Nr=e=>e.startsWith(`#`)?e.slice(1):e;Ar(`#000000`),Ar(`#ffffff`);var Pr=l.z.object({key:l.z.string(),color:Or,position:l.z.number(),switched:l.z.boolean().optional()});l.z.array(Pr);var Fr=l.z.object({key:l.z.string(),name:l.z.string(),color:kr});l.z.object({key:l.z.string(),name:l.z.string(),swatches:l.z.array(Fr)});var Ir=function(e){return e[e.exclusive=0]=`exclusive`,e[e.shared=1]=`shared`,e}({});l.z.enum(Ir),l.z.object({key:l.z.string(),name:l.z.string(),group:l.z.uint32().optional()}),l.z.string().regex(/^(?:$|(?:\/(?:[^~/]|~0|~1)*)+)$/,`must be a valid JSON pointer (RFC 6901)`),l.z.union([l.z.string(),l.z.number(),l.z.boolean(),l.z.null()]),l.z.enum([`string`,`number`,`boolean`,`null`]),l.z.object({key:l.z.string(),value:l.z.string()});var Lr=l.z.uuid();l.z.object({key:Lr,name:l.z.string().min(1),color:kr}).partial({key:!0}),l.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/),l.z.enum([`standard`,`scientific`,`engineering`]);var Rr=l.z.union([l.z.string(),l.z.number()]),zr=()=>l.z.record(Rr,l.z.unknown());typeof process<`u`&&process.versions!=null&&process.versions.node!=null||typeof window>`u`||window.document;var Br=[`macOS`,`Windows`,`Linux`],Vr=[`macos`,`windows`,`linux`],Hr={macos:`macOS`,windows:`Windows`,linux:`Linux`};l.z.enum(Br).or(l.z.enum(Vr).transform(e=>Hr[e])),l.z.object({message:l.z.string().optional(),description:l.z.string().optional(),details:zr().optional()}),l.z.object({stack:l.z.string(),error:l.z.instanceof(Error)}).and(zr()),l.z.enum([`success`,`info`,`warning`,`error`,`loading`,`disabled`]),l.z.literal(`success`),l.z.literal(`info`),l.z.literal(`warning`),l.z.literal(`error`),l.z.literal(`loading`),l.z.literal(`disabled`);var Ur=(...e)=>e.map(Wr).join(``),Wr=e=>(e.endsWith(`/`)||(e+=`/`),e.startsWith(`/`)&&(e=e.slice(1)),e),Gr=e=>e.endsWith(`/`)?e.slice(0,-1):e,Kr=(e,t=``)=>e===null?``:`?${Object.entries(e).filter(([,e])=>e==null?!1:Array.isArray(e)?e.length>0:!0).map(([e,n])=>`${t}${e}=${n}`).join(`&`)}`,qr=class e{protocol;host;port;path;constructor({host:e,port:t,protocol:n=``,pathPrefix:r=``}){this.protocol=n,this.host=e,this.port=t,this.path=Wr(r)}replace(t){return new e({host:t.host??this.host,port:t.port??this.port,protocol:t.protocol??this.protocol,pathPrefix:t.pathPrefix??this.path})}child(t){return new e({...this,pathPrefix:Ur(this.path,t)})}toString(){return Gr(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new e({host:`unknown`,port:0})},Jr=class extends ve.createTyped(`freighter`){},Yr=class extends Jr.sub(`eof`){constructor(){super(`EOF`)}},Xr=class extends Jr.sub(`stream_closed`){constructor(){super(`StreamClosed`)}},Zr=class extends Jr.sub(`unreachable`){url;constructor(e={}){let{message:t=`Unreachable`,url:n=qr.UNKNOWN}=e;super(t),this.url=n}};ve.register({encode:e=>{if(!e.type.startsWith(Jr.TYPE))return null;if(Yr.matches(e))return{type:Yr.TYPE,data:`EOF`};if(Xr.matches(e))return{type:Xr.TYPE,data:`StreamClosed`};if(Zr.matches(e))return{type:Zr.TYPE,data:`Unreachable`};throw Error(`Unknown error type: ${e.type}: ${e.message}`)},decode:e=>{if(!e.type.startsWith(Jr.TYPE))return null;switch(e.type){case Yr.TYPE:return new Yr;case Xr.TYPE:return new Xr;case Zr.TYPE:return new Zr;default:throw new ve.Unknown(`Unknown error type: ${e.data}`)}}});var Qr=class{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0,r=async e=>{if(n===this.middleware.length)return await t(e);let i=this.middleware[n];return n++,await i(e,r)};return await r(e)}},$r=`Content-Type`,ei=new Set([`ECONNREFUSED`,`ECONNRESET`,`ETIMEDOUT`,`EPIPE`,`UND_ERR_CONNECT_TIMEOUT`,`UND_ERR_SOCKET`]),ti=e=>{let t=e?.cause?.code??e?.code??e?.errno;if(typeof t==`string`&&ei.has(t))return!0;if(e.name===`TypeError`){let t=String(e.message||``).toLowerCase();if(/load failed|failed to fetch|networkerror|network error/.test(t))return typeof navigator<`u`&&navigator.onLine,!0}return e?.name===`AbortError`||e?.code,!1},ni=400,ri=class extends Qr{endpoint;encoder;constructor(e,t,n=!1){return super(),this.endpoint=e.replace({protocol:n?`https`:`http`}),this.encoder=t,new Proxy(this,{get:(e,t,n)=>t===`endpoint`?this.endpoint:Reflect.get(e,t,n)})}get headers(){return{[$r]:this.encoder.contentType}}async send(e,t,n,r){let i=null,a=this.endpoint.child(e),o={};o.method=`POST`,o.body=this.encoder.encode(t,n);let[,s]=await this.executeMiddleware({target:a.toString(),protocol:this.endpoint.protocol,params:{},role:`client`},async e=>{let t={...e,params:{}};o.headers={...this.headers,...e.params};let n;try{n=await fetch(e.target,o)}catch(e){if(!(e instanceof Error))throw e;return[t,ti(e)?new Zr({url:a}):e]}let s=await n.arrayBuffer();if(n?.ok)return r!=null&&(i=this.encoder.decode(s,r)),[t,null];try{if(n.status!==ni)return[t,Error(n.statusText)];let e=this.encoder.decode(s,ve.payloadZ);return[t,ve.decode(e)]}catch(e){return[t,Error(`[freighter] - failed to decode error: ${n.statusText}: ${e.message}`)]}});if(s!=null)return[null,s];if(i==null)throw Error(`Response must be defined`);return[i,null]}},ii=(e,t)=>{class n{wrapped;constructor(e){this.wrapped=e}use(...e){this.wrapped.use(...e)}async send(e,n,r,i){let a=new mr.Breaker(t);do{let[t,o]=await this.wrapped.send(e,n,r,i);if(o==null)return[t,null];if(!Zr.matches(o))return[null,o];if(console.warn(`[freighter] ${a.retryMessage}`,o),!await a.wait())return[t,o]}while(!0)}}return new n(e)},S=async(e,t,n,r,i)=>{let[a,o]=await e.send(t,n,r,i);if(o!=null)throw o;return a},ai=l.z.object({type:l.z.enum([`data`,`close`,`open`]),payload:l.z.unknown(),error:l.z.optional(ve.payloadZ)}),oi=class{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,t,n,r){this.codec=t,this.reqSchema=n,this.resSchema=r,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){let e=await this.receiveMsg();if(e.type!==`open`){if(e.error==null)throw Error(`Message error must be defined`);return ve.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new Yr;if(this.sendClosed)throw new Xr;return this.ws.send(this.codec.encode({type:`data`,payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];let e=await this.receiveMsg();if(e.type===`close`){if(e.error==null||(this.serverClosed=ve.decode(e.error),this.serverClosed==null))throw 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;let e={type:`close`};try{this.ws.send(this.codec.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((e,t)=>this.receiveCallbacksQueue.push({resolve:e,reject:t}))}addMessage(e){let t=this.receiveCallbacksQueue.shift();t==null?this.receiveDataQueue.push(e):t.resolve(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,ai))}onClose(e){this.addMessage({type:`close`,error:{type:e.code===ci?Yr.TYPE:Xr.TYPE,data:``}})}},si=`freighterctx`,ci=1e3,li=class e extends Qr{baseUrl;encoder;secure;static MESSAGE_TYPE=`arraybuffer`;constructor(e,t,n=!1){super(),this.secure=n,this.baseUrl=e.replace({protocol:n?`wss`:`ws`}),this.encoder=t}withCodec(t){let n=new e(this.baseUrl,t,this.secure);return n.use(...this.middleware),n}async stream(t,n,r){let i,[,a]=await this.executeMiddleware({target:t,protocol:`websocket`,params:{},role:`client`},async a=>{let o=new WebSocket(this.buildURL(t,a)),s={...a,params:{}};o.binaryType=e.MESSAGE_TYPE;let c=await this.wrapSocket(o,n,r);return c instanceof Error?[s,c]:(i=c,[s,null])});if(a!=null)throw a;return i}buildURL(e,t){let n=Kr({[$r]:this.encoder.contentType,...t.params},si);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(r=>{e.onopen=()=>{let i=new oi(e,this.encoder,t,n);i.receiveOpenAck().then(e=>{r(e??i)}).catch(e=>r(e))},e.onerror=e=>{r(Error(e.message))}})}},ui=Object.defineProperty,C=(e,t)=>{let n={};for(var r in e)ui(n,r,{get:e[r],enumerable:!0});return t||ui(n,Symbol.toStringTag,{value:`Module`}),n},di=e=>l.default.union([l.default.union([l.default.null(),l.default.undefined()]).transform(()=>[]),e.array()]),fi=e=>Array.isArray(e)?e:e==null?[]:[e],pi=(e,t)=>{if(Array.isArray(t))return t.reduce((e,t)=>pi(e,t),e??[]);if(e==null)return[t];let n=e.findIndex(e=>e==t),r=[...e];return n===-1?r.push(t):r[n]=t,r},mi=((e,t)=>{if(e!=null)return Array.isArray(t)?e.filter(e=>!t.includes(e)):e.filter(e=>e!=t)}),hi=(e,t)=>{if(Array.isArray(t))return t.reduce((e,t)=>hi(e,t),e??[]);if(e==null)return[t];let n=e.findIndex(e=>e.key===t.key),r=[...e];return n===-1?r.push(t):r[n]=t,r},gi=((e,t)=>{if(e!=null)return Array.isArray(t)?e.filter(e=>!t.includes(e.key)):e.filter(e=>e.key!==t)}),w=C({nullishToEmpty:()=>di,remove:()=>mi,removeKeyed:()=>gi,toArray:()=>fi,upsert:()=>pi,upsertKeyed:()=>hi}),_i=C({camelToSnake:()=>Ei,capitalize:()=>Di,preserveCase:()=>yi,snakeToCamel:()=>Ti,toKebab:()=>ji,toProperNoun:()=>Mi}),vi=`synnax.caseconv.preserveCase`,yi=e=>(e[vi]=!0,e),bi=e=>{if(typeof e!=`object`||!e)return!1;if(vi in e)return!0;let t=e._zod?.def;return t==null?!1:t.innerType&&bi(t.innerType)?!0:t.type===`union`&&Array.isArray(t.options)?t.options.some(bi):t.type===`pipe`?bi(t.in)||bi(t.out):!1},xi=e=>{if(e==null)return;let t=e._zod?.def;if(t?.type===`array`&&t.element!=null)return t.element;if(t?.type===`union`&&Array.isArray(t.options))for(let e of t.options){let t=xi(e);if(t!=null)return t}},Si=e=>{if(e==null)return null;let t=e;if(t.shape!=null)return t.shape;if(typeof t.sourceType==`function`){let e=t.sourceType();if(e?.shape!=null)return e.shape}let n=t._zod?.def;if(n==null)return null;if(n.innerType!=null)return Si(n.innerType);if(n.type===`union`&&Array.isArray(n.options))for(let e of n.options){let t=Si(e);if(t!=null)return t}return n.type===`pipe`?Si(n.in)??Si(n.out):null},Ci=e=>{if(e.length===0)return e;let t=e.indexOf(`_`)===-1?e:e.replace(/_[a-z]/g,e=>e[1].toUpperCase()),n=t.charCodeAt(0);return n<65||n>90||t.length>1&&t.charCodeAt(1)>=65&&t.charCodeAt(1)<=90?t:String.fromCharCode(n+32)+t.slice(1)},wi=e=>{let t=(n,r=Oi)=>{if(typeof n==`string`)return e(n);if(Array.isArray(n)){let e=xi(r.schema),i={recursive:r.recursive,recursiveInArray:r.recursiveInArray,schema:e};return n.map(e=>t(e,i))}if(!ki(n)||r.schema!=null&&bi(r.schema))return n;let i=r.recursive??!0,a=r.recursiveInArray??i,o=r.schema,s={},c=n;if(`toJSON`in c&&typeof c.toJSON==`function`)return t(c.toJSON(),r);let l=Si(o),u={recursive:i,recursiveInArray:a,schema:void 0},d=Object.keys(c);for(let n=0;n<d.length;n++){let r=d[n],o=c[r],f=e(r),p=l==null?void 0:l[r]??l[f]??void 0;i&&(ki(o)?Ai(o)||(u.schema=p,o=t(o,u)):a&&Array.isArray(o)&&(u.schema=xi(p),o=o.map(e=>{if(ki(e)){if(!Ai(e))return t(e,u)}else if(Array.isArray(e))return t({key:e},u).key;return e}))),s[f]=o}return s};return t},Ti=wi(Ci),Ei=wi(e=>e.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`)),Di=e=>e.length===0?e:e[0].toUpperCase()+e.slice(1),Oi={recursive:!0,recursiveInArray:!0,schema:void 0},ki=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Ai=e=>e instanceof Uint8Array||e instanceof Number||e instanceof String,ji=wi(e=>e.replace(/[\s_]+/g,`-`).replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}-${n.toLowerCase()}`).toLowerCase()),Mi=wi(e=>{if(e.length===0)return e;let t=e.replace(/[_-]/g,` `);return t=t.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t} ${n}`),t=t.replace(/([A-Z]+)([A-Z][a-z])/g,(e,t,n)=>`${t} ${n}`),t=t.replace(/\s+/g,` `).trim(),t=t.replace(/\b\w/g,e=>e.toUpperCase()),t}),Ni=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Pi=e=>{if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Fi=e=>e.nullable().transform(e=>e===null?void 0:e).optional(),Ii=(e,t)=>{let n=e;for(let e of t){if(typeof n!=`object`||!n)return{present:!1,value:void 0};let t=n;if(!(e in t))return{present:!1,value:void 0};n=t[e]}return{present:!0,value:n}},Li=(e,t)=>{let n=Array.isArray(e),r=Array.isArray(t);if(n!==r)return!1;if(n&&r){let n=e,r=t;if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++)if(!Li(n[e],r[e]))return!1;return!0}if(e==null||t==null||typeof e!=`object`||typeof t!=`object`)return e===t;if(`equals`in e)return e.equals(t);let i=Object.keys(e),a=Object.keys(t);if(i.length!==a.length)return!1;for(let n of i){let r=e[n],i=t[n];if(typeof r==`object`&&typeof i==`object`){if(!Li(r,i))return!1}else if(r!==i)return!1}return!0},Ri=(e,t)=>{if(typeof e!=`object`||!e)return e===t;let n=Object.keys(e),r=Object.keys(t);if(r.length>n.length)return!1;for(let n of r){let r=e[n],i=t[n];if(typeof r==`object`&&typeof i==`object`){if(!Ri(r,i))return!1}else if(r!==i)return!1}return!0},zi=(e,t,n=`.`)=>{let r=e.split(n);return r.map((e,i)=>{let a=t(e,i,r);return a==null?null:typeof a==`string`?a:a.join(n)}).filter(e=>e!=null).join(n)},Bi=(e,t)=>{if(!Array.isArray(e))return e[t];let n=e[t];if(n!=null||e.length==0)return n;let r=e[0];if(typeof r==`object`&&`key`in r)return e.find(e=>e.key===t)},Vi=((e,t,n={optional:!1})=>{let{optional:r,getter:i=Bi}=n;if(t===``)return e;let a=t.split(`.`);if(a.length===1){let n=i(e,a[0]);if(n===void 0){if(r)return null;throw Error(`Path ${t} does not exist. ${a[0]} is undefined`)}return n}let o=(e,n)=>{if(n>=a.length)return e;for(let s=a.length-n;s>=1;s--){let c=a.slice(n,n+s).join(`.`),l=i(e,c);if(l!==void 0){if(n+s===a.length)return l;if(l===null){if(r)return null;throw Error(`Path ${t} does not exist. ${c} is null`)}return o(l,n+s)}}if(r)return null;throw Error(`Path ${t} does not exist. ${a[n]} is undefined`)};return o(e,0)}),Hi=(e,...t)=>{if(t.length===0)return e;let n=t.shift();if(Ni(e)&&Ni(n))for(let t in n)try{Ni(n[t])?(t in e||Object.assign(e,{[t]:{}}),Hi(e[t],n[t])):Object.assign(e,{[t]:n[t]})}catch(e){throw e instanceof TypeError?TypeError(`.${t}: ${e.message}`,{cause:e}):e}return Hi(e,...t)},Ui=e=>Object.getOwnPropertySymbols(globalThis).includes(e),Wi=(e,t)=>{let n=Symbol.for(e);if(!Ui(n)){let e=t();Object.defineProperty(globalThis,n,{value:e})}return()=>globalThis[n]},Gi=C({Canceled:()=>ia,NONE:()=>`nil`,NotImplemented:()=>aa,UNKNOWN:()=>Xi,Unknown:()=>na,createTyped:()=>Ji,decode:()=>ta,encode:()=>ea,isTyped:()=>Yi,payloadZ:()=>ra,register:()=>$i}),Ki=`sy_x_error`,qi=e=>t=>typeof t==`object`&&t&&`type`in t&&typeof t.type==`string`?t.type.startsWith(e):t instanceof Error?t.message.startsWith(e):typeof t==`string`?t.startsWith(e):!1,Ji=e=>class t extends Error{static discriminator=Ki;discriminator=t.discriminator;static TYPE=e;type=t.TYPE;static matches=qi(e);matches=t.matches;constructor(e,n){super(e,n),this.name=t.TYPE}static sub(t){return Ji(`${e}.${t}`)}},Yi=e=>{if(typeof e!=`object`||!e)return!1;let t=e;if(t.discriminator!==Ki)return!1;if(!(`type`in t))throw Error(`X Error is missing its type property: ${JSON.stringify(t)}`);return!0},Xi=`unknown`,Zi=class{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:`nil`,data:``};if(Yi(e))for(let t of this.providers){let n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Xi,data:e.message};if(typeof e==`string`)return{type:Xi,data:e};try{return{type:Xi,data:JSON.stringify(e)}}catch{return{type:Xi,data:`unable to encode error information`}}}decode(e){if(e==null||e.type===`nil`)return null;if(e.type===`unknown`)return new na(e.data);for(let t of this.providers){let n=t.decode(e);if(n!=null)return n}return new na(e.data)}},Qi=Wi(`synnax-error-registry`,()=>new Zi),$i=({encode:e,decode:t})=>Qi().register({encode:e,decode:t}),ea=e=>Qi().encode(e),ta=e=>e==null?null:Qi().decode(e),na=class extends Ji(`unknown`){},ra=l.z.object({type:l.z.string(),data:l.z.string()}),ia=class extends Ji(`canceled`){},aa=class extends Ji(`not_implemented`){},oa=e=>{if(e.length===0)return`<root>`;let t=``;return e.forEach((e,n)=>{typeof e==`number`?t+=`[${e}]`:n===0?t+=String(e):t+=`.${String(e)}`}),t},sa=200,ca=10,la=8,ua=(e,t={})=>{let n=t.maxStringLength??sa,r=t.maxArrayLength??ca,i=t.maxDepth??la,a=(e,t)=>{if(e===null)return null;if(e===void 0)return`[undefined]`;let o=typeof e;if(o===`string`){let t=e;return t.length>n?`${t.slice(0,n)}…(+${t.length-n} chars)`:t}if(o===`number`||o===`boolean`)return e;if(o===`bigint`)return`${e.toString()}n`;if(o===`symbol`||o===`function`)return`[${o}]`;if(Array.isArray(e)){if(t>=i)return`[Array(${e.length})]`;let n=e.slice(0,r).map(e=>a(e,t+1));return e.length>r&&n.push(`…(+${e.length-r} more)`),n}if(Pi(e)){if(t>=i)return`[Object]`;let n={};for(let[r,i]of Object.entries(e))n[r]=a(i,t+1);return n}if(e instanceof Date)return e.toISOString();if(e instanceof Error)return`[Error: ${e.message}]`;try{return`[${Object.prototype.toString.call(e)}]`}catch{return`[unknown]`}};return a(e,0)},da=(e,t={})=>JSON.stringify(ua(e,t),null,2),fa=C({ValueExtension:()=>pa,is:()=>_a,isCrudeValueExtension:()=>T,isNonZero:()=>ga,isStringer:()=>ma,isZero:()=>ha}),T=e=>typeof e==`object`&&!!e&&`value`in e,pa=class{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}},ma=e=>typeof e==`object`&&!!e&&`toString`in e,ha=e=>{if(ma(e))return e?.toString().length===0;switch(typeof e){case`string`:return e.length===0;case`number`:return e===0;case`bigint`:return e===0n;case`boolean`:return!e;case`undefined`:return!0;case`object`:return e==null;default:return!1}},ga=e=>!ha(e),_a=e=>e==null||typeof e!=`object`&&typeof e!=`function`,va=`value`,ya=`zod.parse`,ba=`✗`,xa=60,Sa={maxStringLength:60,maxArrayLength:3,maxDepth:3},Ca=e=>e.slice(0,-1),wa=e=>{switch(e.code){case`invalid_type`:return`expected ${e.expected}`;case`invalid_value`:return`expected one of ${JSON.stringify(e.values)}`;case`unrecognized_keys`:return`unexpected key`;case`too_small`:{let t=e.inclusive===!1?`>`:`>=`;return`${e.origin} too small: expected ${t}${e.minimum}`}case`too_big`:{let t=e.inclusive===!1?`<`:`<=`;return`${e.origin} too large: expected ${t}${e.maximum}`}case`invalid_format`:return`expected ${e.format} format`;case`not_multiple_of`:return`expected multiple of ${e.divisor}`;case`custom`:return e.message||`custom validation failed`;default:return e.message}},Ta=(e,t,n)=>{let r=JSON.stringify(ua(t,n));return`${wa(e)}, received ${r}`},Ea=e=>{let t=0;for(let n of e){if(n.path.length>t&&(t=n.path.length),n.code===`invalid_union`&&`errors`in n)for(let e of n.errors){let n=Ea(e);n>t&&(t=n)}if((n.code===`invalid_key`||n.code===`invalid_element`)&&`issues`in n){let e=Ea(n.issues);e>t&&(t=e)}}return t},Da=(e,t=[])=>{let n=[];for(let r of e){let e=[...t,...r.path];if(r.code===`invalid_union`&&`errors`in r&&r.errors.length>0){let t=r.errors[0],i=Ea(t);for(let e=1;e<r.errors.length;e++){let n=Ea(r.errors[e]);n>i&&(t=r.errors[e],i=n)}n.push(...Da(t,e));continue}if(r.code===`invalid_element`&&`issues`in r&&`key`in r&&(typeof r.key==`string`||typeof r.key==`number`)){n.push(...Da(r.issues,[...e,r.key]));continue}if(r.code===`invalid_key`&&`issues`in r){n.push(...Da(r.issues,e));continue}n.push({...r,path:e})}return n},Oa=e=>{let t=[];for(let n of e){if(n.code===`unrecognized_keys`&&`keys`in n&&Array.isArray(n.keys)){for(let e of n.keys)t.push({...n,path:[...n.path,e]});continue}t.push(n)}return t},ka=(e,t,n,r)=>{let i=`${n} `,a=`${n+ba} `,o={...Sa,...r};if(Array.isArray(e)){let e=-1;for(let n of t.keys()){let t=Number(n);Number.isInteger(t)&&t>e&&(e=t)}let n=o.maxArrayLength??3;e>=n&&(o={...o,maxArrayLength:e+2})}let s=ua(e,o);if(typeof s!=`object`||!s){let e=JSON.stringify(s),n=t.values().next().value;return[`${a}${e}${n?` × ${n.reason}`:``}`]}let c=[],l=Array.isArray(s);c.push(`${n}${l?`[`:`{`}`);let u=[];if(l){let e=s;for(let n=0;n<e.length;n++){let r=t.get(String(n));u.push({content:JSON.stringify(e[n]),mark:r&&!r.missing?r:void 0})}}else{let e=s;for(let n of Object.keys(e)){let r=t.get(n);u.push({content:`"${n}": ${JSON.stringify(e[n])}`,mark:r&&!r.missing?r:void 0})}for(let[e,n]of t.entries())n.missing&&u.push({content:`"${e}": <missing>`,mark:n})}let d=0;return u.forEach((e,t)=>{if(e.mark==null)return;let n=t<u.length-1?1:0,r=e.content.length+n;r>d&&r<=xa&&(d=r)}),u.forEach((e,t)=>{let n=t<u.length-1?`,`:``,r=e.content+n;if(e.mark!=null){let t=` `.repeat(Math.max(2,d-r.length+2));c.push(`${a}${r}${t}× ${e.mark.reason}`)}else c.push(`${i}${r}`)}),c.push(n+(l?`]`:`}`)),c},Aa=`__root__`,ja=(e,t,n)=>{let r=new Map;for(let t of e){let e=t.path.length===0?Aa:`::${oa(Ca(t.path))}`,n=r.get(e);n==null?r.set(e,[t]):n.push(t)}let i=[];for(let[e,a]of r){if(e===Aa){i.push(a.map(e=>` × ${Ta(e,t,n)}`).join(`
15
+ `));continue}let r=Ca(a[0].path),{present:o,value:s}=Ii(t,r);if(!o){i.push(a.map(e=>` at ${oa(e.path)}\n × ${Ta(e,t,n)}`).join(`
16
+ `));continue}let c=new Map;for(let e of a){let n=String(e.path[e.path.length-1]),r=Ii(t,e.path);c.set(n,{reason:wa(e),missing:!r.present})}let l=r.length===0,u=ka(s,c,l?` `:` `,n);l?i.push(u.join(`
17
+ `)):i.push([` at ${oa(r)}`,...u].join(`
18
+ `))}return i.join(`
19
+
20
+ `)},Ma=(e,t)=>{let n=Object.entries(e);return n.every(([,e])=>_a(e))?n.map(([e,t])=>`${e}=${typeof t==`string`?t:String(t)}`).join(`, `):da(e,t)},Na=({issues:e,input:t,label:n,context:r,formatOptions:i})=>{let a=i??{},o=Oa(Da(e)),s=[`Failed to parse ${n} (${o.length===1?`1 issue`:`${o.length} issues`})`];return s.push(ja(o,t,a)),r!=null&&Object.keys(r).length>0&&s.push(` context: ${Ma(r,a)}`),s.join(`
21
+
22
+ `)},Pa=class extends Ji(ya){issues;input;label;context;constructor({issues:e,input:t,label:n,context:r,cause:i,formatOptions:a}){super(Na({issues:e,input:t,label:n,context:r,formatOptions:a}),{cause:i}),this.issues=e,this.input=t,this.label=n,this.context=r}toStatus(){let e={input:ua(this.input),issues:this.issues};return this.context!=null&&(e.context=this.context),{message:`Failed to parse ${this.label}`,description:this.message,details:e}}};$i({encode:e=>{if(!Pa.matches(e))return null;let t=e,n={label:t.label,context:t.context,issues:t.issues,input:ua(t.input)};return{type:ya,data:JSON.stringify(n)}},decode:e=>{if(e.type!==ya)return null;let t=JSON.parse(e.data);return new Pa({issues:t.issues,input:t.input,label:t.label,context:t.context})}});var Fa=(e,t,n={})=>{let r=e.safeParse(t);if(r.success)return r.data;throw new Pa({issues:r.error.issues,input:t,label:n.label??va,context:n.context,cause:r.error})},Ia=2**12-1,La=2**16-1,Ra=2**20-1,za=-128,Ba=-(2**15),Va=2**15-1,Ha=-(2n**63n),Ua=2n**63n-1n,Wa=-(2**63),Ga=2**63-1,Ka=e=>(t,n)=>{if(typeof t==`bigint`){if(Za(n))return e(t,BigInt(n));let r=e(Number(t),Number(n));return typeof r==`number`?BigInt(Math.round(r)):r}return e(Number(t),Number(n))},qa=Ka((e,t)=>e-t),Ja=Ka((e,t)=>e+t),Ya=(e,t)=>{let n=typeof e==`bigint`,r=typeof t==`bigint`;return n&&r?e===t:n&&Za(t)?e===BigInt(t):r&&Za(e)?t===BigInt(e):e===t},Xa=Ka((e,t)=>e<=t?e:t),Za=e=>typeof e==`bigint`?!0:Number.isInteger(e),Qa=e=>typeof e==`bigint`?e<0n?-e:e:e<0?-e:e,$a=Ka((e,t)=>e*t),eo=Ka((e,t)=>e/t),to=l.z.tuple([l.z.number(),l.z.number()]),no=[`x`,`y`],ro=l.z.enum(no),io=[`top`,`right`,`bottom`,`left`],ao=l.z.enum(io),oo=[`left`,`right`],so=l.z.enum(oo),co=[`top`,`bottom`],lo=l.z.enum(co),uo=[`center`],fo=l.z.enum(uo),po=[`top`,`right`,`bottom`,`left`,`center`],mo=l.z.enum(po),ho=[`start`,`center`,`end`],go=l.z.enum(ho),_o=[`first`,`last`],vo=l.z.enum(_o),yo=l.z.object({clientX:l.z.number(),clientY:l.z.number()}),bo=l.z.object({width:l.z.number(),height:l.z.number()}),xo=l.z.object({signedWidth:l.z.number(),signedHeight:l.z.number()}),So=l.z.object({lower:l.z.number(),upper:l.z.number()});l.z.enum([`x`,`y`,...io,...uo]),l.z.union([ro,l.z.enum([...io,...uo]),l.z.instanceof(String)]);var E=(e,t,n)=>{let r={};if(typeof t==`object`&&(n=t,t=void 0),n={makeValid:!0,...n},typeof e==`number`||typeof e==`bigint`)t==null?(r.lower=typeof e==`bigint`?0n:0,r.upper=e):(r.lower=e,r.upper=t);else if(Array.isArray(e)){if(e.length!==2)throw Error(`bounds: expected array of length 2`);[r.lower,r.upper]=e}else r.lower=e.lower,r.upper=e.upper;return n?.makeValid?Co(r):r};Object.freeze({lower:0,upper:0}),Object.freeze({lower:-1/0,upper:1/0}),Object.freeze({lower:0,upper:1}),Object.freeze({lower:-1,upper:1});var Co=e=>e.lower>e.upper?{lower:e.upper,upper:e.lower}:e,wo=(e,t)=>{let n=E(e);return t<n.lower?n.lower:t>=n.upper?n.upper-(typeof n.upper==`number`?1:1n):t},To=(e,t)=>{let n=E(e);if(typeof t==`number`||typeof t==`bigint`)return t>=n.lower&&t<n.upper;let r=E(t);return r.lower>=n.lower&&r.upper<=n.upper},Eo=e=>({lower:Math.min(...e.map(e=>E(e).lower)),upper:Math.max(...e.map(e=>E(e).upper))}),Do=(e,t,n)=>{let r=e.map(e=>E(e)),i=n>0?1:n<0?-1:0;if(i===0)return t;let a=n,o=t;for(;Ya(a,0)===!1;){let e=r.findIndex(e=>i>0?o>=e.lower&&o<e.upper:o>e.lower&&o<=e.upper);if(e!==-1){let t=r[e],n;if(n=i>0?qa(t.upper,o):qa(o,t.lower),n>0){let e=Xa(Qa(a),n);if(o=Ja(o,i>0?e:-e),a=qa(a,i>0?e:-e),Ya(a,0))return o;continue}}if(i>0){let e=r.filter(e=>e.lower>o);if(e.length>0)o=e[0].lower;else return o}else{let e=r.filter(e=>e.upper<o);if(e.length>0)o=e[e.length-1].upper;else return o}}return o},Oo=(e,t,n)=>{let r=e.map(e=>E(e));if(t===n)return typeof t==`bigint`?0n:0;let i=E(t<n?[t,n]:[n,t]),a=typeof t==`bigint`?0n:0;for(let e of r){let t=e.lower>i.lower?e.lower:i.lower,n=e.upper<i.upper?e.upper:i.upper;if(t<n){let e=n-t;a+=e}}return a},ko=l.z.int().min(za).max(127),Ao=l.z.int().min(Ba).max(Va),jo=l.z.int().min(Wa).max(Ga),Mo=l.z.int().min(0).max(255),No=l.z.int().min(0).max(Ia),Po=l.z.int().min(0).max(La),Fo=l.z.int().min(0).max(Ra),Io=e=>l.default.array(e).or(e.transform(e=>[e])),Lo=e=>e._zod.def.output,Ro=e=>zi(e,(e,t,n)=>{let r=t===n.length-1,i=!isNaN(parseInt(e,10)),a=!isNaN(parseInt(n[t+1],10));return i&&(e=`element`),r||a?e:[e,`shape`]}),zo=(e,t)=>{if(e==null)return null;let n=e[t];return n==null&&typeof e==`object`&&`sourceType`in e?e.sourceType()[t]:n},Bo=((e,t,n)=>t===``?e:Vi(zo(e,`shape`),Ro(t),{...n,getter:zo})),D=C({ParseError:()=>Pa,functionOutput:()=>Lo,getFieldSchema:()=>Bo,getFieldSchemaPath:()=>Ro,int16:()=>Ao,int64:()=>jo,int8:()=>ko,nullToUndefined:()=>Fi,parse:()=>Fa,toArray:()=>Io,uint12:()=>No,uint16:()=>Po,uint20:()=>Fo,uint8:()=>Mo}),Vo=C({CSVCodec:()=>Uo,CSV_CODEC:()=>Ko,ENCODERS:()=>Jo,JSONCodec:()=>Ho,JSON_CODEC:()=>Go,TEXT_CODEC:()=>qo,TextCodec:()=>Wo}),Ho=class{contentType=`application/json`;decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e,t){return this.encoder.encode(this.encodeString(e,t))}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){let n=Ti(JSON.parse(e),{schema:t});return t==null?n:Fa(t,n)}encodeString(e,t){let n=Ei((t==null?e:Fa(t,e))??{},{schema:t});return JSON.stringify(n,(e,t)=>ArrayBuffer.isView(t)?Array.from(t):typeof t==`bigint`?t.toString():t)}},Uo=class{contentType=`text/csv`;encode(e){let t=this.encodeString(e);return new TextEncoder().encode(t)}decode(e,t){let n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Ni(e[0]))throw Error(`Payload must be an array of objects`);let t=Object.keys(e[0]),n=[t.join(`,`)];return e.forEach(e=>{let r=t.map(t=>JSON.stringify(e[t]??``));n.push(r.join(`,`))}),n.join(`
7
23
  `)}decodeString(e,t){let[n,...r]=e.trim().split(`
8
- `).map(e=>e.trim());if(n.length===0)return t==null?{}:t.parse({});let i=n.split(`,`).map(e=>e.trim()),a={};return i.forEach(e=>{a[e]=[]}),r.forEach(e=>{let t=e.split(`,`).map(e=>e.trim());i.forEach((e,n)=>{let r=this.parseValue(t[n]);r!=null&&a[e].push(r)})}),t==null?a:t.parse(a)}parseValue(e){if(e==null||e.length===0)return null;let t=Number(e);return isNaN(t)?e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e:t}},ci=class{contentType=`text/plain`;encode(e){if(typeof e!=`string`)throw Error(`TextCodec.encode payload must be a string`);return new TextEncoder().encode(e)}decode(e,t){let n=new TextDecoder().decode(e);return t==null?n:t.parse(n)}},li=new oi,ui=new si,di=new ci,fi=[li],pi=C({ValueExtension:()=>mi,isCrudeValueExtension:()=>T,isNonZero:()=>_i,isStringer:()=>hi,isZero:()=>gi}),T=e=>typeof e==`object`&&!!e&&`value`in e,mi=class{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}},hi=e=>typeof e==`object`&&!!e&&`toString`in e,gi=e=>{if(hi(e))return e?.toString().length===0;switch(typeof e){case`string`:return e.length===0;case`number`:return e===0;case`bigint`:return e===0n;case`boolean`:return!e;case`undefined`:return!0;case`object`:return e==null;default:return!1}},_i=e=>!gi(e),vi=C({by:()=>bi,unique:()=>yi}),yi=e=>[...new Set(e)],bi=(e,t,n=!0)=>{let r=new Map;return e.forEach(e=>{let i=t(e);if(r.has(i)){if(n)return;r.delete(i)}r.set(i,e)}),Array.from(r.values())},xi=(e,t=!1)=>{let n=hi(e)?`stringer`:typeof e,r;switch(n){case`string`:r=(e,t)=>e.localeCompare(t);break;case`stringer`:r=(e,t)=>e.toString().localeCompare(t.toString());break;case`number`:r=(e,t)=>Number(e)-Number(t);break;case`bigint`:r=(e,t)=>BigInt(e)-BigInt(t)>0n?1:-1;break;case`boolean`:r=(e,t)=>Number(e)-Number(t);break;case`undefined`:r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return t?Di(r):r},Si=(e,t,n)=>{let r=xi(t[e],n);return(t,n)=>r(t[e],n[e])},Ci=(e,t)=>e.length===t.length?e.every((e,n)=>e===t[n])?0:-1:e.length-t.length,wi=(e,t)=>{if(e.length!==t.length)return e.length-t.length;if(e.length===0)return 0;let n=xi(e[0]),r=[...e].sort(n),i=[...t].sort(n);return r.every((e,t)=>e===i[t])?0:-1},Ti=(e,t)=>wi(yi(e),yi(t)),Ei=(e,t)=>e===t?0:e===`first`&&t===`last`?1:-1,Di=e=>(t,n)=>e(n,t),Oi=e=>e<0,ki=e=>e>0,Ai=e=>e>=0,ji=e=>e===0,Mi=(e,t)=>{let n=/([a-zA-Z]+)|(\d+)/g,r=e.replace(/[\s_.-]+/g,``).match(n),i=t.replace(/[\s_.-]+/g,``).match(n);if(!r||!i)return 0;for(let e=0;e<Math.min(r.length,i.length);e++){let t=r[e],n=i[e];if(isNaN(Number(t))&&isNaN(Number(n))){let e=t.localeCompare(n);if(e!==0)return e}else if(!isNaN(Number(t))&&!isNaN(Number(n))){let e=Number(t)-Number(n);if(e!==0)return e}else return isNaN(Number(t))?-1:1}return r.length-i.length},Ni=(e,t,n)=>{let r=0,i=e.length,a=n??xi(t);for(;r<i;){let n=Math.floor((r+i)/2),o=a(e[n],t);if(o===0)return n;o<0?r=n+1:i=n}return r},Pi=(e,t,n)=>{let r=Ni(e,t,n);e.splice(r,0,t)},Fi=C({EQUAL:()=>0,GREATER_THAN:()=>1,LESS_THAN:()=>-1,insert:()=>Pi,isEqualTo:()=>ji,isGreaterThan:()=>ki,isGreaterThanEqual:()=>Ai,isLessThan:()=>Oi,newF:()=>xi,newFieldF:()=>Si,order:()=>Ei,primitiveArrays:()=>Ci,reverseF:()=>Di,search:()=>Ni,stringsWithNumbers:()=>Mi,uniqueUnorderedPrimitiveArrays:()=>Ti,unorderedPrimitiveArrays:()=>wi}),Ii=(e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i--;)r+=e[Math.random()*e.length|0];return r},Li=C({LENGTH:()=>11,create:()=>Hi}),Ri=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,zi=`0123456789${Ri}`,Bi=Ii(Ri,1),Vi=Ii(zi,10),Hi=()=>`${Bi()}${Vi()}`,Ui=(e,t)=>n=>n instanceof t||typeof n==`object`&&!!n&&`discriminator`in n&&n.discriminator===e,Wi=2**12-1,Gi=2**16-1,Ki=2**20-1,qi=-128,Ji=-(2**15),Yi=2**15-1,Xi=-(2n**63n),Zi=2n**63n-1n,Qi=-(2**63),$i=2**63-1,ea=e=>(t,n)=>{if(typeof t==`bigint`){if(aa(n))return e(t,BigInt(n));let r=e(Number(t),Number(n));return typeof r==`number`?BigInt(Math.round(r)):r}return e(Number(t),Number(n))},ta=ea((e,t)=>e-t),na=ea((e,t)=>e+t),ra=(e,t)=>{let n=typeof e==`bigint`,r=typeof t==`bigint`;return n&&r?e===t:n&&aa(t)?e===BigInt(t):r&&aa(e)?t===BigInt(e):e===t},ia=ea((e,t)=>e<=t?e:t),aa=e=>typeof e==`bigint`?!0:Number.isInteger(e),oa=e=>typeof e==`bigint`?e<0n?-e:e:e<0?-e:e,sa=ea((e,t)=>e*t),ca=ea((e,t)=>e/t),la=l.z.tuple([l.z.number(),l.z.number()]),ua=[`x`,`y`],da=l.z.enum(ua),fa=[`top`,`right`,`bottom`,`left`],pa=l.z.enum(fa),ma=[`left`,`right`],ha=l.z.enum(ma),ga=[`top`,`bottom`],_a=l.z.enum(ga),va=[`center`],ya=l.z.enum(va),ba=[`top`,`right`,`bottom`,`left`,`center`],xa=l.z.enum(ba),Sa=[`start`,`center`,`end`],Ca=l.z.enum(Sa),wa=[`first`,`last`],Ta=l.z.enum(wa),Ea=l.z.object({clientX:l.z.number(),clientY:l.z.number()}),Da=l.z.object({width:l.z.number(),height:l.z.number()}),Oa=l.z.object({signedWidth:l.z.number(),signedHeight:l.z.number()}),ka=l.z.object({lower:l.z.number(),upper:l.z.number()});l.z.enum([`x`,`y`,...fa,...va]),l.z.union([da,l.z.enum([...fa,...va]),l.z.instanceof(String)]);var E=(e,t,n)=>{let r={};if(typeof t==`object`&&(n=t,t=void 0),n={makeValid:!0,...n},typeof e==`number`||typeof e==`bigint`)t==null?(r.lower=typeof e==`bigint`?0n:0,r.upper=e):(r.lower=e,r.upper=t);else if(Array.isArray(e)){if(e.length!==2)throw Error(`bounds: expected array of length 2`);[r.lower,r.upper]=e}else r.lower=e.lower,r.upper=e.upper;return n?.makeValid?Aa(r):r};Object.freeze({lower:0,upper:0}),Object.freeze({lower:-1/0,upper:1/0}),Object.freeze({lower:0,upper:1}),Object.freeze({lower:-1,upper:1});var Aa=e=>e.lower>e.upper?{lower:e.upper,upper:e.lower}:e,ja=(e,t)=>{let n=E(e);return t<n.lower?n.lower:t>=n.upper?n.upper-(typeof n.upper==`number`?1:1n):t},Ma=(e,t)=>{let n=E(e);if(typeof t==`number`||typeof t==`bigint`)return t>=n.lower&&t<n.upper;let r=E(t);return r.lower>=n.lower&&r.upper<=n.upper},Na=e=>({lower:Math.min(...e.map(e=>E(e).lower)),upper:Math.max(...e.map(e=>E(e).upper))}),Pa=(e,t,n)=>{let r=e.map(e=>E(e)),i=n>0?1:n<0?-1:0;if(i===0)return t;let a=n,o=t;for(;ra(a,0)===!1;){let e=r.findIndex(e=>i>0?o>=e.lower&&o<e.upper:o>e.lower&&o<=e.upper);if(e!==-1){let t=r[e],n;if(n=i>0?ta(t.upper,o):ta(o,t.lower),n>0){let e=ia(oa(a),n);if(o=na(o,i>0?e:-e),a=ta(a,i>0?e:-e),ra(a,0))return o;continue}}if(i>0){let e=r.filter(e=>e.lower>o);if(e.length>0)o=e[0].lower;else return o}else{let e=r.filter(e=>e.upper<o);if(e.length>0)o=e[e.length-1].upper;else return o}}return o},Fa=(e,t,n)=>{let r=e.map(e=>E(e));if(t===n)return typeof t==`bigint`?0n:0;let i=E(t<n?[t,n]:[n,t]),a=typeof t==`bigint`?0n:0;for(let e of r){let t=e.lower>i.lower?e.lower:i.lower,n=e.upper<i.upper?e.upper:i.upper;if(t<n){let e=n-t;a+=e}}return a};l.z.object({x:ha.or(ya),y:_a.or(ya)});var Ia=l.z.object({x:ha,y:_a}),La=Object.freeze({x:`left`,y:`top`}),Ra=Object.freeze({x:`right`,y:`top`}),za=Object.freeze({x:`left`,y:`bottom`}),Ba=Object.freeze({x:`right`,y:`bottom`}),Va=Object.freeze({x:`center`,y:`center`}),Ha=Object.freeze({x:`center`,y:`top`}),Ua=Object.freeze({x:`center`,y:`bottom`}),Wa=Object.freeze({x:`right`,y:`center`}),Ga=Object.freeze({x:`left`,y:`center`});Object.freeze([Ga,Wa,Ha,Ua,La,Ra,za,Ba,Va]);var Ka=(e,t)=>e.x===t.x&&e.y===t.y,qa=e=>[e.x,e.y];l.z.enum([`top`,`right`,`bottom`,`left`]);var Ja=l.z.object({x:l.z.number(),y:l.z.number()}),Ya=l.z.union([l.z.number(),Ja,la,Da,Oa,Ea]),Xa=(e,t)=>{if(typeof e==`string`){if(t===void 0)throw Error(`The y coordinate must be given.`);return e===`x`?{x:t,y:0}:{x:0,y:t}}return typeof e==`number`?{x:e,y:t??e}:Array.isArray(e)?{x:e[0],y:e[1]}:`signedWidth`in e?{x:e.signedWidth,y:e.signedHeight}:`clientX`in e?{x:e.clientX,y:e.clientY}:`width`in e?{x:e.width,y:e.height}:{x:e.x,y:e.y}},Za=Object.freeze({x:0,y:0});Object.freeze({x:1,y:1}),Object.freeze({x:1/0,y:1/0}),Object.freeze({x:NaN,y:NaN});var Qa=(e,t)=>{let n=Xa(e);return{x:n.x+t,y:n.y}},$a=(e,t)=>{let n=Xa(e);return{x:n.x,y:n.y+t}},eo=(e,t,n,...r)=>{if(typeof t==`string`){if(typeof n!=`number`)throw Error(`The value must be a number.`);return t===`x`?Qa(e,n):$a(e,n)}if(typeof t==`object`&&`x`in t&&typeof t.x==`string`){let r=Xa(n),i=Xa(e);return t.x===`left`?r.x=-r.x:t.x===`center`&&(r.x=0),t.y===`top`?r.y=-r.y:t.y===`center`&&(r.y=0),{x:i.x+r.x,y:i.y+r.y}}return[e,t,n??Za,...r].reduce((e,t)=>{let n=Xa(t);return{x:e.x+n.x,y:e.y+n.y}},Za)},to=l.z.union([l.z.number(),l.z.string()]);l.z.object({top:to,left:to,width:to,height:to}),l.z.object({left:l.z.number(),top:l.z.number(),right:l.z.number(),bottom:l.z.number()}),l.z.object({one:Ja,two:Ja,root:Ia});var no=(e,t,n=0,r=0,i)=>{let a={one:{...Za},two:{...Za},root:i??La};if(typeof e==`number`){if(typeof t!=`number`)throw Error(`Box constructor called with invalid arguments`);return a.one={x:e,y:t},a.two={x:a.one.x+n,y:a.one.y+r},a}return`one`in e&&`two`in e&&`root`in e?{...e,root:i??e.root}:(`getBoundingClientRect`in e&&(e=e.getBoundingClientRect()),`left`in e?(a.one={x:e.left,y:e.top},a.two={x:e.right,y:e.bottom},a):(a.one=e,t==null?a.two={x:a.one.x+n,y:a.one.y+r}:typeof t==`number`?a.two={x:a.one.x+t,y:a.one.y+n}:`width`in t?a.two={x:a.one.x+t.width,y:a.one.y+t.height}:`signedWidth`in t?a.two={x:a.one.x+t.signedWidth,y:a.one.y+t.signedHeight}:a.two=t,a))},ro=(e,t)=>{let n=no(e);return{x:t.x===`center`?co(n).x:io(n,t.x),y:t.y===`center`?co(n).y:io(n,t.y)}},io=(e,t)=>{let n=no(e),r=qa(n.root).includes(t)?Math.min:Math.max;return ma.includes(t)?r(n.one.x,n.two.x):r(n.one.y,n.two.y)},ao=e=>{let t=no(e);return t.two.x-t.one.x},oo=e=>{let t=no(e);return t.two.y-t.one.y},so=e=>ro(e,La),co=e=>eo(so(e),{x:ao(e)/2,y:oo(e)/2}),lo=e=>{let t=no(e);return{lower:t.one.x,upper:t.two.x}},uo=e=>{let t=no(e);return{lower:t.one.y,upper:t.two.y}},fo=e=>typeof e!=`object`||!e?!1:`one`in e&&`two`in e&&`root`in e;l.z.union([Da,Oa,Ja,la]);var po=(e,t,n)=>t!==void 0&&e<t?t:n!==void 0&&e>n?n:e;l.z.object({offset:Ya,scale:Ya}),l.z.object({offset:l.z.number(),scale:l.z.number()});var mo=e=>(t,n,r,i)=>n===`dimension`?[t,r]:[t,i?r-e:r+e],ho=e=>(t,n,r,i)=>[t,i?r/e:r*e],go=e=>(t,n,r)=>{if(t===null)return[e,r];let{lower:i,upper:a}=t,{lower:o,upper:s}=e,c=a-i,l=s-o;return n===`dimension`?[e,l/c*r]:[e,(r-i)*(l/c)+o]},_o=e=>(t,n,r)=>[e,r],vo=()=>(e,t,n)=>{if(e===null)throw Error(`cannot invert without bounds`);if(t===`dimension`)return[e,n];let{lower:r,upper:i}=e;return[e,i-(n-r)]},yo=e=>(t,n,r)=>{let{lower:i,upper:a}=e;return r=po(r,i,a),[t,r]},bo=class e{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(t){return new e().translate(t)}static magnify(t){return new e().magnify(t)}static scale(t,n){return new e().scale(t,n)}translate(e){let t=this.new(),n=mo(e);return n.type=`translate`,t.ops.push(n),t}magnify(e){let t=this.new(),n=ho(e);return n.type=`magnify`,t.ops.push(n),t}scale(e,t){let n=E(e,t),r=this.new(),i=go(n);return i.type=`scale`,r.ops.push(i),r}clamp(e,t){let n=E(e,t),r=this.new(),i=yo(n);return i.type=`clamp`,r.ops.push(i),r}reBound(e,t){let n=E(e,t),r=this.new(),i=_o(n);return i.type=`re-bound`,r.ops.push(i),r}invert(){let e=vo();e.type=`invert`;let t=this.new();return t.ops.push(e),t}pos(e){return this.exec(`position`,e)}dim(e){return this.exec(`dimension`,e)}new(){let t=new e;return t.ops=this.ops.slice(),t.reversed=this.reversed,t}exec(e,t){return this.currBounds=null,this.ops.reduce(([t,n],r)=>r(t,e,n,this.reversed),[null,t])[1]}reverse(){let e=this.new();e.ops.reverse();let t=[];return e.ops.forEach((n,r)=>{if(n.type===`scale`||t.some(([e,t])=>r>=e&&r<=t))return;let i=e.ops.findIndex((e,t)=>e.type===`scale`&&t>r);i!==-1&&t.push([r,i])}),t.forEach(([t,n])=>{let r=e.ops.slice(t,n);r.unshift(e.ops[n]),e.ops.splice(t,n-t+1,...r)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new e};(class e{x;y;currRoot;constructor(e=new bo,t=new bo,n=null){this.x=e,this.y=t,this.currRoot=n}static translate(t,n){return new e().translate(t,n)}static translateX(t){return new e().translateX(t)}static translateY(t){return new e().translateY(t)}static clamp(t){return new e().clamp(t)}static magnify(t){return new e().magnify(t)}static scale(t){return new e().scale(t)}static reBound(t){return new e().reBound(t)}translate(e,t){let n=Xa(e,t),r=this.copy();return r.x=this.x.translate(n.x),r.y=this.y.translate(n.y),r}translateX(e){let t=this.copy();return t.x=this.x.translate(e),t}translateY(e){let t=this.copy();return t.y=this.y.translate(e),t}magnify(e){let t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){let t=this.copy();if(fo(e)){let n=this.currRoot;return t.currRoot=e.root,n!=null&&!Ka(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(lo(e)),t.y=t.y.scale(uo(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){let t=this.copy();return t.x=this.x.reBound(lo(e)),t.y=this.y.reBound(uo(e)),t}clamp(e){let t=this.copy();return t.x=this.x.clamp(lo(e)),t.y=this.y.clamp(uo(e)),t}copy(){let t=new e;return t.currRoot=this.currRoot,t.x=this.x,t.y=this.y,t}reverse(){let 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 no(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 e});var xo=C({ALIGNMENTS:()=>Sa,CENTER_LOCATIONS:()=>va,DIRECTIONS:()=>ua,LOCATIONS:()=>ba,ORDERS:()=>wa,OUTER_LOCATIONS:()=>fa,X_LOCATIONS:()=>ma,Y_LOCATIONS:()=>ga,alignmentZ:()=>Ca,boundsZ:()=>ka,centerLocationZ:()=>ya,clientXyZ:()=>Ea,dimensionsZ:()=>Da,directionZ:()=>da,locationZ:()=>xa,orderZ:()=>Ta,outerLocationZ:()=>pa,signedDimensionsZ:()=>Oa,xLocationZ:()=>ha,xyZ:()=>Ja,yLocationZ:()=>_a});Ja.extend({root:Ia,units:l.default.object({x:l.default.enum([`px`,`decimal`]),y:l.default.enum([`px`,`decimal`])})}).partial({root:!0,units:!0});var So=l.z.enum([`static`,`dynamic`]),Co=365,wo=30,To=l.z.union([l.z.tuple([l.z.int()]),l.z.tuple([l.z.int(),l.z.int().min(1).max(12)]),l.z.tuple([l.z.int(),l.z.int().min(1).max(12),l.z.int().min(1).max(31)])]),Eo=(e,t)=>{let n=new D(t);if(![O.DAY,O.HOUR,O.MINUTE,O.SECOND,O.MILLISECOND,O.MICROSECOND,O.NANOSECOND].some(e=>e.equals(n)))throw Error(`Invalid argument for remainder. Must be an even TimeSpan or Timestamp`);let r=e.valueOf()%n.valueOf();return e instanceof D?new D(r):new O(r)},D=class e extends mi{constructor(t,n=`UTC`){if(t==null)super(e.now().valueOf());else if(t instanceof Date)super(BigInt(t.getTime())*e.MILLISECOND.valueOf());else if(typeof t==`string`)super(e.parseDateTimeString(t,n).valueOf());else if(Array.isArray(t))super(e.parseDate(t));else{let r=0n;t instanceof Number&&(t=t.valueOf()),n===`local`&&(r=e.utcOffset.valueOf()),typeof t==`number`&&(isFinite(t)?t=t===$i?Zi:Math.trunc(t):(isNaN(t)&&(t=0),t=t===1/0?e.MAX:e.MIN)),T(t)&&(t=t.value),super(BigInt(t.valueOf())+r)}}static parseDate([t=1970,n=1,r=1]){let i=new Date(t,n-1,r,0,0,0,0);return new e(BigInt(i.getTime())*e.MILLISECOND.valueOf()).truncate(e.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(t,n=`UTC`){let[r,i,a]=t.split(`:`),o=`00`,s=`00`;a!=null&&([o,s]=a.split(`.`));let c=e.hours(parseInt(r??`00`,10)).add(e.minutes(parseInt(i??`00`,10))).add(e.seconds(parseInt(o??`00`,10))).add(e.milliseconds(parseInt(s??`00`,10)));return n===`local`&&(c=c.add(e.utcOffset)),c.valueOf()}static parseDateTimeString(t,n=`UTC`){if(!t.includes(`/`)&&!t.includes(`-`))return e.parseTimeString(t,n);if(t.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let r=t,i=0;if(t.includes(`.`)){let e=t.split(`.`);r=e[0];let n=e[1]||`0`;i=parseInt(n.padEnd(3,`0`).slice(0,3),10)}let a=n===`local`?new Date(r.replace(`T`,` `)):new Date(`${r}Z`);return BigInt(a.getTime())*e.MILLISECOND.valueOf()+BigInt(i)*e.MILLISECOND.valueOf()}let r=new Date(t);return t.includes(`:`)||r.setUTCHours(0,0,0,0),new e(BigInt(r.getTime())*e.MILLISECOND.valueOf(),n).valueOf()}toISOString(t=`UTC`){if(t===`UTC`)return this.date().toISOString();let n=this.date(),r=new O(BigInt(n.getTimezoneOffset())*e.MINUTE.valueOf());return this.sub(r).date().toISOString()}timeString(e=!1,t=`UTC`){let n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){let e=this.date();return`${e.toLocaleString(`default`,{month:`short`})} ${e.toLocaleString(`default`,{day:`numeric`})}`}static get utcOffset(){return new O(BigInt(new Date().getTimezoneOffset())*e.MINUTE.valueOf())}static since(t){return new e().span(t)}date(){return new Date(this.milliseconds)}equals(t){return this.valueOf()===new e(t).valueOf()}span(e){return this.range(e).span}range(e){return new A(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(t){return this.valueOf()>new e(t).valueOf()}afterEq(t){return this.valueOf()>=new e(t).valueOf()}before(t){return this.valueOf()<new e(t).valueOf()}beforeEq(t){return this.valueOf()<=new e(t).valueOf()}add(t){return new e(na(this.valueOf(),new O(t).valueOf()))}sub(t){return new e(ta(this.valueOf(),new O(t).valueOf()))}get hours(){return Number(this.valueOf())/Number(O.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(O.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(O.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(O.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(e.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(e.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}get localYear(){return this.date().getFullYear()}setYear(t){let n=this.date();return n.setUTCFullYear(t),new e(n)}setLocalYear(t){let n=this.date();return n.setFullYear(t),new e(n)}get month(){return this.date().getUTCMonth()}get localMonth(){return this.date().getMonth()}setMonth(t){let n=this.date();return n.setUTCMonth(t),new e(n)}setLocalMonth(t){let n=this.date();return n.setMonth(t),new e(n)}get day(){return this.date().getUTCDate()}get localDay(){return this.date().getDate()}setDay(t){let n=this.date();return n.setUTCDate(t),new e(n)}setLocalDay(t){let n=this.date();return n.setDate(t),new e(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(t){let n=this.date();return n.setHours(t),new e(n)}setHour(t){let n=this.date();return n.setUTCHours(t),new e(n)}get minute(){return this.date().getUTCMinutes()}get localMinute(){return this.date().getMinutes()}setMinute(t){let n=this.date();return n.setUTCMinutes(t),new e(n)}setLocalMinute(t){let n=this.date();return n.setMinutes(t),new e(n)}get second(){return this.date().getUTCSeconds()}get localSecond(){return this.date().getSeconds()}setSecond(t){let n=this.date();return n.setUTCSeconds(t),new e(n)}setLocalSecond(t){let n=this.date();return n.setSeconds(t),new e(n)}get millisecond(){return this.date().getUTCMilliseconds()}get localMillisecond(){return this.date().getMilliseconds()}setMillisecond(t){let n=this.date();return n.setUTCMilliseconds(t),new e(n)}setLocalMillisecond(t){let n=this.date();return n.setMilliseconds(t),new e(n)}toString(e=`ISO`,t=`UTC`){switch(e){case`ISODate`:return this.toISOString(t).slice(0,10);case`ISOTime`:return this.toISOString(t).slice(11,23);case`time`:return this.timeString(!1,t);case`preciseTime`:return this.timeString(!0,t);case`date`:return this.dateString();case`preciseDate`:return`${this.dateString()} ${this.timeString(!0,t)}`;case`dateTime`:return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}remainder(e){return Eo(this,e)}get isToday(){return this.truncate(O.DAY).equals(e.now().truncate(O.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(O.days(30))?`shortDate`:e.greaterThanOrEqual(O.DAY)?`dateTime`:e.greaterThanOrEqual(O.HOUR)?`time`:e.greaterThanOrEqual(O.SECOND)?`preciseTime`:`ISOTime`}static now(){return new e(new Date)}static max(...t){let n=e.MIN;for(let r of t){let t=new e(r);t.after(n)&&(n=t)}return n}static min(...t){let n=e.MAX;for(let r of t){let t=new e(r);t.before(n)&&(n=t)}return n}static nanoseconds(t,n=`UTC`){return new e(t,n)}static NANOSECOND=e.nanoseconds(1);static microseconds(t,n=`UTC`){return e.nanoseconds(t*1e3,n)}static MICROSECOND=e.microseconds(1);static milliseconds(t,n=`UTC`){return e.microseconds(t*1e3,n)}static MILLISECOND=e.milliseconds(1);static seconds(t,n=`UTC`){return e.milliseconds(t*1e3,n)}static SECOND=e.seconds(1);static minutes(t,n=`UTC`){return e.seconds(t*60,n)}static MINUTE=e.minutes(1);static hours(t,n=`UTC`){return e.minutes(t*60,n)}static HOUR=e.hours(1);static days(t,n=`UTC`){return e.hours(t*24,n)}static DAY=e.days(1);static MAX=new e(Zi);static MIN=new e(0);static ZERO=new e(0);static z=l.z.union([l.z.instanceof(e),l.z.object({value:l.z.bigint()}).transform(t=>new e(t.value)),l.z.string().transform(t=>new e(BigInt(t))),l.z.number().transform(t=>new e(t)),l.z.bigint().transform(t=>new e(t)),l.z.date().transform(t=>new e(t)),l.z.custom(e=>e instanceof O).transform(t=>new e(t)),To.transform(t=>new e(t))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}},O=class e extends mi{constructor(e){typeof e==`number`&&(e=Math.trunc(e.valueOf())),T(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(t){return t instanceof e?t:t instanceof Do?t.period:t instanceof D?new e(t):(T(t)&&(t=t.value),[`number`,`bigint`].includes(typeof t)?e.seconds(t):new e(t))}static fromMilliseconds(t){return t instanceof e?t:t instanceof Do?t.period:t instanceof D?new e(t):(T(t)&&(t=t.value),[`number`,`bigint`].includes(typeof t)?e.milliseconds(t):new e(t))}valueOf(){return this.value}lessThan(t){return this.valueOf()<new e(t).valueOf()}greaterThan(t){return this.valueOf()>new e(t).valueOf()}lessThanOrEqual(t){return this.valueOf()<=new e(t).valueOf()}greaterThanOrEqual(t){return this.valueOf()>=new e(t).valueOf()}remainder(e){return Eo(this,e)}truncate(t){return new e(BigInt(Math.trunc(Number(this.valueOf()/t.valueOf())))*t.valueOf())}toString(t=`full`){if(t===`semantic`)return this.toSemanticString();let n=this.truncate(e.DAY),r=this.truncate(e.HOUR),i=this.truncate(e.MINUTE),a=this.truncate(e.SECOND),o=this.truncate(e.MILLISECOND),s=this.truncate(e.MICROSECOND),c=this.truncate(e.NANOSECOND),l=n,u=r.sub(n),d=i.sub(r),f=a.sub(i),p=o.sub(a),m=s.sub(o),h=c.sub(s),g=``;return l.isZero||(g+=`${l.days}d `),u.isZero||(g+=`${u.hours}h `),d.isZero||(g+=`${d.minutes}m `),f.isZero||(g+=`${f.seconds}s `),p.isZero||(g+=`${p.milliseconds}ms `),m.isZero||(g+=`${m.microseconds}µs `),h.isZero||(g+=`${h.nanoseconds}ns`),g.trim()}toSemanticString(){let t=new e(this.valueOf()<0n?-this.valueOf():this.valueOf()),n=this.valueOf()<0n;if(t.valueOf()===0n)return`0s`;if(t.lessThan(e.SECOND))return`< 1s`;let r=t.days,i=t.hours,a=t.minutes,o=t.seconds,s=Math.floor(r/Co),c=Math.floor(r/wo),l=Math.floor(r/7),u=Math.floor(r),d=Math.floor(i),f=Math.floor(a),p=Math.floor(o),m=n?`-`:``;if(s>=1){let e=`${s}y`;if(s<2){let t=Math.floor(r%Co/wo);t>0&&(e+=` ${t}mo`)}return m+e}if(l>=1&&r<wo&&r%7==0){let e=`${l}w`,t=Math.floor(r%7),n=Math.floor(i-l*7*24);return l<2&&(t>0?e+=` ${t}d`:n>0&&n<24&&(e+=` ${n}h`)),m+e}if(c>=1){let e=`${c}mo`;if(c<3){let t=Math.floor(r%wo);t>0&&(e+=` ${t}d`)}return m+e}if(l>=1){let e=`${l}w`,t=Math.floor(r%7),n=Math.floor(i-l*7*24);return l<2&&(t>0?e+=` ${t}d`:n>0&&n<24&&(e+=` ${n}h`)),m+e}if(u>=1){let e=`${u}d`,t=Math.floor(i-u*24);return u<2&&t>0&&(e+=` ${t}h`),m+e}if(d>=1){let e=`${d}h`;if(d<3){let t=Math.floor(a-d*60);t>0&&(e+=` ${t}m`)}return m+e}if(f>=1){let e=`${f}m`;if(f<5){let t=Math.floor(o-f*60);t>0&&(e+=` ${t}s`)}return m+e}return`${m}${p}s`}mult(t){return new e(sa(this.valueOf(),t))}div(t){return new e(ca(this.valueOf(),t))}get days(){return Number(this.valueOf())/Number(e.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(e.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(e.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(e.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(e.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(e.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(t){return this.valueOf()===new e(t).valueOf()}add(t){return new e(this.valueOf()+new e(t).valueOf())}sub(t){return new e(this.valueOf()-new e(t).valueOf())}static nanoseconds(t=1){return new e(t)}static NANOSECOND=e.nanoseconds(1);static microseconds(t=1){return e.nanoseconds(sa(t,1e3))}static MICROSECOND=e.microseconds(1);static milliseconds(t=1){return e.microseconds(sa(t,1e3))}static MILLISECOND=e.milliseconds(1);static seconds(t=1){return e.milliseconds(sa(t,1e3))}static SECOND=e.seconds(1);static minutes(t=1){return e.seconds(sa(t,60))}static MINUTE=e.minutes(1);static hours(t){return e.minutes(sa(t,60))}static HOUR=e.hours(1);static days(t){return e.hours(sa(t,24))}static DAY=e.days(1);static MAX=new e(Zi);static MIN=new e(0);static ZERO=new e(0);static z=l.z.union([l.z.object({value:l.z.bigint()}).transform(t=>new e(t.value)),l.z.string().transform(t=>new e(BigInt(t))),l.z.number().transform(t=>new e(t)),l.z.bigint().transform(t=>new e(t)),l.z.instanceof(e),l.z.instanceof(D).transform(t=>new e(t)),l.z.custom(e=>e instanceof Do).transform(t=>new e(t))])},Do=class e extends mi{constructor(e){T(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(t){return this.valueOf()===new e(t).valueOf()}get period(){return O.seconds(1/this.valueOf())}sampleCount(e){return new O(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new k(t).valueOf()}span(e){return O.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/new k(t).valueOf())}add(t){return new e(na(this.valueOf(),new e(t).valueOf()))}sub(t){return new e(ta(this.valueOf(),new e(t).valueOf()))}mult(t){return new e(sa(this.valueOf(),t))}div(t){return new e(ca(this.valueOf(),t))}static hz(t){return new e(t)}static khz(t){return e.hz(t*1e3)}static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)])},k=class e extends mi{constructor(e){T(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new Oo(e*this.valueOf())}add(t){return new e(na(this.valueOf(),new e(t).valueOf()))}sub(t){return new e(ta(this.valueOf(),new e(t).valueOf()))}mult(t){return new e(sa(this.valueOf(),t))}div(t){return new e(ca(this.valueOf(),t))}static UNKNOWN=new e(0);static BIT128=new e(16);static BIT64=new e(8);static BIT32=new e(4);static BIT16=new e(2);static BIT8=new e(1);static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)])},A=class e{start;end;constructor(e,t){typeof e==`object`&&`start`in e?(this.start=new D(e.start),this.end=new D(e.end)):(this.start=new D(e),this.end=new D(t))}get span(){return new O(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,t=O.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),r=this.end.sub(e.end).valueOf();return n<0&&(n=-n),r<0&&(r=-r),n<=t.valueOf()&&r<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString(`preciseDate`)} - ${this.span.toString()}`}overlapsWith(e,t=O.ZERO){e=e.makeValid();let n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;let r=D.max(n.start,e.start),i=D.min(n.end,e.end);return i.before(r)?!1:new O(i.sub(r)).greaterThanOrEqual(t)}contains(t){return t instanceof e?this.contains(t.start)&&this.contains(t.end):this.start.beforeEq(t)&&this.end.after(t)}boundBy(t){let n=new e(this.start,this.end);return t.start.after(this.start)&&(n.start=t.start),t.start.after(this.end)&&(n.end=t.start),t.end.before(this.end)&&(n.end=t.end),t.end.before(this.start)&&(n.start=t.end),n}static max(...t){return new e(D.min(...t.map(e=>e.start)),D.max(...t.map(e=>e.end)))}static MAX=new e(D.MIN,D.MAX);static ZERO=new e(D.ZERO,D.ZERO);static z=l.z.union([l.z.object({start:D.z,end:D.z}).transform(t=>new e(t.start,t.end)),l.z.instanceof(e)]);static boundedZ=e.z.refine(({isValid:e})=>e,{message:`Time range start time must be before or equal to time range end time`}).refine(({end:e})=>e.valueOf()<=Zi,{message:`Time range end time must be less than or equal to the maximum value of an int64`}).refine(({start:e})=>e.valueOf()>=Xi,{message:`Time range start time must be greater than or equal to the minimum value of an int64`});static sort(e,t){return D.sort(e.start,t.start)||D.sort(e.end,t.end)}static merge(...t){return e.max(...t.map(t=>new e(t).makeValid()))}},j=class e extends mi{constructor(t){if(T(t)&&(t=t.value),t instanceof e||typeof t==`string`||typeof t.valueOf()==`string`)super(t.valueOf());else{let n=e.ARRAY_CONSTRUCTOR_DATA_TYPES.get(t.constructor.name);if(n==null)throw Error(`unable to find data type for ${t.toString()}`);super(n.valueOf())}}get Array(){let t=e.ARRAY_CONSTRUCTORS.get(this.toString());if(t==null)throw Error(`unable to find array constructor for ${this.valueOf()}`);return t}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(e=>this.equals(e))}toString(t=!1){return t?e.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(e.JSON)||this.equals(e.STRING)||this.equals(e.BYTES)}get isNumeric(){return!this.isVariable&&!this.equals(e.UUID)}get isInteger(){let e=this.toString();return e.startsWith(`int`)||e.startsWith(`uint`)}get isFloat(){return this.toString().startsWith(`float`)}get density(){let t=e.DENSITIES.get(this.toString());if(t==null)throw Error(`unable to find density for ${this.valueOf()}`);return t}get isUnsignedInteger(){return this.equals(e.UINT8)||this.equals(e.UINT16)||this.equals(e.UINT32)||this.equals(e.UINT64)}get isSignedInteger(){return this.equals(e.INT8)||this.equals(e.INT16)||this.equals(e.INT32)||this.equals(e.INT64)}canSafelyCastTo(t){return this.equals(t)?!0:!this.isNumeric||!t.isNumeric||this.isVariable||t.isVariable||this.isUnsignedInteger&&t.isSignedInteger?!1:this.isFloat?t.isFloat&&this.density.valueOf()<=t.density.valueOf():this.equals(e.INT32)&&t.equals(e.FLOAT64)||this.equals(e.INT8)&&t.equals(e.FLOAT32)?!0:this.isInteger&&t.isInteger?this.density.valueOf()<=t.density.valueOf()&&this.isUnsignedInteger===t.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return e.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new e(`unknown`);static FLOAT64=new e(`float64`);static FLOAT32=new e(`float32`);static INT64=new e(`int64`);static INT32=new e(`int32`);static INT16=new e(`int16`);static INT8=new e(`int8`);static UINT64=new e(`uint64`);static UINT32=new e(`uint32`);static UINT16=new e(`uint16`);static UINT8=new e(`uint8`);static TIMESTAMP=new e(`timestamp`);static UUID=new e(`uuid`);static STRING=new e(`string`);static JSON=new e(`json`);static BYTES=new e(`bytes`);static ARRAY_CONSTRUCTORS=new Map([[e.UINT8.toString(),Uint8Array],[e.UINT16.toString(),Uint16Array],[e.UINT32.toString(),Uint32Array],[e.UINT64.toString(),BigUint64Array],[e.FLOAT32.toString(),Float32Array],[e.FLOAT64.toString(),Float64Array],[e.INT8.toString(),Int8Array],[e.INT16.toString(),Int16Array],[e.INT32.toString(),Int32Array],[e.INT64.toString(),BigInt64Array],[e.TIMESTAMP.toString(),BigInt64Array],[e.STRING.toString(),Uint8Array],[e.JSON.toString(),Uint8Array],[e.UUID.toString(),Uint8Array],[e.BYTES.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,e.UINT8],[Uint16Array.name,e.UINT16],[Uint32Array.name,e.UINT32],[BigUint64Array.name,e.UINT64],[Float32Array.name,e.FLOAT32],[Float64Array.name,e.FLOAT64],[Int8Array.name,e.INT8],[Int16Array.name,e.INT16],[Int32Array.name,e.INT32],[BigInt64Array.name,e.INT64]]);static DENSITIES=new Map([[e.UINT8.toString(),k.BIT8],[e.UINT16.toString(),k.BIT16],[e.UINT32.toString(),k.BIT32],[e.UINT64.toString(),k.BIT64],[e.FLOAT32.toString(),k.BIT32],[e.FLOAT64.toString(),k.BIT64],[e.INT8.toString(),k.BIT8],[e.INT16.toString(),k.BIT16],[e.INT32.toString(),k.BIT32],[e.INT64.toString(),k.BIT64],[e.TIMESTAMP.toString(),k.BIT64],[e.STRING.toString(),k.UNKNOWN],[e.JSON.toString(),k.UNKNOWN],[e.UUID.toString(),k.BIT128],[e.BYTES.toString(),k.UNKNOWN]]);static ALL=[e.UNKNOWN,e.UINT8,e.UINT16,e.UINT32,e.UINT64,e.INT8,e.INT16,e.INT32,e.INT64,e.FLOAT32,e.FLOAT64,e.TIMESTAMP,e.UUID,e.STRING,e.JSON,e.BYTES];static SHORT_STRINGS=new Map([[e.UINT8.toString(),`u8`],[e.UINT16.toString(),`u16`],[e.UINT32.toString(),`u32`],[e.UINT64.toString(),`u64`],[e.INT8.toString(),`i8`],[e.INT16.toString(),`i16`],[e.INT32.toString(),`i32`],[e.INT64.toString(),`i64`],[e.FLOAT32.toString(),`f32`],[e.FLOAT64.toString(),`f64`],[e.TIMESTAMP.toString(),`ts`],[e.UUID.toString(),`uuid`],[e.STRING.toString(),`str`],[e.JSON.toString(),`json`],[e.BYTES.toString(),`bytes`]]);static BIG_INT_TYPES=[e.INT64,e.UINT64,e.TIMESTAMP];static z=l.z.union([l.z.string().transform(t=>new e(t)),l.z.instanceof(e)])},Oo=class e extends mi{constructor(e){T(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return T(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return T(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(t){return T(t)&&(t=t.value),new e(na(this.valueOf(),t.valueOf()))}sub(t){return T(t)&&(t=t.value),new e(ta(this.valueOf(),t.valueOf()))}mult(t){return new e(sa(this.valueOf(),t))}div(t){return new e(ca(this.valueOf(),t))}truncate(t){return new e(Math.trunc(this.valueOf()/new e(t).valueOf())*new e(t).valueOf())}remainder(t){return e.bytes(this.valueOf()%new e(t).valueOf())}get gigabytes(){return this.valueOf()/e.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/e.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/e.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/e.TERABYTE.valueOf()}toString(){let t=this.truncate(e.TERABYTE),n=this.truncate(e.GIGABYTE),r=this.truncate(e.MEGABYTE),i=this.truncate(e.KILOBYTE),a=this.truncate(e.BYTE),o=t,s=n.sub(t),c=r.sub(n),l=i.sub(r),u=a.sub(i),d=``;return o.isZero||(d+=`${o.terabytes}TB `),s.isZero||(d+=`${s.gigabytes}GB `),c.isZero||(d+=`${c.megabytes}MB `),l.isZero||(d+=`${l.kilobytes}KB `),(!u.isZero||d===``)&&(d+=`${u.valueOf()}B`),d.trim()}static bytes(t=1){return new e(t)}static BYTE=new e(1);static kilobytes(t=1){return e.bytes(new e(t).valueOf()*1e3)}static KILOBYTE=e.kilobytes(1);static megabytes(t=1){return e.kilobytes(new e(t).valueOf()*1e3)}static MEGABYTE=e.megabytes(1);static gigabytes(t=1){return e.megabytes(new e(t).valueOf()*1e3)}static GIGABYTE=e.gigabytes(1);static terabytes(t){return e.gigabytes(new e(t).valueOf()*1e3)}static TERABYTE=e.terabytes(1);static ZERO=new e(0);static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)]);get isZero(){return this.valueOf()===0}},ko=l.z.object({start:l.z.number(),end:l.z.number()}),Ao=l.z.union([l.z.instanceof(Uint8Array),l.z.instanceof(Uint16Array),l.z.instanceof(Uint32Array),l.z.instanceof(BigUint64Array),l.z.instanceof(Float32Array),l.z.instanceof(Float64Array),l.z.instanceof(Int8Array),l.z.instanceof(Int16Array),l.z.instanceof(Int32Array),l.z.instanceof(BigInt64Array)]),jo=e=>{let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===`bigint`||e instanceof D||e instanceof O||e instanceof Date},Mo=(e,t,n,r=0)=>e.usesBigInt&&!t.usesBigInt?Number(n)-Number(r):!e.usesBigInt&&t.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):ta(n,r),No=A.z,Po=D.z,Fo=O.z,Io=Do.z,Lo=Oo.z,Ro=j.z,zo=A.boundedZ,Bo=/^(?:[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 Vo(e){return typeof e==`string`&&Bo.test(e)}var M=[];for(let e=0;e<256;++e)M.push((e+256).toString(16).slice(1));function Ho(e,t=0){return(M[e[t+0]]+M[e[t+1]]+M[e[t+2]]+M[e[t+3]]+`-`+M[e[t+4]]+M[e[t+5]]+`-`+M[e[t+6]]+M[e[t+7]]+`-`+M[e[t+8]]+M[e[t+9]]+`-`+M[e[t+10]]+M[e[t+11]]+M[e[t+12]]+M[e[t+13]]+M[e[t+14]]+M[e[t+15]]).toLowerCase()}function Uo(e,t=0){let n=Ho(e,t);if(!Vo(n))throw TypeError(`Stringified UUID is invalid`);return n}typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var Wo=(e,t)=>Uo(e,t),Go=-1,Ko={[Symbol.iterator]:()=>Ko,next:()=>({done:!0,value:void 0})},qo=l.z.string().transform(e=>new Uint8Array(atob(e).split(``).map(e=>e.charCodeAt(0))).buffer),Jo=l.z.union([l.z.null(),l.z.undefined()]).transform(()=>new Uint8Array().buffer),Yo=10,Xo=(e,t)=>{if(e===`number`&&!t.isNumeric)throw Error(`cannot convert series of type ${t.toString()} to number`);if(e===`bigint`&&!t.usesBigInt)throw Error(`cannot convert series of type ${t.toString()} to bigint`)},Zo=`sy_x_telem_series`,Qo=class e{key;discriminator=Zo;dataType;sampleOffset;gl;_data;timeRange=A.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Go;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=l.z.object({timeRange:A.z.optional(),dataType:j.z,alignment:l.z.coerce.bigint().optional(),data:l.z.union([qo,Jo,l.z.instanceof(ArrayBuffer),l.z.instanceof(Uint8Array)]),glBufferUsage:So.default(`static`).optional()});static z=e.crudeZ.transform(t=>new e(t));constructor(e){$o(e)&&(e={data:e}),e.data??=[];let{dataType:t,timeRange:n,sampleOffset:r=0,glBufferUsage:i=`static`,alignment:a=0n,alignmentMultiple:o=1n,key:s=Hi(),data:c}=e;if(es(c)){let e=c;this.key=e.key,this.dataType=e.dataType,this.sampleOffset=e.sampleOffset,this.gl=e.gl,this._data=e._data,this.timeRange=e.timeRange,this.alignment=e.alignment,this.alignmentMultiple=e.alignmentMultiple,this.cachedMin=e.cachedMin,this.cachedMax=e.cachedMax,this.writePos=e.writePos,this._refCount=e._refCount,this.cachedLength=e.cachedLength;return}let l=jo(c),u=Array.isArray(c);if(t!=null)this.dataType=new j(t);else if(c instanceof ArrayBuffer)throw Error(`cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.`);else if(u||l){let e=c;if(!l){if(c.length===0)throw Error(`cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.`);e=c[0]}if(typeof e==`string`)this.dataType=j.STRING;else if(typeof e==`number`)this.dataType=j.FLOAT64;else if(typeof e==`bigint`)this.dataType=j.INT64;else if(typeof e==`boolean`)this.dataType=j.UINT8;else if(e instanceof D||e instanceof Date||e instanceof D)this.dataType=j.TIMESTAMP;else if(typeof e==`object`)this.dataType=j.JSON;else throw Error(`cannot infer data type of ${typeof e} when constructing a Series from a JS array`)}else this.dataType=new j(c);if(!u&&!l)this._data=c;else if(u&&c.length===0)this._data=new this.dataType.Array([]).buffer;else{let e=l?[c]:c,t=e[0];(t instanceof D||t instanceof Date||t instanceof O)&&(e=e.map(e=>new D(e).valueOf())),this.dataType.equals(j.STRING)?(this.cachedLength=e.length,this._data=new TextEncoder().encode(`${e.join(`
9
- `)}\n`).buffer):this.dataType.equals(j.JSON)?(this.cachedLength=e.length,this._data=new TextEncoder().encode(`${e.map(e=>li.encodeString(e)).join(`
10
- `)}\n`).buffer):this.dataType.usesBigInt&&typeof t==`number`?this._data=new this.dataType.Array(e.map(e=>BigInt(Math.round(e)))).buffer:!this.dataType.usesBigInt&&typeof t==`bigint`?this._data=new this.dataType.Array(e.map(Number)).buffer:this._data=new this.dataType.Array(e).buffer}this.key=s,this.alignment=a,this.alignmentMultiple=o,this.sampleOffset=r??0,this.timeRange=n??A.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:t,dataType:n,...r}){if(t===0)throw Error(`[Series] - cannot allocate an array of length 0`);let i=new e({data:new new j(n).Array(t).buffer,dataType:n,...r});return i.writePos=0,i}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 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===Go)return 0;let t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===Go)return 0;let t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this.cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.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===Go?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
11
- `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(j.JSON))throw Error(`cannot parse non-JSON series as JSON`);return this.toStrings().map(t=>e.parse(li.decodeString(t)))}get byteCapacity(){return new Oo(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Go?this.byteCapacity:this.dataType.isVariable?new Oo(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength==null?this.dataType.isVariable?this.calculateCachedLength():this.writePos===Go?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos:this.cachedLength}calculateCachedLength(){if(!this.dataType.isVariable)throw Error(`cannot calculate length of a non-variable length data type`);let e=0,t=[0];return this.data.forEach((n,r)=>{n===Yo&&(e++,t.push(r+1))}),this._cachedIndexes=t,this.cachedLength=e,e}convert(t,n=0){if(this.dataType.equals(t))return this;let r=new t.Array(this.length);for(let e=0;e<this.length;e++)r[e]=Mo(this.dataType,t,this.data[e],n);return new e({data:r.buffer,dataType:t,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){return this.length===0?-1/0:(this.dataType.equals(j.TIMESTAMP)?this.cachedMax=this.data[this.data.length-1]:(this.dataType.usesBigInt,this.cachedMax=this.data.reduce((e,t)=>e>t?e:t)),this.cachedMax)}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw Error(`cannot calculate maximum on a variable length data type`);return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),na(this.cachedMax,this.sampleOffset))}calcRawMin(){return this.length===0?1/0:(this.dataType.equals(j.TIMESTAMP)?this.cachedMin=this.data[0]:(this.dataType.usesBigInt,this.cachedMin=this.data.reduce((e,t)=>e<t?e:t)),this.cachedMin)}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw Error(`cannot calculate minimum on a variable length data type`);return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),na(this.cachedMin,this.sampleOffset))}get bounds(){return E(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){let t=e.cachedMin??e.calcRawMin();t<this.cachedMin&&(this.cachedMin=t)}if(this.cachedMax!=null){let t=e.cachedMax??e.calcRawMax();t>this.cachedMax&&(this.cachedMax=t)}}atAlignment(e,t){let n=Number((e-this.alignment)/this.alignmentMultiple);if(n<0||n>=this.length){if(t===!0)throw Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(j.UUID))return this.atUUID(e,t);e<0&&(e=this.length+e);let n=this.data[e];if(n==null){if(t===!0)throw Error(`[series] - no value at index ${e}`);return}return na(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);let n=Wo(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){let n=0,r=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],r=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let t=0;t<this.data.length;t++)if(this.data[t]===Yo){if(e===0){r=t;break}n=t+1,e--}if(r===0&&(r=this.data.length),n>=r||e>0){if(t)throw Error(`[series] - no value at index ${e}`);return}}let i=this.data.slice(n,r);return this.dataType.equals(j.STRING)?new TextDecoder().decode(i):Xr(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let t=0,n=this.length-1,r=xi(e);for(;t<=n;){let i=Math.floor((t+n)/2),a=r(this.at(i,!0),e);if(a===0)return i;a<0?t=i+1:n=i-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(j.FLOAT32)&&!this.dataType.equals(j.UINT8))throw Error(`Only FLOAT32 and UINT8 arrays can be used in WebGL`);let{buffer:t,bufferUsage:n,prevBuffer:r}=this.gl;if(t??(this.gl.buffer=e.createBuffer()),this.writePos!==r)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Go){r===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);let t=this.dataType.density.size(r).valueOf(),n=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,t,n.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n===`static`?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Go}as(e){return Xo(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:ls(this.alignmentBounds.lower),upper:ls(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return E(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 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){let e=new ns(this);return this.dataType.equals(j.JSON)?new rs(e):e}return this.dataType.equals(j.UUID)?new is(this):new as(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new ts(this,e,t??this.length)}subAlignmentIterator(e,t){let n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),r=Math.ceil(Number(t-this.alignment)/Number(this.alignmentMultiple));return new ts(this,n,r)}subBytes(t,n){return t>=0&&(n==null||n>=this.byteLength.valueOf())?this:new e({data:this.data.subarray(t,n),dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}sliceSub(t,n,r){if(n<=0&&(r==null||r>=this.length))return this;let i;return i=t?this.data.subarray(n,r):this.data.slice(n,r),new e({data:i,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(t){return new e({data:this.buffer,dataType:this.dataType,timeRange:A.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:`static`,alignment:t})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(e=>e.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=`,`;e+=`...,`;for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=`,`)}return e+=`])`,e}},$o=e=>e==null?!1:Array.isArray(e)||e instanceof ArrayBuffer||ArrayBuffer.isView(e)&&!(e instanceof DataView)||e instanceof Qo?!0:jo(e),es=Ui(Zo,Qo),ts=class{series;end;index;constructor(e,t,n){this.series=e;let r=E(0,e.length+1);this.end=ja(r,n),this.index=ja(r,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},ns=class{series;index;decoder;constructor(e){if(!e.dataType.isVariable)throw Error(`cannot create a variable series iterator for a non-variable series`);this.series=e,this.index=0,this.decoder=new TextDecoder}next(){let e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==Yo;)this.index++;let n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}},rs=class e{wrapped;static schema=l.z.record(l.z.string(),l.z.unknown());constructor(e){this.wrapped=e}next(){let t=this.wrapped.next();return t.done===!0?{done:!0,value:void 0}:{done:!1,value:li.decodeString(t.value,e.schema)}}},is=class{series;index;data;density;constructor(e){if(!e.dataType.equals(j.UUID))throw 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=j.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};let e=Wo(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}},as=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)}}},os=class{series;constructor(e=[]){if(e.length!==0){let t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw Error(`[multi-series] - series must have the same data type`)}this.series=e}as(e){return Xo(e,this.dataType),this}get dataType(){return this.series.length===0?j.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?A.ZERO:new A(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?E(0n,0n):E(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){let t=()=>Error(`cannot push a ${e.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),n=e.dataType.equals(this.dataType);if(es(e)){if(this.series.length!==0&&!n)throw t();this.series.push(e)}else{if(this.series.length!==0&&e.series.length!==0&&!n)throw t();this.series.push(...e.series)}}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){for(let n of this.series)if(Ma(n.alignmentBounds,e))return n.atAlignment(e,t);if(t)throw Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(let n of this.series){if(e<n.length)return n.at(e,t);e-=n.length}if(t)throw Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new cs(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return Ko;let n=0;for(let t=0;t<this.series.length;t++){let r=this.series[t];if(e<r.alignment)break;if(e>=r.alignmentBounds.upper)n+=r.length;else if(Ma(r.alignmentBounds,e)){n+=Math.ceil(Number(e-r.alignment)/Number(r.alignmentMultiple));break}}let r=0;for(let e=0;e<this.series.length;e++){let n=this.series[e];if(t<n.alignment)break;if(t>=n.alignmentBounds.upper)r+=n.length;else if(Ma(n.alignmentBounds,t)){r+=Math.ceil(Number(t-n.alignment)/Number(n.alignmentMultiple));break}}return new cs(this,n,r)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return Ko;t=Math.min(t,Number(this.distance(e,this.alignmentBounds.upper)));let n=0;for(let t=0;t<this.series.length;t++){let r=this.series[t];if(e<r.alignment)break;if(e>=r.alignmentBounds.upper)n+=r.length;else if(Ma(r.alignmentBounds,e)){n+=Number(e-r.alignment);break}}return new cs(this,n,n+t)}updateGLBuffer(e){this.series.forEach(t=>t.updateGLBuffer(e))}get bounds(){return Na(this.series.map(e=>e.bounds))}get byteLength(){return new Oo(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){let e=new this.dataType.Array(this.length),t=0;for(let n of this.series)e.set(n.data,t),t+=n.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){return Pa(this.series.map(e=>e.alignmentBounds),e,t)}acquire(e){this.series.forEach(t=>t.acquire(e))}release(){this.series.forEach(e=>e.release())}distance(e,t){return Fa(this.series.map(e=>e.alignmentBounds),e,t)}parseJSON(e){if(!this.dataType.equals(j.JSON))throw Error(`cannot parse non-JSON series as JSON`);return this.series.flatMap(t=>t.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new ss(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}},ss=class{series;seriesIndex;internal;constructor(e){this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){let 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}},cs=class{series;index;end;constructor(e,t,n){this.series=e,this.end=n,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}},ls=e=>({domain:e>>32n,sample:e&4294967295n}),us=C({DataType:()=>j,Density:()=>k,MultiSeries:()=>os,Rate:()=>Do,Series:()=>Qo,Size:()=>Oo,TimeRange:()=>A,TimeSpan:()=>O,TimeStamp:()=>D,convertDataType:()=>Mo,dataTypeZ:()=>Ro,isCrudeSeries:()=>$o,isTelemValue:()=>jo,numericTimeRangeZ:()=>ko,rateZ:()=>Io,sizeZ:()=>Lo,timeRangeBoundedZ:()=>zo,timeRangeZ:()=>No,timeSpanZ:()=>Fo,timeStampZ:()=>Po,typedArrayZ:()=>Ao}),ds=async e=>await new Promise(t=>setTimeout(t,O.fromMilliseconds(e).milliseconds)),fs=C({Breaker:()=>ps,breakerConfigZ:()=>ms}),ps=class{config;retries;interval;constructor(e){this.config={baseInterval:new O(e?.baseInterval??O.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??ds},this.retries=0,this.interval=new O(this.config.baseInterval)}async wait(){let{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),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}},ms=l.z.object({baseInterval:O.z.optional(),maxRetries:l.z.number().optional(),scale:l.z.number().optional()}),hs=e=>e.nullable().transform(e=>e===null?void 0:e).optional(),gs=l.z.int().min(qi).max(127),_s=l.z.int().min(Ji).max(Yi),vs=l.z.int().min(Qi).max($i),ys=l.z.int().min(0).max(255),bs=l.z.int().min(0).max(Wi),xs=l.z.int().min(0).max(Gi),Ss=l.z.int().min(0).max(Ki),Cs=e=>l.default.array(e).or(e.transform(e=>[e])),ws=(e,t)=>{let n=Array.isArray(e),r=Array.isArray(t);if(n!==r)return!1;if(n&&r){let n=e,r=t;if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++)if(!ws(n[e],r[e]))return!1;return!0}if(e==null||t==null||typeof e!=`object`||typeof t!=`object`)return e===t;if(`equals`in e)return e.equals(t);let i=Object.keys(e),a=Object.keys(t);if(i.length!==a.length)return!1;for(let n of i){let r=e[n],i=t[n];if(typeof r==`object`&&typeof i==`object`){if(!ws(r,i))return!1}else if(r!==i)return!1}return!0},Ts=(e,t)=>{if(typeof e!=`object`||!e)return e===t;let n=Object.keys(e),r=Object.keys(t);if(r.length>n.length)return!1;for(let n of r){let r=e[n],i=t[n];if(typeof r==`object`&&typeof i==`object`){if(!Ts(r,i))return!1}else if(r!==i)return!1}return!0},Es=(e,t,n=`.`)=>{let r=e.split(n);return r.map((e,i)=>{let a=t(e,i,r);return a==null?null:typeof a==`string`?a:a.join(n)}).filter(e=>e!=null).join(n)},Ds=(e,t)=>{if(!Array.isArray(e))return e[t];let n=e[t];if(n!=null||e.length==0)return n;let r=e[0];if(typeof r==`object`&&`key`in r)return e.find(e=>e.key===t)},Os=((e,t,n={optional:!1})=>{let{optional:r,getter:i=Ds}=n;if(t===``)return e;let a=t.split(`.`);if(a.length===1){let n=i(e,a[0]);if(n===void 0){if(r)return null;throw Error(`Path ${t} does not exist. ${a[0]} is undefined`)}return n}let o=(e,n)=>{if(n>=a.length)return e;for(let s=a.length-n;s>=1;s--){let c=a.slice(n,n+s).join(`.`),l=i(e,c);if(l!==void 0){if(n+s===a.length)return l;if(l===null){if(r)return null;throw Error(`Path ${t} does not exist. ${c} is null`)}return o(l,n+s)}}if(r)return null;throw Error(`Path ${t} does not exist. ${a[n]} is undefined`)};return o(e,0)}),ks=(e,...t)=>{if(t.length===0)return e;let n=t.shift();if(ii(e)&&ii(n))for(let t in n)try{ii(n[t])?(t in e||Object.assign(e,{[t]:{}}),ks(e[t],n[t])):Object.assign(e,{[t]:n[t]})}catch(e){throw e instanceof TypeError?TypeError(`.${t}: ${e.message}`,{cause:e}):e}return ks(e,...t)},As=e=>e._zod.def.output,js=e=>Es(e,(e,t,n)=>{let r=t===n.length-1,i=!isNaN(parseInt(e,10)),a=!isNaN(parseInt(n[t+1],10));return i&&(e=`element`),r||a?e:[e,`shape`]}),Ms=(e,t)=>{if(e==null)return null;let n=e[t];return n==null&&typeof e==`object`&&`sourceType`in e?e.sourceType()[t]:n},Ns=((e,t,n)=>t===``?e:Os(Ms(e,`shape`),js(t),{...n,getter:Ms})),N=C({functionOutput:()=>As,getFieldSchema:()=>Ns,getFieldSchemaPath:()=>js,int16:()=>_s,int64:()=>vs,int8:()=>gs,nullToUndefined:()=>hs,toArray:()=>Cs,uint12:()=>bs,uint16:()=>xs,uint20:()=>Ss,uint8:()=>ys}),Ps=l.z.string().regex(/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i),Fs=ys,Is=l.z.number().min(0).max(1),Ls=l.z.tuple([Fs,Fs,Fs,Is]),Rs=l.z.tuple([Fs,Fs,Fs]),zs=l.z.object({rgba255:Ls}),Bs=l.z.object({r:Fs,g:Fs,b:Fs,a:Is}),Vs=l.z.number().min(0).max(360),Hs=l.z.number().min(0).max(100),Us=l.z.number().min(0).max(100),Ws=l.z.tuple([Vs,Hs,Us,Is]),Gs=l.z.union([Ps,Rs,Ls,Ws,zs,Bs]),Ks=Gs.transform(e=>P(e)),qs=e=>Ks.safeParse(e).success,Js=e=>Ls.safeParse(e).success,Ys=(e=>{if(e==null)return;let t=Ks.safeParse(e);if(t.success)return Qs(t.data);if(typeof e==`string`)return e;throw t.error}),P=(e,t=1)=>{if(e=Gs.parse(e),typeof e==`string`)return gc(e,t);if(Array.isArray(e)){if(e.length<3||e.length>4)throw Error(`Invalid color: [${e.join(`, `)}]`);return e.length===3?[...e,t]:e}return`a`in e&&`r`in e?[e.r,e.g,e.b,e.a]:e.rgba255},Xs=(e,t)=>{if(e==null||t==null)return e==t;let n=P(e),r=P(t);return n.every((e,t)=>e===r[t])},Zs=(e=>{if(e==null)return;let[t,n,r,i]=P(e),a=Math.round(i*255);return`#${vc(t)}${vc(n)}${vc(r)}${a===255?``:vc(a)}`}),Qs=e=>{let[t,n,r,i]=P(e);return`rgba(${t}, ${n}, ${r}, ${i})`},$s=e=>`rgb(${ec(e)})`,ec=e=>{let[t,n,r]=P(e);return`${t}, ${n}, ${r}`},tc=e=>[...nc(e),oc(e)],nc=e=>[rc(e)/255,ic(e)/255,ac(e)/255],rc=e=>P(e)[0],ic=e=>P(e)[1],ac=e=>P(e)[2],oc=e=>P(e)[3],sc=e=>Xs(_c,e),cc=e=>Tc(P(e)),lc=(e,t)=>{let[n,r,i]=P(e);if(t>100)throw Error(`Color opacity must be between 0 and 100, got ${t}`);return t>1&&(t/=100),[n,r,i,t]},uc=e=>{let[t,n,r]=nc(e).map(e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4);return Number((.2126*t+.7152*n+.0722*r).toFixed(3))},dc=e=>{let[t,n,r]=nc(e);return 1-(Math.max(t,n,r)-Math.min(t,n,r))},fc=(e,t)=>{let n=P(e),r=P(t),i=uc(n),a=uc(r);return(Math.max(i,a)+.5)/(Math.min(i,a)+.5)},pc=(e,...t)=>{if(t.length===0)throw Error(`[Color.pickByContrast] - must provide at least one color`);let n=P(e),[r]=t.sort((e,t)=>fc(n,t)-fc(n,e));return P(r)},mc=e=>uc(e)<.5,hc=e=>uc(e)>.5,gc=(e,t=1)=>(e=Ps.parse(e),e=bc(e),[yc(e,0),yc(e,2),yc(e,4),e.length===8?yc(e,6)/255:t]),_c=[0,0,0,0],vc=e=>Math.floor(e).toString(16).padStart(2,`0`),yc=(e,t)=>parseInt(e.slice(t,t+2),16),bc=e=>e.startsWith(`#`)?e.slice(1):e,xc={black:`#000000`,white:`#ffffff`,red:`#ff0000`,green:`#008000`,blue:`#0000ff`,yellow:`#ffff00`,cyan:`#00ffff`,magenta:`#ff00ff`,silver:`#c0c0c0`,gray:`#808080`,grey:`#808080`,maroon:`#800000`,olive:`#808000`,lime:`#00ff00`,aqua:`#00ffff`,teal:`#008080`,navy:`#000080`,fuchsia:`#ff00ff`,purple:`#800080`,orange:`#ffa500`,brown:`#a52a2a`,tan:`#d2b48c`,gold:`#ffd700`,indigo:`#4b0082`,violet:`#ee82ee`,pink:`#ffc0cb`,coral:`#ff7f50`,salmon:`#fa8072`,khaki:`#f0e68c`,crimson:`#dc143c`,transparent:`transparent`},Sc=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!(t===`transparent`||t===`none`)){if(t.startsWith(`#`)){if(t.length===4){let e=t[1],n=t[2],r=t[3],i=`#${e}${e}${n}${n}${r}${r}`;if(Ps.safeParse(i).success)return gc(i)}return(t.length===7||t.length===9)&&Ps.safeParse(t).success?gc(t):void 0}if(t.startsWith(`rgb`)){let e=t.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(e){let[,t,n,r,i]=e;return[parseInt(t,10),parseInt(n,10),parseInt(r,10),i?parseFloat(i):1]}}if(xc[t])return gc(xc[t])}},Cc=e=>{e=Ws.parse(e);let[t,n,r]=e,i=e[3];t/=360,n/=100,r/=100;let a,o,s;if(n===0)a=o=s=r;else{let e=r<.5?r*(1+n):r+n-r*n,i=2*r-e;a=wc(i,e,t+1/3),o=wc(i,e,t),s=wc(i,e,t-1/3)}return[Math.round(a*255),Math.round(o*255),Math.round(s*255),i]},wc=(e,t,n)=>(n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e),Tc=e=>{e=Ls.parse(e);let[t,n,r]=e,i=e[3];t/=255,n/=255,r/=255;let a=Math.max(t,n,r),o=Math.min(t,n,r),s,c,l=(a+o)/2;if(a===o)s=c=0;else{let e=a-o;c=l>.5?e/(2-a-o):e/(a+o),s=a===t?(n-r)/e+(n<r?6:0):a===n?(r-t)/e+2:(t-n)/e+4,s/=6}return s*=360,c*=100,l*=100,[Math.round(s),Math.round(c),Math.round(l),i]},Ec=P(`#000000`),Dc=P(`#ffffff`),Oc=l.z.object({key:l.z.string(),color:Gs,position:l.z.number(),switched:l.z.boolean().optional()}),kc=l.z.array(Oc),Ac=(e,t)=>{if(e.length===0)return _c;if(e=e.slice().sort((e,t)=>e.position-t.position),t<=e[0].position)return P(e[0].color);if(t>=e[e.length-1].position)return P(e[e.length-1].color);for(let n=0;n<e.length-1;n++){let r=e[n],i=e[n+1];if(t<r.position||t>i.position)continue;if(t===r.position)return P(r.color);if(t===i.position)return P(i.color);let a=(t-r.position)/(i.position-r.position),o=P(r.color),s=P(i.color);return P([Math.round(rc(o)+a*(rc(s)-rc(o))),Math.round(ic(o)+a*(ic(s)-ic(o))),Math.round(ac(o)+a*(ac(s)-ac(o))),oc(o)+a*(oc(s)-oc(o))])}return P(e[e.length-1].color)},jc=l.z.object({key:l.z.string(),name:l.z.string(),color:Ks}),Mc=l.z.object({key:l.z.string(),name:l.z.string(),swatches:l.z.array(jc)}),Nc=C({BLACK:()=>Ec,WHITE:()=>Dc,ZERO:()=>_c,aValue:()=>oc,bValue:()=>ac,colorZ:()=>Ks,construct:()=>P,contrast:()=>fc,crudeZ:()=>Gs,cssString:()=>Ys,equals:()=>Xs,fromCSS:()=>Sc,fromGradient:()=>Ac,fromHSLA:()=>Cc,gValue:()=>ic,gradientZ:()=>kc,grayness:()=>dc,hex:()=>Zs,hsla:()=>cc,isColor:()=>Js,isCrude:()=>qs,isDark:()=>mc,isLight:()=>hc,isZero:()=>sc,luminance:()=>uc,paletteZ:()=>Mc,pickByContrast:()=>pc,rValue:()=>rc,rgbCSS:()=>$s,rgbString:()=>ec,rgba1:()=>tc,rgbaCSS:()=>Qs,setAlpha:()=>lc,stopZ:()=>Oc}),Pc=ys,Fc=function(e){return e[e.exclusive=0]=`exclusive`,e[e.shared=1]=`shared`,e}({}),Ic=l.z.enum(Fc),Lc=l.z.object({key:l.z.string(),name:l.z.string(),group:l.z.uint32().optional()}),Rc=e=>l.z.object({subject:Lc,resource:e,authority:Pc}),zc={lower:0,upper:256},Bc=(...e)=>t=>t.filter(t=>{let n=!1;return t.to!=null&&(n=e.includes(t.to.resource)),t.from!=null&&!n&&(n=e.includes(t.from.resource)),n}),Vc=e=>l.z.object({from:Rc(e),to:l.z.null().optional()}),Hc=e=>l.z.object({from:l.z.null().optional(),to:Rc(e)}),Uc=e=>l.z.union([Vc(e),Hc(e),l.z.object({from:Rc(e),to:Rc(e)})]),F=C({ABSOLUTE_AUTHORITY:()=>255,AUTHORITY_BOUNDS:()=>zc,Concurrency:()=>Fc,ZERO_AUTHORITY:()=>0,acquireZ:()=>Hc,authorityZ:()=>Pc,concurrencyZ:()=>Ic,filterTransfersByChannelKey:()=>Bc,releaseZ:()=>Vc,stateZ:()=>Rc,subjectZ:()=>Lc,transferZ:()=>Uc}),Wc=C({formatValue:()=>Gc}),Gc=e=>{switch(typeof e){case`bigint`:case`number`:return e.toString();case`boolean`:return e?`1`:`0`;case`undefined`:return``;case`string`:case`symbol`:case`function`:return qc(e.toString());case`object`:return e==null?``:qc(JSON.stringify(e))}},Kc=/[",\n]/,qc=e=>Kc.test(e)?`"${e.replace(/"/g,`""`)}"`:e,Jc=(e,t)=>{let n=null;return t===0?e:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>e(...r),t)}},Yc=e=>Object.getOwnPropertySymbols(globalThis).includes(e),Xc=(e,t)=>{let n=Symbol.for(e);if(!Yc(n)){let e=t();Object.defineProperty(globalThis,n,{value:e})}return()=>globalThis[n]},Zc=C({Canceled:()=>ul,NONE:()=>`nil`,NotImplemented:()=>dl,UNKNOWN:()=>nl,Unknown:()=>cl,createTyped:()=>el,decode:()=>sl,encode:()=>ol,isTyped:()=>tl,payloadZ:()=>ll,register:()=>al}),Qc=`sy_x_error`,$c=e=>t=>typeof t==`object`&&t&&`type`in t&&typeof t.type==`string`?t.type.startsWith(e):t instanceof Error?t.message.startsWith(e):typeof t==`string`?t.startsWith(e):!1,el=e=>class t extends Error{static discriminator=Qc;discriminator=t.discriminator;static TYPE=e;type=t.TYPE;static matches=$c(e);matches=t.matches;constructor(e,n){super(e,n),this.name=t.TYPE}static sub(t){return el(`${e}.${t}`)}},tl=e=>{if(typeof e!=`object`||!e)return!1;let t=e;if(t.discriminator!==Qc)return!1;if(!(`type`in t))throw Error(`X Error is missing its type property: ${JSON.stringify(t)}`);return!0},nl=`unknown`,rl=class{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:`nil`,data:``};if(tl(e))for(let t of this.providers){let n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:nl,data:e.message};if(typeof e==`string`)return{type:nl,data:e};try{return{type:nl,data:JSON.stringify(e)}}catch{return{type:nl,data:`unable to encode error information`}}}decode(e){if(e==null||e.type===`nil`)return null;if(e.type===`unknown`)return new cl(e.data);for(let t of this.providers){let n=t.decode(e);if(n!=null)return n}return new cl(e.data)}},il=Xc(`synnax-error-registry`,()=>new rl),al=({encode:e,decode:t})=>il().register({encode:e,decode:t}),ol=e=>il().encode(e),sl=e=>e==null?null:il().decode(e),cl=class extends el(`unknown`){},ll=l.z.object({type:l.z.string(),data:l.z.string()}),ul=class extends el(`canceled`){},dl=class extends el(`not_implemented`){};l.z.string().regex(/^(?:$|(?:\/(?:[^~/]|~0|~1)*)+)$/,`must be a valid JSON pointer (RFC 6901)`),l.z.union([l.z.string(),l.z.number(),l.z.boolean(),l.z.null()]),l.z.enum([`string`,`number`,`boolean`,`null`]),l.z.object({key:l.z.string(),value:l.z.string()});var fl=C({keyZ:()=>pl,labelZ:()=>ml,newZ:()=>hl}),pl=l.z.uuid(),ml=l.z.object({key:pl,name:l.z.string().min(1),color:Ks}),hl=ml.partial({key:!0}),gl=C({compareSemVer:()=>yl,createMigration:()=>Cl,migrator:()=>wl,semVerNewer:()=>xl,semVerOlder:()=>Sl,semVerZ:()=>_l,versionsEqual:()=>bl}),_l=l.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/),vl=(e,t)=>{let n=e.split(`.`),r=t.split(`.`),i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=n[e],i=r[e];if(t===void 0)return-1;if(i===void 0)return 1;let a=/^\d+$/.test(t),o=/^\d+$/.test(i);if(a&&!o)return-1;if(!a&&o)return 1;if(a&&o){let e=parseInt(t,10),n=parseInt(i,10);if(e<n)return-1;if(e>n)return 1}else{if(t<i)return-1;if(t>i)return 1}}return 0},yl=((e,t,n={})=>{n.checkMajor??=!0,n.checkMinor??=!0,n.checkPatch??=!0;let r=_l.parse(e),i=_l.parse(t),[a,o]=r.split(`-`),[s,c]=i.split(`-`),[l,u,d]=a.split(`.`).map(Number),[f,p,m]=s.split(`.`).map(Number);if(n.checkMajor){if(l<f)return-1;if(l>f)return 1}if(n.checkMinor){if(u<p)return-1;if(u>p)return 1}if(n.checkPatch){if(d<m)return-1;if(d>m)return 1}return o===void 0&&c===void 0?0:o===void 0?1:c===void 0?-1:vl(o,c)}),bl=(e,t,n={})=>ji(yl(e,t,n)),xl=(e,t,n={})=>ki(yl(e,t,n)),Sl=(e,t,n={})=>Oi(yl(e,t,n)),Cl=({name:e,migrate:t})=>n=>{try{let r=t(n);return console.log(`${e} migrated: ${n.version} -> ${r.version}`),r}catch(t){throw console.log(`${e} failed to migrate from ${n.version}`),console.error(t),t}},wl=({name:e,migrations:t,targetSchema:n,defaultVersion:r,def:i})=>{let a=Object.keys(t).sort(yl).pop();if(a==null)return t=>{if(t.version??=r,t.version!==i.version)return console.log(`${e} version ${t.version} is newer than latest version of ${i.version}.
24
+ `).map(e=>e.trim());if(n.length===0)return t==null?{}:t.parse({});let i=n.split(`,`).map(e=>e.trim()),a={};return i.forEach(e=>{a[e]=[]}),r.forEach(e=>{let t=e.split(`,`).map(e=>e.trim());i.forEach((e,n)=>{let r=this.parseValue(t[n]);r!=null&&a[e].push(r)})}),t==null?a:t.parse(a)}parseValue(e){if(e==null||e.length===0)return null;let t=Number(e);return isNaN(t)?e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e:t}},Wo=class{contentType=`text/plain`;encode(e){if(typeof e!=`string`)throw Error(`TextCodec.encode payload must be a string`);return new TextEncoder().encode(e)}decode(e,t){let n=new TextDecoder().decode(e);return t==null?n:t.parse(n)}},Go=new Ho,Ko=new Uo,qo=new Wo,Jo=[Go],Yo=C({by:()=>Zo,unique:()=>Xo}),Xo=e=>[...new Set(e)],Zo=(e,t,n=!0)=>{let r=new Map;return e.forEach(e=>{let i=t(e);if(r.has(i)){if(n)return;r.delete(i)}r.set(i,e)}),Array.from(r.values())},Qo=(e,t=!1)=>{let n=ma(e)?`stringer`:typeof e,r;switch(n){case`string`:r=(e,t)=>e.localeCompare(t);break;case`stringer`:r=(e,t)=>e.toString().localeCompare(t.toString());break;case`number`:r=(e,t)=>Number(e)-Number(t);break;case`bigint`:r=(e,t)=>BigInt(e)-BigInt(t)>0n?1:-1;break;case`boolean`:r=(e,t)=>Number(e)-Number(t);break;case`undefined`:r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return t?is(r):r},$o=(e,t,n)=>{let r=Qo(t[e],n);return(t,n)=>r(t[e],n[e])},es=(e,t)=>e.length===t.length?e.every((e,n)=>e===t[n])?0:-1:e.length-t.length,ts=(e,t)=>{if(e.length!==t.length)return e.length-t.length;if(e.length===0)return 0;let n=Qo(e[0]),r=[...e].sort(n),i=[...t].sort(n);return r.every((e,t)=>e===i[t])?0:-1},ns=(e,t)=>ts(Xo(e),Xo(t)),rs=(e,t)=>e===t?0:e===`first`&&t===`last`?1:-1,is=e=>(t,n)=>e(n,t),as=e=>e<0,os=e=>e>0,ss=e=>e>=0,cs=e=>e===0,ls=(e,t)=>{let n=/([a-zA-Z]+)|(\d+)/g,r=e.replace(/[\s_.-]+/g,``).match(n),i=t.replace(/[\s_.-]+/g,``).match(n);if(!r||!i)return 0;for(let e=0;e<Math.min(r.length,i.length);e++){let t=r[e],n=i[e];if(isNaN(Number(t))&&isNaN(Number(n))){let e=t.localeCompare(n);if(e!==0)return e}else if(!isNaN(Number(t))&&!isNaN(Number(n))){let e=Number(t)-Number(n);if(e!==0)return e}else return isNaN(Number(t))?-1:1}return r.length-i.length},us=(e,t,n)=>{let r=0,i=e.length,a=n??Qo(t);for(;r<i;){let n=Math.floor((r+i)/2),o=a(e[n],t);if(o===0)return n;o<0?r=n+1:i=n}return r},ds=(e,t,n)=>{let r=us(e,t,n);e.splice(r,0,t)},fs=C({EQUAL:()=>0,GREATER_THAN:()=>1,LESS_THAN:()=>-1,insert:()=>ds,isEqualTo:()=>cs,isGreaterThan:()=>os,isGreaterThanEqual:()=>ss,isLessThan:()=>as,newF:()=>Qo,newFieldF:()=>$o,order:()=>rs,primitiveArrays:()=>es,reverseF:()=>is,search:()=>us,stringsWithNumbers:()=>ls,uniqueUnorderedPrimitiveArrays:()=>ns,unorderedPrimitiveArrays:()=>ts}),ps=(e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i--;)r+=e[Math.random()*e.length|0];return r},ms=C({LENGTH:()=>11,create:()=>ys}),hs=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,gs=`0123456789${hs}`,_s=ps(hs,1),vs=ps(gs,10),ys=()=>`${_s()}${vs()}`,bs=(e,t)=>n=>n instanceof t||typeof n==`object`&&!!n&&`discriminator`in n&&n.discriminator===e;l.z.object({x:so.or(fo),y:lo.or(fo)});var xs=l.z.object({x:so,y:lo}),Ss=Object.freeze({x:`left`,y:`top`}),Cs=Object.freeze({x:`right`,y:`top`}),ws=Object.freeze({x:`left`,y:`bottom`}),Ts=Object.freeze({x:`right`,y:`bottom`}),Es=Object.freeze({x:`center`,y:`center`}),Ds=Object.freeze({x:`center`,y:`top`}),Os=Object.freeze({x:`center`,y:`bottom`}),ks=Object.freeze({x:`right`,y:`center`}),As=Object.freeze({x:`left`,y:`center`});Object.freeze([As,ks,Ds,Os,Ss,Cs,ws,Ts,Es]);var js=(e,t)=>e.x===t.x&&e.y===t.y,Ms=e=>[e.x,e.y];l.z.enum([`top`,`right`,`bottom`,`left`]);var Ns=l.z.object({x:l.z.number(),y:l.z.number()}),Ps=l.z.union([l.z.number(),Ns,to,bo,xo,yo]),Fs=(e,t)=>{if(typeof e==`string`){if(t===void 0)throw Error(`The y coordinate must be given.`);return e===`x`?{x:t,y:0}:{x:0,y:t}}return typeof e==`number`?{x:e,y:t??e}:Array.isArray(e)?{x:e[0],y:e[1]}:`signedWidth`in e?{x:e.signedWidth,y:e.signedHeight}:`clientX`in e?{x:e.clientX,y:e.clientY}:`width`in e?{x:e.width,y:e.height}:{x:e.x,y:e.y}},Is=Object.freeze({x:0,y:0});Object.freeze({x:1,y:1}),Object.freeze({x:1/0,y:1/0}),Object.freeze({x:NaN,y:NaN});var Ls=(e,t)=>{let n=Fs(e);return{x:n.x+t,y:n.y}},Rs=(e,t)=>{let n=Fs(e);return{x:n.x,y:n.y+t}},zs=(e,t,n,...r)=>{if(typeof t==`string`){if(typeof n!=`number`)throw Error(`The value must be a number.`);return t===`x`?Ls(e,n):Rs(e,n)}if(typeof t==`object`&&`x`in t&&typeof t.x==`string`){let r=Fs(n),i=Fs(e);return t.x===`left`?r.x=-r.x:t.x===`center`&&(r.x=0),t.y===`top`?r.y=-r.y:t.y===`center`&&(r.y=0),{x:i.x+r.x,y:i.y+r.y}}return[e,t,n??Is,...r].reduce((e,t)=>{let n=Fs(t);return{x:e.x+n.x,y:e.y+n.y}},Is)},Bs=l.z.union([l.z.number(),l.z.string()]);l.z.object({top:Bs,left:Bs,width:Bs,height:Bs}),l.z.object({left:l.z.number(),top:l.z.number(),right:l.z.number(),bottom:l.z.number()}),l.z.object({one:Ns,two:Ns,root:xs});var Vs=(e,t,n=0,r=0,i)=>{let a={one:{...Is},two:{...Is},root:i??Ss};if(typeof e==`number`){if(typeof t!=`number`)throw Error(`Box constructor called with invalid arguments`);return a.one={x:e,y:t},a.two={x:a.one.x+n,y:a.one.y+r},a}return`one`in e&&`two`in e&&`root`in e?{...e,root:i??e.root}:(`getBoundingClientRect`in e&&(e=e.getBoundingClientRect()),`left`in e?(a.one={x:e.left,y:e.top},a.two={x:e.right,y:e.bottom},a):(a.one=e,t==null?a.two={x:a.one.x+n,y:a.one.y+r}:typeof t==`number`?a.two={x:a.one.x+t,y:a.one.y+n}:`width`in t?a.two={x:a.one.x+t.width,y:a.one.y+t.height}:`signedWidth`in t?a.two={x:a.one.x+t.signedWidth,y:a.one.y+t.signedHeight}:a.two=t,a))},Hs=(e,t)=>{let n=Vs(e);return{x:t.x===`center`?qs(n).x:Us(n,t.x),y:t.y===`center`?qs(n).y:Us(n,t.y)}},Us=(e,t)=>{let n=Vs(e),r=Ms(n.root).includes(t)?Math.min:Math.max;return oo.includes(t)?r(n.one.x,n.two.x):r(n.one.y,n.two.y)},Ws=e=>{let t=Vs(e);return t.two.x-t.one.x},Gs=e=>{let t=Vs(e);return t.two.y-t.one.y},Ks=e=>Hs(e,Ss),qs=e=>zs(Ks(e),{x:Ws(e)/2,y:Gs(e)/2}),Js=e=>{let t=Vs(e);return{lower:t.one.x,upper:t.two.x}},Ys=e=>{let t=Vs(e);return{lower:t.one.y,upper:t.two.y}},Xs=e=>typeof e!=`object`||!e?!1:`one`in e&&`two`in e&&`root`in e;l.z.union([bo,xo,Ns,to]);var Zs=(e,t,n)=>t!==void 0&&e<t?t:n!==void 0&&e>n?n:e;l.z.object({offset:Ps,scale:Ps}),l.z.object({offset:l.z.number(),scale:l.z.number()});var Qs=e=>(t,n,r,i)=>n===`dimension`?[t,r]:[t,i?r-e:r+e],$s=e=>(t,n,r,i)=>[t,i?r/e:r*e],ec=e=>(t,n,r)=>{if(t===null)return[e,r];let{lower:i,upper:a}=t,{lower:o,upper:s}=e,c=a-i,l=s-o;return n===`dimension`?[e,l/c*r]:[e,(r-i)*(l/c)+o]},tc=e=>(t,n,r)=>[e,r],nc=()=>(e,t,n)=>{if(e===null)throw Error(`cannot invert without bounds`);if(t===`dimension`)return[e,n];let{lower:r,upper:i}=e;return[e,i-(n-r)]},rc=e=>(t,n,r)=>{let{lower:i,upper:a}=e;return r=Zs(r,i,a),[t,r]},ic=class e{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(t){return new e().translate(t)}static magnify(t){return new e().magnify(t)}static scale(t,n){return new e().scale(t,n)}translate(e){let t=this.new(),n=Qs(e);return n.type=`translate`,t.ops.push(n),t}magnify(e){let t=this.new(),n=$s(e);return n.type=`magnify`,t.ops.push(n),t}scale(e,t){let n=E(e,t),r=this.new(),i=ec(n);return i.type=`scale`,r.ops.push(i),r}clamp(e,t){let n=E(e,t),r=this.new(),i=rc(n);return i.type=`clamp`,r.ops.push(i),r}reBound(e,t){let n=E(e,t),r=this.new(),i=tc(n);return i.type=`re-bound`,r.ops.push(i),r}invert(){let e=nc();e.type=`invert`;let t=this.new();return t.ops.push(e),t}pos(e){return this.exec(`position`,e)}dim(e){return this.exec(`dimension`,e)}new(){let t=new e;return t.ops=this.ops.slice(),t.reversed=this.reversed,t}exec(e,t){return this.currBounds=null,this.ops.reduce(([t,n],r)=>r(t,e,n,this.reversed),[null,t])[1]}reverse(){let e=this.new();e.ops.reverse();let t=[];return e.ops.forEach((n,r)=>{if(n.type===`scale`||t.some(([e,t])=>r>=e&&r<=t))return;let i=e.ops.findIndex((e,t)=>e.type===`scale`&&t>r);i!==-1&&t.push([r,i])}),t.forEach(([t,n])=>{let r=e.ops.slice(t,n);r.unshift(e.ops[n]),e.ops.splice(t,n-t+1,...r)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new e};(class e{x;y;currRoot;constructor(e=new ic,t=new ic,n=null){this.x=e,this.y=t,this.currRoot=n}static translate(t,n){return new e().translate(t,n)}static translateX(t){return new e().translateX(t)}static translateY(t){return new e().translateY(t)}static clamp(t){return new e().clamp(t)}static magnify(t){return new e().magnify(t)}static scale(t){return new e().scale(t)}static reBound(t){return new e().reBound(t)}translate(e,t){let n=Fs(e,t),r=this.copy();return r.x=this.x.translate(n.x),r.y=this.y.translate(n.y),r}translateX(e){let t=this.copy();return t.x=this.x.translate(e),t}translateY(e){let t=this.copy();return t.y=this.y.translate(e),t}magnify(e){let t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){let t=this.copy();if(Xs(e)){let n=this.currRoot;return t.currRoot=e.root,n!=null&&!js(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Js(e)),t.y=t.y.scale(Ys(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){let t=this.copy();return t.x=this.x.reBound(Js(e)),t.y=this.y.reBound(Ys(e)),t}clamp(e){let t=this.copy();return t.x=this.x.clamp(Js(e)),t.y=this.y.clamp(Ys(e)),t}copy(){let t=new e;return t.currRoot=this.currRoot,t.x=this.x,t.y=this.y,t}reverse(){let e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Vs(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new e});var ac=C({ALIGNMENTS:()=>ho,CENTER_LOCATIONS:()=>uo,DIRECTIONS:()=>no,LOCATIONS:()=>po,ORDERS:()=>_o,OUTER_LOCATIONS:()=>io,X_LOCATIONS:()=>oo,Y_LOCATIONS:()=>co,alignmentZ:()=>go,boundsZ:()=>So,centerLocationZ:()=>fo,clientXyZ:()=>yo,dimensionsZ:()=>bo,directionZ:()=>ro,locationZ:()=>mo,orderZ:()=>vo,outerLocationZ:()=>ao,signedDimensionsZ:()=>xo,xLocationZ:()=>so,xyZ:()=>Ns,yLocationZ:()=>lo});Ns.extend({root:xs,units:l.default.object({x:l.default.enum([`px`,`decimal`]),y:l.default.enum([`px`,`decimal`])})}).partial({root:!0,units:!0});var oc=l.z.enum([`static`,`dynamic`]),sc=365,cc=30,lc=l.z.union([l.z.tuple([l.z.int()]),l.z.tuple([l.z.int(),l.z.int().min(1).max(12)]),l.z.tuple([l.z.int(),l.z.int().min(1).max(12),l.z.int().min(1).max(31)])]),uc=(e,t)=>{let n=new O(t);if(![k.DAY,k.HOUR,k.MINUTE,k.SECOND,k.MILLISECOND,k.MICROSECOND,k.NANOSECOND].some(e=>e.equals(n)))throw Error(`Invalid argument for remainder. Must be an even TimeSpan or Timestamp`);let r=e.valueOf()%n.valueOf();return e instanceof O?new O(r):new k(r)},O=class e extends pa{constructor(t,n=`UTC`){if(t==null)super(e.now().valueOf());else if(t instanceof Date)super(BigInt(t.getTime())*e.MILLISECOND.valueOf());else if(typeof t==`string`)super(e.parseDateTimeString(t,n).valueOf());else if(Array.isArray(t))super(e.parseDate(t));else{let r=0n;t instanceof Number&&(t=t.valueOf()),n===`local`&&(r=e.utcOffset.valueOf()),typeof t==`number`&&(isFinite(t)?t=t===Ga?Ua:Math.trunc(t):(isNaN(t)&&(t=0),t=t===1/0?e.MAX:e.MIN)),T(t)&&(t=t.value),super(BigInt(t.valueOf())+r)}}static parseDate([t=1970,n=1,r=1]){let i=new Date(t,n-1,r,0,0,0,0);return new e(BigInt(i.getTime())*e.MILLISECOND.valueOf()).truncate(e.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(t,n=`UTC`){let[r,i,a]=t.split(`:`),o=`00`,s=`00`;a!=null&&([o,s]=a.split(`.`));let c=e.hours(parseInt(r??`00`,10)).add(e.minutes(parseInt(i??`00`,10))).add(e.seconds(parseInt(o??`00`,10))).add(e.milliseconds(parseInt(s??`00`,10)));return n===`local`&&(c=c.add(e.utcOffset)),c.valueOf()}static parseDateTimeString(t,n=`UTC`){if(!t.includes(`/`)&&!t.includes(`-`))return e.parseTimeString(t,n);if(t.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let r=t,i=0;if(t.includes(`.`)){let e=t.split(`.`);r=e[0];let n=e[1]||`0`;i=parseInt(n.padEnd(3,`0`).slice(0,3),10)}let a=n===`local`?new Date(r.replace(`T`,` `)):new Date(`${r}Z`);return BigInt(a.getTime())*e.MILLISECOND.valueOf()+BigInt(i)*e.MILLISECOND.valueOf()}let r=new Date(t);return t.includes(`:`)||r.setUTCHours(0,0,0,0),new e(BigInt(r.getTime())*e.MILLISECOND.valueOf(),n).valueOf()}toISOString(t=`UTC`){if(t===`UTC`)return this.date().toISOString();let n=this.date(),r=new k(BigInt(n.getTimezoneOffset())*e.MINUTE.valueOf());return this.sub(r).date().toISOString()}timeString(e=!1,t=`UTC`){let n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){let e=this.date();return`${e.toLocaleString(`default`,{month:`short`})} ${e.toLocaleString(`default`,{day:`numeric`})}`}static get utcOffset(){return new k(BigInt(new Date().getTimezoneOffset())*e.MINUTE.valueOf())}static since(t){return new e().span(t)}date(){return new Date(this.milliseconds)}equals(t){return this.valueOf()===new e(t).valueOf()}span(e){return this.range(e).span}range(e){return new j(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(t){return this.valueOf()>new e(t).valueOf()}afterEq(t){return this.valueOf()>=new e(t).valueOf()}before(t){return this.valueOf()<new e(t).valueOf()}beforeEq(t){return this.valueOf()<=new e(t).valueOf()}add(t){return new e(Ja(this.valueOf(),new k(t).valueOf()))}sub(t){return new e(qa(this.valueOf(),new k(t).valueOf()))}get hours(){return Number(this.valueOf())/Number(k.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(k.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(k.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(k.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(e.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(e.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}get localYear(){return this.date().getFullYear()}setYear(t){let n=this.date();return n.setUTCFullYear(t),new e(n)}setLocalYear(t){let n=this.date();return n.setFullYear(t),new e(n)}get month(){return this.date().getUTCMonth()}get localMonth(){return this.date().getMonth()}setMonth(t){let n=this.date();return n.setUTCMonth(t),new e(n)}setLocalMonth(t){let n=this.date();return n.setMonth(t),new e(n)}get day(){return this.date().getUTCDate()}get localDay(){return this.date().getDate()}setDay(t){let n=this.date();return n.setUTCDate(t),new e(n)}setLocalDay(t){let n=this.date();return n.setDate(t),new e(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(t){let n=this.date();return n.setHours(t),new e(n)}setHour(t){let n=this.date();return n.setUTCHours(t),new e(n)}get minute(){return this.date().getUTCMinutes()}get localMinute(){return this.date().getMinutes()}setMinute(t){let n=this.date();return n.setUTCMinutes(t),new e(n)}setLocalMinute(t){let n=this.date();return n.setMinutes(t),new e(n)}get second(){return this.date().getUTCSeconds()}get localSecond(){return this.date().getSeconds()}setSecond(t){let n=this.date();return n.setUTCSeconds(t),new e(n)}setLocalSecond(t){let n=this.date();return n.setSeconds(t),new e(n)}get millisecond(){return this.date().getUTCMilliseconds()}get localMillisecond(){return this.date().getMilliseconds()}setMillisecond(t){let n=this.date();return n.setUTCMilliseconds(t),new e(n)}setLocalMillisecond(t){let n=this.date();return n.setMilliseconds(t),new e(n)}toString(e=`ISO`,t=`UTC`){switch(e){case`ISODate`:return this.toISOString(t).slice(0,10);case`ISOTime`:return this.toISOString(t).slice(11,23);case`time`:return this.timeString(!1,t);case`preciseTime`:return this.timeString(!0,t);case`date`:return this.dateString();case`preciseDate`:return`${this.dateString()} ${this.timeString(!0,t)}`;case`dateTime`:return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}remainder(e){return uc(this,e)}get isToday(){return this.truncate(k.DAY).equals(e.now().truncate(k.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(k.days(30))?`shortDate`:e.greaterThanOrEqual(k.DAY)?`dateTime`:e.greaterThanOrEqual(k.HOUR)?`time`:e.greaterThanOrEqual(k.SECOND)?`preciseTime`:`ISOTime`}static now(){return new e(new Date)}static max(...t){let n=e.MIN;for(let r of t){let t=new e(r);t.after(n)&&(n=t)}return n}static min(...t){let n=e.MAX;for(let r of t){let t=new e(r);t.before(n)&&(n=t)}return n}static nanoseconds(t,n=`UTC`){return new e(t,n)}static NANOSECOND=e.nanoseconds(1);static microseconds(t,n=`UTC`){return e.nanoseconds(t*1e3,n)}static MICROSECOND=e.microseconds(1);static milliseconds(t,n=`UTC`){return e.microseconds(t*1e3,n)}static MILLISECOND=e.milliseconds(1);static seconds(t,n=`UTC`){return e.milliseconds(t*1e3,n)}static SECOND=e.seconds(1);static minutes(t,n=`UTC`){return e.seconds(t*60,n)}static MINUTE=e.minutes(1);static hours(t,n=`UTC`){return e.minutes(t*60,n)}static HOUR=e.hours(1);static days(t,n=`UTC`){return e.hours(t*24,n)}static DAY=e.days(1);static MAX=new e(Ua);static MIN=new e(0);static ZERO=new e(0);static z=l.z.union([l.z.instanceof(e),l.z.object({value:l.z.bigint()}).transform(t=>new e(t.value)),l.z.string().transform(t=>new e(BigInt(t))),l.z.number().transform(t=>new e(t)),l.z.bigint().transform(t=>new e(t)),l.z.date().transform(t=>new e(t)),l.z.custom(e=>e instanceof k).transform(t=>new e(t)),lc.transform(t=>new e(t))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}},k=class e extends pa{constructor(e){typeof e==`number`&&(e=Math.trunc(e.valueOf())),T(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(t){return t instanceof e?t:t instanceof dc?t.period:t instanceof O?new e(t):(T(t)&&(t=t.value),[`number`,`bigint`].includes(typeof t)?e.seconds(t):new e(t))}static fromMilliseconds(t){return t instanceof e?t:t instanceof dc?t.period:t instanceof O?new e(t):(T(t)&&(t=t.value),[`number`,`bigint`].includes(typeof t)?e.milliseconds(t):new e(t))}valueOf(){return this.value}lessThan(t){return this.valueOf()<new e(t).valueOf()}greaterThan(t){return this.valueOf()>new e(t).valueOf()}lessThanOrEqual(t){return this.valueOf()<=new e(t).valueOf()}greaterThanOrEqual(t){return this.valueOf()>=new e(t).valueOf()}remainder(e){return uc(this,e)}truncate(t){return new e(BigInt(Math.trunc(Number(this.valueOf()/t.valueOf())))*t.valueOf())}toString(t=`full`){if(t===`semantic`)return this.toSemanticString();let n=this.truncate(e.DAY),r=this.truncate(e.HOUR),i=this.truncate(e.MINUTE),a=this.truncate(e.SECOND),o=this.truncate(e.MILLISECOND),s=this.truncate(e.MICROSECOND),c=this.truncate(e.NANOSECOND),l=n,u=r.sub(n),d=i.sub(r),f=a.sub(i),p=o.sub(a),m=s.sub(o),h=c.sub(s),g=``;return l.isZero||(g+=`${l.days}d `),u.isZero||(g+=`${u.hours}h `),d.isZero||(g+=`${d.minutes}m `),f.isZero||(g+=`${f.seconds}s `),p.isZero||(g+=`${p.milliseconds}ms `),m.isZero||(g+=`${m.microseconds}µs `),h.isZero||(g+=`${h.nanoseconds}ns`),g.trim()}toSemanticString(){let t=new e(this.valueOf()<0n?-this.valueOf():this.valueOf()),n=this.valueOf()<0n;if(t.valueOf()===0n)return`0s`;if(t.lessThan(e.SECOND))return`< 1s`;let r=t.days,i=t.hours,a=t.minutes,o=t.seconds,s=Math.floor(r/sc),c=Math.floor(r/cc),l=Math.floor(r/7),u=Math.floor(r),d=Math.floor(i),f=Math.floor(a),p=Math.floor(o),m=n?`-`:``;if(s>=1){let e=`${s}y`;if(s<2){let t=Math.floor(r%sc/cc);t>0&&(e+=` ${t}mo`)}return m+e}if(l>=1&&r<cc&&r%7==0){let e=`${l}w`,t=Math.floor(r%7),n=Math.floor(i-l*7*24);return l<2&&(t>0?e+=` ${t}d`:n>0&&n<24&&(e+=` ${n}h`)),m+e}if(c>=1){let e=`${c}mo`;if(c<3){let t=Math.floor(r%cc);t>0&&(e+=` ${t}d`)}return m+e}if(l>=1){let e=`${l}w`,t=Math.floor(r%7),n=Math.floor(i-l*7*24);return l<2&&(t>0?e+=` ${t}d`:n>0&&n<24&&(e+=` ${n}h`)),m+e}if(u>=1){let e=`${u}d`,t=Math.floor(i-u*24);return u<2&&t>0&&(e+=` ${t}h`),m+e}if(d>=1){let e=`${d}h`;if(d<3){let t=Math.floor(a-d*60);t>0&&(e+=` ${t}m`)}return m+e}if(f>=1){let e=`${f}m`;if(f<5){let t=Math.floor(o-f*60);t>0&&(e+=` ${t}s`)}return m+e}return`${m}${p}s`}mult(t){return new e($a(this.valueOf(),t))}div(t){return new e(eo(this.valueOf(),t))}get days(){return Number(this.valueOf())/Number(e.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(e.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(e.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(e.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(e.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(e.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(t){return this.valueOf()===new e(t).valueOf()}add(t){return new e(this.valueOf()+new e(t).valueOf())}sub(t){return new e(this.valueOf()-new e(t).valueOf())}static nanoseconds(t=1){return new e(t)}static NANOSECOND=e.nanoseconds(1);static microseconds(t=1){return e.nanoseconds($a(t,1e3))}static MICROSECOND=e.microseconds(1);static milliseconds(t=1){return e.microseconds($a(t,1e3))}static MILLISECOND=e.milliseconds(1);static seconds(t=1){return e.milliseconds($a(t,1e3))}static SECOND=e.seconds(1);static minutes(t=1){return e.seconds($a(t,60))}static MINUTE=e.minutes(1);static hours(t){return e.minutes($a(t,60))}static HOUR=e.hours(1);static days(t){return e.hours($a(t,24))}static DAY=e.days(1);static MAX=new e(Ua);static MIN=new e(0);static ZERO=new e(0);static z=l.z.union([l.z.object({value:l.z.bigint()}).transform(t=>new e(t.value)),l.z.string().transform(t=>new e(BigInt(t))),l.z.number().transform(t=>new e(t)),l.z.bigint().transform(t=>new e(t)),l.z.instanceof(e),l.z.instanceof(O).transform(t=>new e(t)),l.z.custom(e=>e instanceof dc).transform(t=>new e(t))])},dc=class e extends pa{constructor(e){T(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(t){return this.valueOf()===new e(t).valueOf()}get period(){return k.seconds(1/this.valueOf())}sampleCount(e){return new k(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new A(t).valueOf()}span(e){return k.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/new A(t).valueOf())}add(t){return new e(Ja(this.valueOf(),new e(t).valueOf()))}sub(t){return new e(qa(this.valueOf(),new e(t).valueOf()))}mult(t){return new e($a(this.valueOf(),t))}div(t){return new e(eo(this.valueOf(),t))}static hz(t){return new e(t)}static khz(t){return e.hz(t*1e3)}static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)])},A=class e extends pa{constructor(e){T(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new fc(e*this.valueOf())}add(t){return new e(Ja(this.valueOf(),new e(t).valueOf()))}sub(t){return new e(qa(this.valueOf(),new e(t).valueOf()))}mult(t){return new e($a(this.valueOf(),t))}div(t){return new e(eo(this.valueOf(),t))}static UNKNOWN=new e(0);static BIT128=new e(16);static BIT64=new e(8);static BIT32=new e(4);static BIT16=new e(2);static BIT8=new e(1);static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)])},j=class e{start;end;constructor(e,t){typeof e==`object`&&`start`in e?(this.start=new O(e.start),this.end=new O(e.end)):(this.start=new O(e),this.end=new O(t))}get span(){return new k(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,t=k.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),r=this.end.sub(e.end).valueOf();return n<0&&(n=-n),r<0&&(r=-r),n<=t.valueOf()&&r<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString(`preciseDate`)} - ${this.span.toString()}`}overlapsWith(e,t=k.ZERO){e=e.makeValid();let n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;let r=O.max(n.start,e.start),i=O.min(n.end,e.end);return i.before(r)?!1:new k(i.sub(r)).greaterThanOrEqual(t)}contains(t){return t instanceof e?this.contains(t.start)&&this.contains(t.end):this.start.beforeEq(t)&&this.end.after(t)}boundBy(t){let n=new e(this.start,this.end);return t.start.after(this.start)&&(n.start=t.start),t.start.after(this.end)&&(n.end=t.start),t.end.before(this.end)&&(n.end=t.end),t.end.before(this.start)&&(n.start=t.end),n}static max(...t){return new e(O.min(...t.map(e=>e.start)),O.max(...t.map(e=>e.end)))}static MAX=new e(O.MIN,O.MAX);static ZERO=new e(O.ZERO,O.ZERO);static z=l.z.union([l.z.object({start:O.z,end:O.z}).transform(t=>new e(t.start,t.end)),l.z.instanceof(e)]);static boundedZ=e.z.refine(({isValid:e})=>e,{message:`Time range start time must be before or equal to time range end time`}).refine(({end:e})=>e.valueOf()<=Ua,{message:`Time range end time must be less than or equal to the maximum value of an int64`}).refine(({start:e})=>e.valueOf()>=Ha,{message:`Time range start time must be greater than or equal to the minimum value of an int64`});static sort(e,t){return O.sort(e.start,t.start)||O.sort(e.end,t.end)}static merge(...t){return e.max(...t.map(t=>new e(t).makeValid()))}},M=class e extends pa{constructor(t){if(T(t)&&(t=t.value),t instanceof e||typeof t==`string`||typeof t.valueOf()==`string`)super(t.valueOf());else{let n=e.ARRAY_CONSTRUCTOR_DATA_TYPES.get(t.constructor.name);if(n==null)throw Error(`unable to find data type for ${t.toString()}`);super(n.valueOf())}}get Array(){let t=e.ARRAY_CONSTRUCTORS.get(this.toString());if(t==null)throw Error(`unable to find array constructor for ${this.valueOf()}`);return t}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(e=>this.equals(e))}toString(t=!1){return t?e.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(e.JSON)||this.equals(e.STRING)||this.equals(e.BYTES)}get isNumeric(){return!this.isVariable&&!this.equals(e.UUID)}get isInteger(){let e=this.toString();return e.startsWith(`int`)||e.startsWith(`uint`)}get isFloat(){return this.toString().startsWith(`float`)}get density(){let t=e.DENSITIES.get(this.toString());if(t==null)throw Error(`unable to find density for ${this.valueOf()}`);return t}get isUnsignedInteger(){return this.equals(e.UINT8)||this.equals(e.UINT16)||this.equals(e.UINT32)||this.equals(e.UINT64)}get isSignedInteger(){return this.equals(e.INT8)||this.equals(e.INT16)||this.equals(e.INT32)||this.equals(e.INT64)}canSafelyCastTo(t){return this.equals(t)?!0:!this.isNumeric||!t.isNumeric||this.isVariable||t.isVariable||this.isUnsignedInteger&&t.isSignedInteger?!1:this.isFloat?t.isFloat&&this.density.valueOf()<=t.density.valueOf():this.equals(e.INT32)&&t.equals(e.FLOAT64)||this.equals(e.INT8)&&t.equals(e.FLOAT32)?!0:this.isInteger&&t.isInteger?this.density.valueOf()<=t.density.valueOf()&&this.isUnsignedInteger===t.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return e.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new e(`unknown`);static FLOAT64=new e(`float64`);static FLOAT32=new e(`float32`);static INT64=new e(`int64`);static INT32=new e(`int32`);static INT16=new e(`int16`);static INT8=new e(`int8`);static UINT64=new e(`uint64`);static UINT32=new e(`uint32`);static UINT16=new e(`uint16`);static UINT8=new e(`uint8`);static TIMESTAMP=new e(`timestamp`);static UUID=new e(`uuid`);static STRING=new e(`string`);static JSON=new e(`json`);static BYTES=new e(`bytes`);static ARRAY_CONSTRUCTORS=new Map([[e.UINT8.toString(),Uint8Array],[e.UINT16.toString(),Uint16Array],[e.UINT32.toString(),Uint32Array],[e.UINT64.toString(),BigUint64Array],[e.FLOAT32.toString(),Float32Array],[e.FLOAT64.toString(),Float64Array],[e.INT8.toString(),Int8Array],[e.INT16.toString(),Int16Array],[e.INT32.toString(),Int32Array],[e.INT64.toString(),BigInt64Array],[e.TIMESTAMP.toString(),BigInt64Array],[e.STRING.toString(),Uint8Array],[e.JSON.toString(),Uint8Array],[e.UUID.toString(),Uint8Array],[e.BYTES.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,e.UINT8],[Uint16Array.name,e.UINT16],[Uint32Array.name,e.UINT32],[BigUint64Array.name,e.UINT64],[Float32Array.name,e.FLOAT32],[Float64Array.name,e.FLOAT64],[Int8Array.name,e.INT8],[Int16Array.name,e.INT16],[Int32Array.name,e.INT32],[BigInt64Array.name,e.INT64]]);static DENSITIES=new Map([[e.UINT8.toString(),A.BIT8],[e.UINT16.toString(),A.BIT16],[e.UINT32.toString(),A.BIT32],[e.UINT64.toString(),A.BIT64],[e.FLOAT32.toString(),A.BIT32],[e.FLOAT64.toString(),A.BIT64],[e.INT8.toString(),A.BIT8],[e.INT16.toString(),A.BIT16],[e.INT32.toString(),A.BIT32],[e.INT64.toString(),A.BIT64],[e.TIMESTAMP.toString(),A.BIT64],[e.STRING.toString(),A.UNKNOWN],[e.JSON.toString(),A.UNKNOWN],[e.UUID.toString(),A.BIT128],[e.BYTES.toString(),A.UNKNOWN]]);static ALL=[e.UNKNOWN,e.UINT8,e.UINT16,e.UINT32,e.UINT64,e.INT8,e.INT16,e.INT32,e.INT64,e.FLOAT32,e.FLOAT64,e.TIMESTAMP,e.UUID,e.STRING,e.JSON,e.BYTES];static SHORT_STRINGS=new Map([[e.UINT8.toString(),`u8`],[e.UINT16.toString(),`u16`],[e.UINT32.toString(),`u32`],[e.UINT64.toString(),`u64`],[e.INT8.toString(),`i8`],[e.INT16.toString(),`i16`],[e.INT32.toString(),`i32`],[e.INT64.toString(),`i64`],[e.FLOAT32.toString(),`f32`],[e.FLOAT64.toString(),`f64`],[e.TIMESTAMP.toString(),`ts`],[e.UUID.toString(),`uuid`],[e.STRING.toString(),`str`],[e.JSON.toString(),`json`],[e.BYTES.toString(),`bytes`]]);static BIG_INT_TYPES=[e.INT64,e.UINT64,e.TIMESTAMP];static z=l.z.union([l.z.string().transform(t=>new e(t)),l.z.instanceof(e)])},fc=class e extends pa{constructor(e){T(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return T(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return T(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(t){return T(t)&&(t=t.value),new e(Ja(this.valueOf(),t.valueOf()))}sub(t){return T(t)&&(t=t.value),new e(qa(this.valueOf(),t.valueOf()))}mult(t){return new e($a(this.valueOf(),t))}div(t){return new e(eo(this.valueOf(),t))}truncate(t){return new e(Math.trunc(this.valueOf()/new e(t).valueOf())*new e(t).valueOf())}remainder(t){return e.bytes(this.valueOf()%new e(t).valueOf())}get gigabytes(){return this.valueOf()/e.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/e.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/e.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/e.TERABYTE.valueOf()}toString(){let t=this.truncate(e.TERABYTE),n=this.truncate(e.GIGABYTE),r=this.truncate(e.MEGABYTE),i=this.truncate(e.KILOBYTE),a=this.truncate(e.BYTE),o=t,s=n.sub(t),c=r.sub(n),l=i.sub(r),u=a.sub(i),d=``;return o.isZero||(d+=`${o.terabytes}TB `),s.isZero||(d+=`${s.gigabytes}GB `),c.isZero||(d+=`${c.megabytes}MB `),l.isZero||(d+=`${l.kilobytes}KB `),(!u.isZero||d===``)&&(d+=`${u.valueOf()}B`),d.trim()}static bytes(t=1){return new e(t)}static BYTE=new e(1);static kilobytes(t=1){return e.bytes(new e(t).valueOf()*1e3)}static KILOBYTE=e.kilobytes(1);static megabytes(t=1){return e.kilobytes(new e(t).valueOf()*1e3)}static MEGABYTE=e.megabytes(1);static gigabytes(t=1){return e.megabytes(new e(t).valueOf()*1e3)}static GIGABYTE=e.gigabytes(1);static terabytes(t){return e.gigabytes(new e(t).valueOf()*1e3)}static TERABYTE=e.terabytes(1);static ZERO=new e(0);static z=l.z.union([l.z.number().transform(t=>new e(t)),l.z.instanceof(e)]);get isZero(){return this.valueOf()===0}},pc=l.z.object({start:l.z.number(),end:l.z.number()}),mc=l.z.union([l.z.instanceof(Uint8Array),l.z.instanceof(Uint16Array),l.z.instanceof(Uint32Array),l.z.instanceof(BigUint64Array),l.z.instanceof(Float32Array),l.z.instanceof(Float64Array),l.z.instanceof(Int8Array),l.z.instanceof(Int16Array),l.z.instanceof(Int32Array),l.z.instanceof(BigInt64Array)]),hc=e=>{let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===`bigint`||e instanceof O||e instanceof k||e instanceof Date},gc=(e,t,n,r=0)=>e.usesBigInt&&!t.usesBigInt?Number(n)-Number(r):!e.usesBigInt&&t.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):qa(n,r),_c=j.z,vc=O.z,yc=k.z,bc=dc.z,xc=fc.z,Sc=M.z,Cc=j.boundedZ,wc=/^(?:[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 Tc(e){return typeof e==`string`&&wc.test(e)}var N=[];for(let e=0;e<256;++e)N.push((e+256).toString(16).slice(1));function Ec(e,t=0){return(N[e[t+0]]+N[e[t+1]]+N[e[t+2]]+N[e[t+3]]+`-`+N[e[t+4]]+N[e[t+5]]+`-`+N[e[t+6]]+N[e[t+7]]+`-`+N[e[t+8]]+N[e[t+9]]+`-`+N[e[t+10]]+N[e[t+11]]+N[e[t+12]]+N[e[t+13]]+N[e[t+14]]+N[e[t+15]]).toLowerCase()}function Dc(e,t=0){let n=Ec(e,t);if(!Tc(n))throw TypeError(`Stringified UUID is invalid`);return n}typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var Oc=(e,t)=>Dc(e,t),kc=-1,Ac={[Symbol.iterator]:()=>Ac,next:()=>({done:!0,value:void 0})},jc=l.z.string().transform(e=>new Uint8Array(atob(e).split(``).map(e=>e.charCodeAt(0))).buffer),Mc=l.z.union([l.z.null(),l.z.undefined()]).transform(()=>new Uint8Array().buffer),Nc=10,Pc=(e,t)=>{if(e===`number`&&!t.isNumeric)throw Error(`cannot convert series of type ${t.toString()} to number`);if(e===`bigint`&&!t.usesBigInt)throw Error(`cannot convert series of type ${t.toString()} to bigint`)},Fc=`sy_x_telem_series`,Ic=class e{key;discriminator=Fc;dataType;sampleOffset;gl;_data;timeRange=j.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=kc;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=l.z.object({timeRange:j.z.optional(),dataType:M.z,alignment:l.z.coerce.bigint().optional(),data:l.z.union([jc,Mc,l.z.instanceof(ArrayBuffer),l.z.instanceof(Uint8Array)]),glBufferUsage:oc.default(`static`).optional()});static z=e.crudeZ.transform(t=>new e(t));constructor(e){Lc(e)&&(e={data:e}),e.data??=[];let{dataType:t,timeRange:n,sampleOffset:r=0,glBufferUsage:i=`static`,alignment:a=0n,alignmentMultiple:o=1n,key:s=ys(),data:c}=e;if(Rc(c)){let e=c;this.key=e.key,this.dataType=e.dataType,this.sampleOffset=e.sampleOffset,this.gl=e.gl,this._data=e._data,this.timeRange=e.timeRange,this.alignment=e.alignment,this.alignmentMultiple=e.alignmentMultiple,this.cachedMin=e.cachedMin,this.cachedMax=e.cachedMax,this.writePos=e.writePos,this._refCount=e._refCount,this.cachedLength=e.cachedLength;return}let l=hc(c),u=Array.isArray(c);if(t!=null)this.dataType=new M(t);else if(c instanceof ArrayBuffer)throw Error(`cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.`);else if(u||l){let e=c;if(!l){if(c.length===0)throw Error(`cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.`);e=c[0]}if(typeof e==`string`)this.dataType=M.STRING;else if(typeof e==`number`)this.dataType=M.FLOAT64;else if(typeof e==`bigint`)this.dataType=M.INT64;else if(typeof e==`boolean`)this.dataType=M.UINT8;else if(e instanceof O||e instanceof Date||e instanceof O)this.dataType=M.TIMESTAMP;else if(typeof e==`object`)this.dataType=M.JSON;else throw Error(`cannot infer data type of ${typeof e} when constructing a Series from a JS array`)}else this.dataType=new M(c);if(!u&&!l)this._data=c;else if(u&&c.length===0)this._data=new this.dataType.Array([]).buffer;else{let e=l?[c]:c,t=e[0];(t instanceof O||t instanceof Date||t instanceof k)&&(e=e.map(e=>new O(e).valueOf())),this.dataType.equals(M.STRING)?(this.cachedLength=e.length,this._data=new TextEncoder().encode(`${e.join(`
25
+ `)}\n`).buffer):this.dataType.equals(M.JSON)?(this.cachedLength=e.length,this._data=new TextEncoder().encode(`${e.map(e=>Go.encodeString(e)).join(`
26
+ `)}\n`).buffer):this.dataType.usesBigInt&&typeof t==`number`?this._data=new this.dataType.Array(e.map(e=>BigInt(Math.round(e)))).buffer:!this.dataType.usesBigInt&&typeof t==`bigint`?this._data=new this.dataType.Array(e.map(Number)).buffer:this._data=new this.dataType.Array(e).buffer}this.key=s,this.alignment=a,this.alignmentMultiple=o,this.sampleOffset=r??0,this.timeRange=n??j.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:t,dataType:n,...r}){if(t===0)throw Error(`[Series] - cannot allocate an array of length 0`);let i=new e({data:new new M(n).Array(t).buffer,dataType:n,...r});return i.writePos=0,i}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 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===kc)return 0;let t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===kc)return 0;let t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this.cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.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===kc?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
27
+ `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(M.JSON))throw Error(`cannot parse non-JSON series as JSON`);return this.toStrings().map(t=>e.parse(Go.decodeString(t)))}get byteCapacity(){return new fc(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===kc?this.byteCapacity:this.dataType.isVariable?new fc(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength==null?this.dataType.isVariable?this.calculateCachedLength():this.writePos===kc?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos:this.cachedLength}calculateCachedLength(){if(!this.dataType.isVariable)throw Error(`cannot calculate length of a non-variable length data type`);let e=0,t=[0];return this.data.forEach((n,r)=>{n===Nc&&(e++,t.push(r+1))}),this._cachedIndexes=t,this.cachedLength=e,e}convert(t,n=0){if(this.dataType.equals(t))return this;let r=new t.Array(this.length);for(let e=0;e<this.length;e++)r[e]=gc(this.dataType,t,this.data[e],n);return new e({data:r.buffer,dataType:t,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){return this.length===0?-1/0:(this.dataType.equals(M.TIMESTAMP)?this.cachedMax=this.data[this.data.length-1]:(this.dataType.usesBigInt,this.cachedMax=this.data.reduce((e,t)=>e>t?e:t)),this.cachedMax)}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw Error(`cannot calculate maximum on a variable length data type`);return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),Ja(this.cachedMax,this.sampleOffset))}calcRawMin(){return this.length===0?1/0:(this.dataType.equals(M.TIMESTAMP)?this.cachedMin=this.data[0]:(this.dataType.usesBigInt,this.cachedMin=this.data.reduce((e,t)=>e<t?e:t)),this.cachedMin)}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw Error(`cannot calculate minimum on a variable length data type`);return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),Ja(this.cachedMin,this.sampleOffset))}get bounds(){return E(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){let t=e.cachedMin??e.calcRawMin();t<this.cachedMin&&(this.cachedMin=t)}if(this.cachedMax!=null){let t=e.cachedMax??e.calcRawMax();t>this.cachedMax&&(this.cachedMax=t)}}atAlignment(e,t){let n=Number((e-this.alignment)/this.alignmentMultiple);if(n<0||n>=this.length){if(t===!0)throw Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(M.UUID))return this.atUUID(e,t);e<0&&(e=this.length+e);let n=this.data[e];if(n==null){if(t===!0)throw Error(`[series] - no value at index ${e}`);return}return Ja(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);let n=Oc(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){let n=0,r=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],r=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let t=0;t<this.data.length;t++)if(this.data[t]===Nc){if(e===0){r=t;break}n=t+1,e--}if(r===0&&(r=this.data.length),n>=r||e>0){if(t)throw Error(`[series] - no value at index ${e}`);return}}let i=this.data.slice(n,r);return this.dataType.equals(M.STRING)?new TextDecoder().decode(i):Ti(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let t=0,n=this.length-1,r=Qo(e);for(;t<=n;){let i=Math.floor((t+n)/2),a=r(this.at(i,!0),e);if(a===0)return i;a<0?t=i+1:n=i-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(M.FLOAT32)&&!this.dataType.equals(M.UINT8))throw Error(`Only FLOAT32 and UINT8 arrays can be used in WebGL`);let{buffer:t,bufferUsage:n,prevBuffer:r}=this.gl;if(t??(this.gl.buffer=e.createBuffer()),this.writePos!==r)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==kc){r===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);let t=this.dataType.density.size(r).valueOf(),n=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,t,n.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n===`static`?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=kc}as(e){return Pc(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:qc(this.alignmentBounds.lower),upper:qc(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return E(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 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){let e=new Bc(this);return this.dataType.equals(M.JSON)?new Vc(e):e}return this.dataType.equals(M.UUID)?new Hc(this):new Uc(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new zc(this,e,t??this.length)}subAlignmentIterator(e,t){let n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),r=Math.ceil(Number(t-this.alignment)/Number(this.alignmentMultiple));return new zc(this,n,r)}subBytes(t,n){return t>=0&&(n==null||n>=this.byteLength.valueOf())?this:new e({data:this.data.subarray(t,n),dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}sliceSub(t,n,r){if(n<=0&&(r==null||r>=this.length))return this;let i;return i=t?this.data.subarray(n,r):this.data.slice(n,r),new e({data:i,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(t){return new e({data:this.buffer,dataType:this.dataType,timeRange:j.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:`static`,alignment:t})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(e=>e.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=`,`;e+=`...,`;for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=`,`)}return e+=`])`,e}},Lc=e=>e==null?!1:Array.isArray(e)||e instanceof ArrayBuffer||ArrayBuffer.isView(e)&&!(e instanceof DataView)||e instanceof Ic?!0:hc(e),Rc=bs(Fc,Ic),zc=class{series;end;index;constructor(e,t,n){this.series=e;let r=E(0,e.length+1);this.end=wo(r,n),this.index=wo(r,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},Bc=class{series;index;decoder;constructor(e){if(!e.dataType.isVariable)throw Error(`cannot create a variable series iterator for a non-variable series`);this.series=e,this.index=0,this.decoder=new TextDecoder}next(){let e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==Nc;)this.index++;let n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}},Vc=class e{wrapped;static schema=l.z.record(l.z.string(),l.z.unknown());constructor(e){this.wrapped=e}next(){let t=this.wrapped.next();return t.done===!0?{done:!0,value:void 0}:{done:!1,value:Go.decodeString(t.value,e.schema)}}},Hc=class{series;index;data;density;constructor(e){if(!e.dataType.equals(M.UUID))throw 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=M.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};let e=Oc(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}},Uc=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)}}},Wc=class{series;constructor(e=[]){if(e.length!==0){let t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw Error(`[multi-series] - series must have the same data type`)}this.series=e}as(e){return Pc(e,this.dataType),this}get dataType(){return this.series.length===0?M.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?j.ZERO:new j(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?E(0n,0n):E(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){let t=()=>Error(`cannot push a ${e.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),n=e.dataType.equals(this.dataType);if(Rc(e)){if(this.series.length!==0&&!n)throw t();this.series.push(e)}else{if(this.series.length!==0&&e.series.length!==0&&!n)throw t();this.series.push(...e.series)}}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){for(let n of this.series)if(To(n.alignmentBounds,e))return n.atAlignment(e,t);if(t)throw Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(let n of this.series){if(e<n.length)return n.at(e,t);e-=n.length}if(t)throw Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new Kc(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return Ac;let n=0;for(let t=0;t<this.series.length;t++){let r=this.series[t];if(e<r.alignment)break;if(e>=r.alignmentBounds.upper)n+=r.length;else if(To(r.alignmentBounds,e)){n+=Math.ceil(Number(e-r.alignment)/Number(r.alignmentMultiple));break}}let r=0;for(let e=0;e<this.series.length;e++){let n=this.series[e];if(t<n.alignment)break;if(t>=n.alignmentBounds.upper)r+=n.length;else if(To(n.alignmentBounds,t)){r+=Math.ceil(Number(t-n.alignment)/Number(n.alignmentMultiple));break}}return new Kc(this,n,r)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return Ac;t=Math.min(t,Number(this.distance(e,this.alignmentBounds.upper)));let n=0;for(let t=0;t<this.series.length;t++){let r=this.series[t];if(e<r.alignment)break;if(e>=r.alignmentBounds.upper)n+=r.length;else if(To(r.alignmentBounds,e)){n+=Number(e-r.alignment);break}}return new Kc(this,n,n+t)}updateGLBuffer(e){this.series.forEach(t=>t.updateGLBuffer(e))}get bounds(){return Eo(this.series.map(e=>e.bounds))}get byteLength(){return new fc(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){let e=new this.dataType.Array(this.length),t=0;for(let n of this.series)e.set(n.data,t),t+=n.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){return Do(this.series.map(e=>e.alignmentBounds),e,t)}acquire(e){this.series.forEach(t=>t.acquire(e))}release(){this.series.forEach(e=>e.release())}distance(e,t){return Oo(this.series.map(e=>e.alignmentBounds),e,t)}parseJSON(e){if(!this.dataType.equals(M.JSON))throw Error(`cannot parse non-JSON series as JSON`);return this.series.flatMap(t=>t.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new Gc(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}},Gc=class{series;seriesIndex;internal;constructor(e){this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){let 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}},Kc=class{series;index;end;constructor(e,t,n){this.series=e,this.end=n,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}},qc=e=>({domain:e>>32n,sample:e&4294967295n}),Jc=C({DataType:()=>M,Density:()=>A,MultiSeries:()=>Wc,Rate:()=>dc,Series:()=>Ic,Size:()=>fc,TimeRange:()=>j,TimeSpan:()=>k,TimeStamp:()=>O,convertDataType:()=>gc,dataTypeZ:()=>Sc,isCrudeSeries:()=>Lc,isTelemValue:()=>hc,numericTimeRangeZ:()=>pc,rateZ:()=>bc,sizeZ:()=>xc,timeRangeBoundedZ:()=>Cc,timeRangeZ:()=>_c,timeSpanZ:()=>yc,timeStampZ:()=>vc,typedArrayZ:()=>mc}),Yc=async e=>await new Promise(t=>setTimeout(t,k.fromMilliseconds(e).milliseconds)),Xc=C({Breaker:()=>Zc,breakerConfigZ:()=>Qc}),Zc=class{config;retries;interval;constructor(e){this.config={baseInterval:new k(e?.baseInterval??k.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Yc},this.retries=0,this.interval=new k(this.config.baseInterval)}async wait(){let{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),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}},Qc=l.z.object({baseInterval:k.z.optional(),maxRetries:l.z.number().optional(),scale:l.z.number().optional()}),$c=l.z.string().regex(/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i),el=Mo,tl=l.z.number().min(0).max(1),nl=l.z.tuple([el,el,el,tl]),rl=l.z.tuple([el,el,el]),il=l.z.object({rgba255:nl}),al=l.z.object({r:el,g:el,b:el,a:tl}),ol=l.z.number().min(0).max(360),sl=l.z.number().min(0).max(100),cl=l.z.number().min(0).max(100),ll=l.z.tuple([ol,sl,cl,tl]),ul=l.z.union([$c,rl,nl,ll,il,al]),dl=ul.transform(e=>P(e)),fl=e=>dl.safeParse(e).success,pl=e=>nl.safeParse(e).success,ml=(e=>{if(e==null)return;let t=dl.safeParse(e);if(t.success)return _l(t.data);if(typeof e==`string`)return e;throw t.error}),P=(e,t=1)=>{if(e=ul.parse(e),typeof e==`string`)return Fl(e,t);if(Array.isArray(e)){if(e.length<3||e.length>4)throw Error(`Invalid color: [${e.join(`, `)}]`);return e.length===3?[...e,t]:e}return`a`in e&&`r`in e?[e.r,e.g,e.b,e.a]:e.rgba255},hl=(e,t)=>{if(e==null||t==null)return e==t;let n=P(e),r=P(t);return n.every((e,t)=>e===r[t])},gl=(e=>{if(e==null)return;let[t,n,r,i]=P(e),a=Math.round(i*255);return`#${Ll(t)}${Ll(n)}${Ll(r)}${a===255?``:Ll(a)}`}),_l=e=>{let[t,n,r,i]=P(e);return`rgba(${t}, ${n}, ${r}, ${i})`},vl=e=>`rgb(${yl(e)})`,yl=e=>{let[t,n,r]=P(e);return`${t}, ${n}, ${r}`},bl=e=>[...xl(e),Tl(e)],xl=e=>[Sl(e)/255,Cl(e)/255,wl(e)/255],Sl=e=>P(e)[0],Cl=e=>P(e)[1],wl=e=>P(e)[2],Tl=e=>P(e)[3],El=e=>hl(Il,e),Dl=e=>Wl(P(e)),Ol=(e,t)=>{let[n,r,i]=P(e);if(t>100)throw Error(`Color opacity must be between 0 and 100, got ${t}`);return t>1&&(t/=100),[n,r,i,t]},kl=e=>{let[t,n,r]=xl(e).map(e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4);return Number((.2126*t+.7152*n+.0722*r).toFixed(3))},Al=e=>{let[t,n,r]=xl(e);return 1-(Math.max(t,n,r)-Math.min(t,n,r))},jl=(e,t)=>{let n=P(e),r=P(t),i=kl(n),a=kl(r);return(Math.max(i,a)+.5)/(Math.min(i,a)+.5)},Ml=(e,...t)=>{if(t.length===0)throw Error(`[Color.pickByContrast] - must provide at least one color`);let n=P(e),[r]=t.sort((e,t)=>jl(n,t)-jl(n,e));return P(r)},Nl=e=>kl(e)<.5,Pl=e=>kl(e)>.5,Fl=(e,t=1)=>(e=$c.parse(e),e=zl(e),[Rl(e,0),Rl(e,2),Rl(e,4),e.length===8?Rl(e,6)/255:t]),Il=[0,0,0,0],Ll=e=>Math.floor(e).toString(16).padStart(2,`0`),Rl=(e,t)=>parseInt(e.slice(t,t+2),16),zl=e=>e.startsWith(`#`)?e.slice(1):e,Bl={black:`#000000`,white:`#ffffff`,red:`#ff0000`,green:`#008000`,blue:`#0000ff`,yellow:`#ffff00`,cyan:`#00ffff`,magenta:`#ff00ff`,silver:`#c0c0c0`,gray:`#808080`,grey:`#808080`,maroon:`#800000`,olive:`#808000`,lime:`#00ff00`,aqua:`#00ffff`,teal:`#008080`,navy:`#000080`,fuchsia:`#ff00ff`,purple:`#800080`,orange:`#ffa500`,brown:`#a52a2a`,tan:`#d2b48c`,gold:`#ffd700`,indigo:`#4b0082`,violet:`#ee82ee`,pink:`#ffc0cb`,coral:`#ff7f50`,salmon:`#fa8072`,khaki:`#f0e68c`,crimson:`#dc143c`,transparent:`transparent`},Vl=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!(t===`transparent`||t===`none`)){if(t.startsWith(`#`)){if(t.length===4){let e=t[1],n=t[2],r=t[3],i=`#${e}${e}${n}${n}${r}${r}`;if($c.safeParse(i).success)return Fl(i)}return(t.length===7||t.length===9)&&$c.safeParse(t).success?Fl(t):void 0}if(t.startsWith(`rgb`)){let e=t.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(e){let[,t,n,r,i]=e;return[parseInt(t,10),parseInt(n,10),parseInt(r,10),i?parseFloat(i):1]}}if(Bl[t])return Fl(Bl[t])}},Hl=e=>{e=ll.parse(e);let[t,n,r]=e,i=e[3];t/=360,n/=100,r/=100;let a,o,s;if(n===0)a=o=s=r;else{let e=r<.5?r*(1+n):r+n-r*n,i=2*r-e;a=Ul(i,e,t+1/3),o=Ul(i,e,t),s=Ul(i,e,t-1/3)}return[Math.round(a*255),Math.round(o*255),Math.round(s*255),i]},Ul=(e,t,n)=>(n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e),Wl=e=>{e=nl.parse(e);let[t,n,r]=e,i=e[3];t/=255,n/=255,r/=255;let a=Math.max(t,n,r),o=Math.min(t,n,r),s,c,l=(a+o)/2;if(a===o)s=c=0;else{let e=a-o;c=l>.5?e/(2-a-o):e/(a+o),s=a===t?(n-r)/e+(n<r?6:0):a===n?(r-t)/e+2:(t-n)/e+4,s/=6}return s*=360,c*=100,l*=100,[Math.round(s),Math.round(c),Math.round(l),i]},Gl=P(`#000000`),Kl=P(`#ffffff`),ql=l.z.object({key:l.z.string(),color:ul,position:l.z.number(),switched:l.z.boolean().optional()}),Jl=l.z.array(ql),Yl=(e,t)=>{if(e.length===0)return Il;if(e=e.slice().sort((e,t)=>e.position-t.position),t<=e[0].position)return P(e[0].color);if(t>=e[e.length-1].position)return P(e[e.length-1].color);for(let n=0;n<e.length-1;n++){let r=e[n],i=e[n+1];if(t<r.position||t>i.position)continue;if(t===r.position)return P(r.color);if(t===i.position)return P(i.color);let a=(t-r.position)/(i.position-r.position),o=P(r.color),s=P(i.color);return P([Math.round(Sl(o)+a*(Sl(s)-Sl(o))),Math.round(Cl(o)+a*(Cl(s)-Cl(o))),Math.round(wl(o)+a*(wl(s)-wl(o))),Tl(o)+a*(Tl(s)-Tl(o))])}return P(e[e.length-1].color)},Xl=l.z.object({key:l.z.string(),name:l.z.string(),color:dl}),Zl=l.z.object({key:l.z.string(),name:l.z.string(),swatches:l.z.array(Xl)}),Ql=C({BLACK:()=>Gl,WHITE:()=>Kl,ZERO:()=>Il,aValue:()=>Tl,bValue:()=>wl,colorZ:()=>dl,construct:()=>P,contrast:()=>jl,crudeZ:()=>ul,cssString:()=>ml,equals:()=>hl,fromCSS:()=>Vl,fromGradient:()=>Yl,fromHSLA:()=>Hl,gValue:()=>Cl,gradientZ:()=>Jl,grayness:()=>Al,hex:()=>gl,hsla:()=>Dl,isColor:()=>pl,isCrude:()=>fl,isDark:()=>Nl,isLight:()=>Pl,isZero:()=>El,luminance:()=>kl,paletteZ:()=>Zl,pickByContrast:()=>Ml,rValue:()=>Sl,rgbCSS:()=>vl,rgbString:()=>yl,rgba1:()=>bl,rgbaCSS:()=>_l,setAlpha:()=>Ol,stopZ:()=>ql}),$l=Mo,eu=function(e){return e[e.exclusive=0]=`exclusive`,e[e.shared=1]=`shared`,e}({}),tu=l.z.enum(eu),nu=l.z.object({key:l.z.string(),name:l.z.string(),group:l.z.uint32().optional()}),ru=e=>l.z.object({subject:nu,resource:e,authority:$l}),iu={lower:0,upper:256},au=(...e)=>t=>t.filter(t=>{let n=!1;return t.to!=null&&(n=e.includes(t.to.resource)),t.from!=null&&!n&&(n=e.includes(t.from.resource)),n}),ou=e=>l.z.object({from:ru(e),to:l.z.null().optional()}),su=e=>l.z.object({from:l.z.null().optional(),to:ru(e)}),cu=e=>l.z.union([ou(e),su(e),l.z.object({from:ru(e),to:ru(e)})]),F=C({ABSOLUTE_AUTHORITY:()=>255,AUTHORITY_BOUNDS:()=>iu,Concurrency:()=>eu,ZERO_AUTHORITY:()=>0,acquireZ:()=>su,authorityZ:()=>$l,concurrencyZ:()=>tu,filterTransfersByChannelKey:()=>au,releaseZ:()=>ou,stateZ:()=>ru,subjectZ:()=>nu,transferZ:()=>cu}),lu=C({formatValue:()=>uu}),uu=e=>{switch(typeof e){case`bigint`:case`number`:return e.toString();case`boolean`:return e?`1`:`0`;case`undefined`:return``;case`string`:case`symbol`:case`function`:return fu(e.toString());case`object`:return e==null?``:fu(JSON.stringify(e))}},du=/[",\n]/,fu=e=>du.test(e)?`"${e.replace(/"/g,`""`)}"`:e,pu=(e,t)=>{let n=null;return t===0?e:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>e(...r),t)}};l.z.string().regex(/^(?:$|(?:\/(?:[^~/]|~0|~1)*)+)$/,`must be a valid JSON pointer (RFC 6901)`),l.z.union([l.z.string(),l.z.number(),l.z.boolean(),l.z.null()]),l.z.enum([`string`,`number`,`boolean`,`null`]),l.z.object({key:l.z.string(),value:l.z.string()});var mu=C({keyZ:()=>hu,labelZ:()=>gu,newZ:()=>_u}),hu=l.z.uuid(),gu=l.z.object({key:hu,name:l.z.string().min(1),color:dl}),_u=gu.partial({key:!0}),vu=C({compareSemVer:()=>xu,createMigration:()=>Tu,migrator:()=>Eu,semVerNewer:()=>Cu,semVerOlder:()=>wu,semVerZ:()=>yu,versionsEqual:()=>Su}),yu=l.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/),bu=(e,t)=>{let n=e.split(`.`),r=t.split(`.`),i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=n[e],i=r[e];if(t===void 0)return-1;if(i===void 0)return 1;let a=/^\d+$/.test(t),o=/^\d+$/.test(i);if(a&&!o)return-1;if(!a&&o)return 1;if(a&&o){let e=parseInt(t,10),n=parseInt(i,10);if(e<n)return-1;if(e>n)return 1}else{if(t<i)return-1;if(t>i)return 1}}return 0},xu=((e,t,n={})=>{n.checkMajor??=!0,n.checkMinor??=!0,n.checkPatch??=!0;let r=yu.parse(e),i=yu.parse(t),[a,o]=r.split(`-`),[s,c]=i.split(`-`),[l,u,d]=a.split(`.`).map(Number),[f,p,m]=s.split(`.`).map(Number);if(n.checkMajor){if(l<f)return-1;if(l>f)return 1}if(n.checkMinor){if(u<p)return-1;if(u>p)return 1}if(n.checkPatch){if(d<m)return-1;if(d>m)return 1}return o===void 0&&c===void 0?0:o===void 0?1:c===void 0?-1:bu(o,c)}),Su=(e,t,n={})=>cs(xu(e,t,n)),Cu=(e,t,n={})=>os(xu(e,t,n)),wu=(e,t,n={})=>as(xu(e,t,n)),Tu=({name:e,migrate:t})=>n=>{try{let r=t(n);return console.log(`${e} migrated: ${n.version} -> ${r.version}`),r}catch(t){throw console.log(`${e} failed to migrate from ${n.version}`),console.error(t),t}},Eu=({name:e,migrations:t,targetSchema:n,defaultVersion:r,def:i})=>{let a=Object.keys(t).sort(xu).pop();if(a==null)return t=>{if(t.version??=r,t.version!==i.version)return console.log(`${e} version ${t.version} is newer than latest version of ${i.version}.
12
28
  Returning default instead.
13
- `),i;try{return n==null?t:n.parse(t)}catch(t){return console.log(`${e} failed to parse default. Exiting with default`),console.error(t),i}};let o=Object.keys(t).length,s=!1,c=n=>{try{if(o===0||xl(n.version,a))return console.log(s?`${e} ${n.version} now up to date`:`${e} version ${n.version} is up to date with target version ${i.version}`),n;let r=t[n.version],l=r(n);return s=!0,c(l)}catch(t){return console.log(`${e} failed to migrate from ${n.version} to ${a}`),console.error(t),i}};return t=>{try{if(t.version==null)if(r!=null)console.log(`${e} version is null. Setting version to default of ${r}`),t.version=r;else return console.log(`${e} version is null and no default version set. Exiting with default`),i;return c(t)}catch(t){return console.log(`${e} failed to parse final result. Exiting with default`),console.error(t),i}}};l.z.enum([`standard`,`scientific`,`engineering`]);var Tl=C({BaseObserver:()=>Dl,Observer:()=>El}),El=class{handlers;transform;closer;constructor(e,t){this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){let[n,r]=this.transform(e);if(!r)return;t=n}this.handlers.forEach((e,n)=>n(t))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}},Dl=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((t,n)=>n(e))}},I=C({entries:()=>Al,keyZ:()=>Ol,map:()=>jl,nullishToEmpty:()=>Pl,omit:()=>Nl,purgeUndefined:()=>Ml,unknownZ:()=>kl}),Ol=l.z.union([l.z.string(),l.z.number()]),kl=()=>l.z.record(Ol,l.z.unknown()),Al=e=>Object.entries(e),jl=(e,t)=>Object.fromEntries(Al(e).map(([e,n])=>[e,t(n,e)])),Ml=e=>Object.fromEntries(Al(e).filter(([e,t])=>t!==void 0)),Nl=(e,...t)=>{let n={...e};for(let e of t)delete n[e];return n},Pl=()=>l.z.union([l.z.union([l.z.null(),l.z.undefined()]).transform(()=>({})),kl()]),Fl=()=>typeof process<`u`&&process.versions!=null&&process.versions.node!=null?`node`:typeof window>`u`||window.document===void 0?`webworker`:`browser`,Il=Fl(),Ll=[`macOS`,`Windows`,`Linux`],Rl=[`macos`,`windows`,`linux`],zl={macos:`macOS`,windows:`Windows`,linux:`Linux`},Bl=l.z.enum(Ll).or(l.z.enum(Rl).transform(e=>zl[e])),Vl=()=>{if(typeof window>`u`)return;let e=window.navigator.userAgent.toLowerCase();if(e.includes(`mac`))return`macOS`;if(e.includes(`win`))return`Windows`;if(e.includes(`linux`))return`Linux`},Hl,Ul=((e={})=>{let{force:t,default:n}=e;return t??Hl??(Hl=Vl(),Hl??n)}),Wl=C({OPERATING_SYSTEMS:()=>Ll,RUNTIME:()=>Il,detect:()=>Fl,getOS:()=>Ul,osZ:()=>Bl}),Gl=l.z.object({stack:l.z.string(),error:l.z.instanceof(Error)}),Kl=(e,t)=>{if(!(e instanceof Error))throw e;return ql({variant:`error`,message:t??e.message,description:t==null?void 0:e.message,details:{stack:e.stack??``,error:e}})},ql=e=>({key:Hi(),time:D.now(),name:``,...e}),Jl=(e,t=[])=>{if(e!=null)return Array.isArray(t)?t.includes(e)?e:void 0:t===e?e:void 0},Yl=(e,t=[])=>{if(e!=null)return Array.isArray(t)?t.includes(e)?void 0:e:t===e?void 0:e},Xl={includeTimestamp:!1,includeName:!0},Zl=(e,t={})=>{let n={...Xl,...t},r=[],i=e.variant.toUpperCase();if(n.includeName&&e.name.length>0&&(i+=` [${e.name}]`),i+=`: ${e.message}`,n.includeTimestamp&&(i+=` (${e.time.toString(`dateTime`,`local`)})`),r.push(i),e.description!=null){let t;try{let n=JSON.parse(e.description);t=`Description:\n${JSON.stringify(n,null,2)}`}catch{t=`Description: ${e.description}`}r.push(t)}if(`details`in e&&ii(e.details)){let t=e.details;`stack`in t&&r.push(`Stack Trace:\n${String(t.stack)}`);let n=Object.fromEntries(Object.entries(t).filter(([e])=>e!==`stack`&&e!==`error`));Object.keys(n).length>0&&r.push(`Details:\n${JSON.stringify(n,null,2)}`)}return r.join(`
29
+ `),i;try{return n==null?t:n.parse(t)}catch(t){return console.log(`${e} failed to parse default. Exiting with default`),console.error(t),i}};let o=Object.keys(t).length,s=!1,c=n=>{try{if(o===0||Cu(n.version,a))return console.log(s?`${e} ${n.version} now up to date`:`${e} version ${n.version} is up to date with target version ${i.version}`),n;let r=t[n.version],l=r(n);return s=!0,c(l)}catch(t){return console.log(`${e} failed to migrate from ${n.version} to ${a}`),console.error(t),i}};return t=>{try{if(t.version==null)if(r!=null)console.log(`${e} version is null. Setting version to default of ${r}`),t.version=r;else return console.log(`${e} version is null and no default version set. Exiting with default`),i;return c(t)}catch(t){return console.log(`${e} failed to parse final result. Exiting with default`),console.error(t),i}}};l.z.enum([`standard`,`scientific`,`engineering`]);var Du=C({BaseObserver:()=>ku,Observer:()=>Ou}),Ou=class{handlers;transform;closer;constructor(e,t){this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){let[n,r]=this.transform(e);if(!r)return;t=n}this.handlers.forEach((e,n)=>n(t))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}},ku=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((t,n)=>n(e))}},I=C({entries:()=>Mu,keyZ:()=>Au,map:()=>Nu,nullishToEmpty:()=>Iu,omit:()=>Fu,purgeUndefined:()=>Pu,unknownZ:()=>ju}),Au=l.z.union([l.z.string(),l.z.number()]),ju=()=>l.z.record(Au,l.z.unknown()),Mu=e=>Object.entries(e),Nu=(e,t)=>Object.fromEntries(Mu(e).map(([e,n])=>[e,t(n,e)])),Pu=e=>Object.fromEntries(Mu(e).filter(([e,t])=>t!==void 0)),Fu=(e,...t)=>{let n={...e};for(let e of t)delete n[e];return n},Iu=()=>l.z.union([l.z.union([l.z.null(),l.z.undefined()]).transform(()=>({})),ju()]),Lu=()=>typeof process<`u`&&process.versions!=null&&process.versions.node!=null?`node`:typeof window>`u`||window.document===void 0?`webworker`:`browser`,Ru=Lu(),zu=[`macOS`,`Windows`,`Linux`],Bu=[`macos`,`windows`,`linux`],Vu={macos:`macOS`,windows:`Windows`,linux:`Linux`},Hu=l.z.enum(zu).or(l.z.enum(Bu).transform(e=>Vu[e])),Uu=()=>{if(typeof window>`u`)return;let e=window.navigator.userAgent.toLowerCase();if(e.includes(`mac`))return`macOS`;if(e.includes(`win`))return`Windows`;if(e.includes(`linux`))return`Linux`},Wu,Gu=((e={})=>{let{force:t,default:n}=e;return t??Wu??(Wu=Uu(),Wu??n)}),Ku=C({OPERATING_SYSTEMS:()=>zu,RUNTIME:()=>Ru,detect:()=>Lu,getOS:()=>Gu,osZ:()=>Hu}),qu=l.z.object({message:l.z.string().optional(),description:l.z.string().optional(),details:ju().optional()}),Ju=e=>`toStatus`in e&&typeof e.toStatus==`function`,Yu=e=>{if(!Ju(e))return;let t;try{t=e.toStatus()}catch{return}let n=qu.safeParse(t);return n.success?n.data:void 0},Xu=l.z.object({stack:l.z.string(),error:l.z.instanceof(Error)}).and(ju()),Zu=(e,t)=>{if(!(e instanceof Error))throw e;let n={variant:`error`,message:t??e.message,description:t==null?void 0:e.message,details:{stack:e.stack??``,error:e}},r=Yu(e);return r!=null&&(t!=null&&r.message!=null?n.message=`${t}: ${r.message}`:r.message!=null&&(n.message=r.message),r.description!=null&&(n.description=r.description),r.details!=null&&n.details!=null&&(n.details={...n.details,...r.details})),Qu(n)},Qu=e=>({key:ys(),time:O.now(),name:``,...e}),$u=(e,t=[])=>{if(e!=null)return Array.isArray(t)?t.includes(e)?e:void 0:t===e?e:void 0},ed=(e,t=[])=>{if(e!=null)return Array.isArray(t)?t.includes(e)?void 0:e:t===e?void 0:e},td={includeTimestamp:!1,includeName:!0},nd=e=>{if(e.includes(`
30
+ `))return`Description:\n${e}`;try{let t=JSON.parse(e);return`Description:\n${JSON.stringify(t,null,2)}`}catch{return`Description: ${e}`}},rd=(e,t={})=>{let n={...td,...t},r=[],i=e.variant.toUpperCase();if(n.includeName&&ga(e.name)&&(i+=` [${e.name}]`),i+=`: ${e.message}`,n.includeTimestamp&&(i+=` (${e.time.toString(`dateTime`,`local`)})`),r.push(i),e.description!=null&&r.push(nd(e.description)),`details`in e&&Ni(e.details)){let t=e.details;`stack`in t&&typeof t.stack==`string`&&t.stack!==``&&r.push(`Stack Trace:\n${t.stack}`);let n=Object.fromEntries(Object.entries(t).filter(([e])=>e!==`stack`&&e!==`error`));Object.keys(n).length>0&&r.push(`Details:\n${JSON.stringify(n,null,2)}`)}return r.join(`
14
31
 
15
- `)},Ql=[`success`,`info`,`warning`,`error`,`loading`,`disabled`],$l=l.z.enum(Ql),eu=l.z.literal(`success`),tu=l.z.literal(`info`),nu=l.z.literal(`warning`),ru=l.z.literal(`error`),iu=l.z.literal(`loading`),au=l.z.literal(`disabled`),ou=({details:e,v:t}={})=>l.z.object({key:l.z.string().default(()=>Hi()),name:l.z.string().default(``),variant:t??$l,message:l.z.string(),description:l.z.string().optional(),time:Po.default(()=>D.now()),details:e??l.z.unknown().optional(),labels:hs(ml.array())}),su=({details:e,v:t}={})=>ou({details:e,v:t}).partial({key:!0,name:!0,time:!0}),cu=C({VARIANTS:()=>Ql,create:()=>ql,disabledVariantZ:()=>au,errorVariantZ:()=>ru,exceptionDetailsSchema:()=>Gl,fromException:()=>Kl,infoVariantZ:()=>tu,keepVariants:()=>Jl,loadingVariantZ:()=>iu,newZ:()=>su,removeVariants:()=>Yl,statusZ:()=>ou,successVariantZ:()=>eu,toString:()=>Zl,variantZ:()=>$l,warningVariantZ:()=>nu}),lu=(e,t)=>{if(!t.has(e))return e;let n,r,i=e;for(;t.has(i);){let e=i.match(uu);e?(n=i.slice(0,e.index).trim(),r=parseInt(e[1],10)+1):(n=i,r=1),i=`${n} (${r})`}return i},uu=/\((\d+)\)$/,du=(e,t=``)=>{if(typeof e==`string`)return e;let n=e.length;return n===0?t:n===1?e[0]:n===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(`, `)}, and ${e[n-1]}`},fu=e=>{let t=e.split(` `),n=new Set,r=t.map(e=>e.charAt(0).toLowerCase()).join(``);n.add(r.replace(/-/g,`_`)),n.add(r.replace(/(.)(.)/g,`$1_$2`).replace(/-/g,`_`));let i=/\d+/g;e.match(i)&&t.forEach((e,r)=>{if(i.test(e)){let e=t.map((e,t)=>t===r?e:e.charAt(0).toLowerCase()).join(``);n.add(e.replace(/-/g,`_`)),n.add(e.replace(/(.)(.)/g,`$1_$2`).replace(/-/g,`_`))}});let a=t.map(e=>(e.length>3?e.substring(0,3):e).toLowerCase());return n.add(a.join(``).replace(/-/g,`_`)),n.add(a.join(`_`).replace(/-/g,`_`)),Array.from(n).filter(e=>e.length>=2&&e.length<=12&&!/^\d/.test(e))},pu=(e,t)=>e.startsWith(t)?e.slice(t.length):e,mu=C({createShortIdentifiers:()=>fu,deduplicateFileName:()=>lu,naturalLanguageJoin:()=>du,trimPrefix:()=>pu}),hu=(...e)=>e.map(gu).join(``),gu=e=>(e.endsWith(`/`)||(e+=`/`),e.startsWith(`/`)&&(e=e.slice(1)),e),_u=e=>e.endsWith(`/`)?e.slice(0,-1):e,vu=class e{protocol;host;port;path;constructor({host:e,port:t,protocol:n=``,pathPrefix:r=``}){this.protocol=n,this.host=e,this.port=t,this.path=gu(r)}replace(t){return new e({host:t.host??this.host,port:t.port??this.port,protocol:t.protocol??this.protocol,pathPrefix:t.pathPrefix??this.path})}child(t){return new e({...this,pathPrefix:hu(this.path,t)})}toString(){return _u(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new e({host:`unknown`,port:0})},yu=class extends Zc.createTyped(`sy`){},L=class extends yu.sub(`validation`){},bu=class e extends L.sub(`path`){path;error;static encodedSchema=l.z.object({path:l.z.string().array(),error:Zc.payloadZ});constructor(e,t){let n=w.toArray(e);super(`${n.join(`.`)}: ${t.message}`),this.path=n.flatMap(e=>e.split(`.`)),this.error=t}static decode(t){let n=e.encodedSchema.parse(JSON.parse(t.data));return new e(n.path,Zc.decode(n.error))}},xu=class extends yu.sub(`auth`){},Su=class extends xu.sub(`invalid_token`){},Cu=class extends xu.sub(`expired_token`){};xu.sub(`access_denied`);var wu=class extends yu.sub(`unexpected`){constructor(e){super(`
32
+ `)},id=[`success`,`info`,`warning`,`error`,`loading`,`disabled`],ad=l.z.enum(id),od=l.z.literal(`success`),sd=l.z.literal(`info`),cd=l.z.literal(`warning`),ld=l.z.literal(`error`),ud=l.z.literal(`loading`),dd=l.z.literal(`disabled`),fd=({details:e,v:t}={})=>l.z.object({key:l.z.string().default(()=>ys()),name:l.z.string().default(``),variant:t??ad,message:l.z.string(),description:l.z.string().optional(),time:vc.default(()=>O.now()),details:e??l.z.unknown().optional(),labels:Fi(gu.array())}),pd=({details:e,v:t}={})=>fd({details:e,v:t}).partial({key:!0,name:!0,time:!0}),md=C({VARIANTS:()=>id,create:()=>Qu,disabledVariantZ:()=>dd,errorVariantZ:()=>ld,exceptionDetailsSchema:()=>Xu,fromException:()=>Zu,infoVariantZ:()=>sd,keepVariants:()=>$u,loadingVariantZ:()=>ud,newZ:()=>pd,removeVariants:()=>ed,statusZ:()=>fd,successVariantZ:()=>od,toString:()=>rd,variantZ:()=>ad,warningVariantZ:()=>cd}),hd=(e,t)=>{if(!t.has(e))return e;let n,r,i=e;for(;t.has(i);){let e=i.match(gd);e?(n=i.slice(0,e.index).trim(),r=parseInt(e[1],10)+1):(n=i,r=1),i=`${n} (${r})`}return i},gd=/\((\d+)\)$/,_d=(e,t=``)=>{if(typeof e==`string`)return e;let n=e.length;return n===0?t:n===1?e[0]:n===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(`, `)}, and ${e[n-1]}`},vd=e=>{let t=e.split(` `),n=new Set,r=t.map(e=>e.charAt(0).toLowerCase()).join(``);n.add(r.replace(/-/g,`_`)),n.add(r.replace(/(.)(.)/g,`$1_$2`).replace(/-/g,`_`));let i=/\d+/g;e.match(i)&&t.forEach((e,r)=>{if(i.test(e)){let e=t.map((e,t)=>t===r?e:e.charAt(0).toLowerCase()).join(``);n.add(e.replace(/-/g,`_`)),n.add(e.replace(/(.)(.)/g,`$1_$2`).replace(/-/g,`_`))}});let a=t.map(e=>(e.length>3?e.substring(0,3):e).toLowerCase());return n.add(a.join(``).replace(/-/g,`_`)),n.add(a.join(`_`).replace(/-/g,`_`)),Array.from(n).filter(e=>e.length>=2&&e.length<=12&&!/^\d/.test(e))},yd=(e,t)=>e.startsWith(t)?e.slice(t.length):e,bd=C({createShortIdentifiers:()=>vd,deduplicateFileName:()=>hd,naturalLanguageJoin:()=>_d,trimPrefix:()=>yd}),xd=(...e)=>e.map(Sd).join(``),Sd=e=>(e.endsWith(`/`)||(e+=`/`),e.startsWith(`/`)&&(e=e.slice(1)),e),Cd=e=>e.endsWith(`/`)?e.slice(0,-1):e,wd=class e{protocol;host;port;path;constructor({host:e,port:t,protocol:n=``,pathPrefix:r=``}){this.protocol=n,this.host=e,this.port=t,this.path=Sd(r)}replace(t){return new e({host:t.host??this.host,port:t.port??this.port,protocol:t.protocol??this.protocol,pathPrefix:t.pathPrefix??this.path})}child(t){return new e({...this,pathPrefix:xd(this.path,t)})}toString(){return Cd(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new e({host:`unknown`,port:0})},Td=class extends Gi.createTyped(`sy`){},L=class extends Td.sub(`validation`){},Ed=class e extends L.sub(`path`){path;error;static encodedSchema=l.z.object({path:l.z.string().array(),error:Gi.payloadZ});constructor(e,t){let n=w.toArray(e);super(`${n.join(`.`)}: ${t.message}`),this.path=n.flatMap(e=>e.split(`.`)),this.error=t}static decode(t){let n=e.encodedSchema.parse(JSON.parse(t.data));return new e(n.path,Gi.decode(n.error))}},Dd=class extends Td.sub(`auth`){},Od=class extends Dd.sub(`invalid_token`){},kd=class extends Dd.sub(`expired_token`){};Dd.sub(`access_denied`);var Ad=class extends Td.sub(`unexpected`){constructor(e){super(`
16
33
  Unexpected error encountered:
17
34
 
18
35
  ${e}
19
36
 
20
37
  Please report this to the Synnax team.
21
- `)}},Tu=class extends yu.sub(`query`){},Eu=class extends Tu.sub(`not_found`){},Du=class extends Tu.sub(`multiple_results`){},Ou=class extends yu.sub(`route`){path;constructor(e,t){super(e),this.path=t}},ku=class extends yu.sub(`control`){},Au=class extends ku.sub(`unauthorized`){},ju=class extends yu.sub(`disconnected`){constructor(e=`Operation failed because no Core is connected.`){super(e)}},Mu=class extends yu.sub(`contiguity`){};Zc.register({encode:()=>{throw new Zc.NotImplemented},decode:e=>e.type.startsWith(yu.TYPE)?e.type.startsWith(L.TYPE)?e.type===bu.TYPE?bu.decode(e):new L(e.data):e.type.startsWith(xu.TYPE)?e.type.startsWith(Su.TYPE)?new Su(e.data):e.type.startsWith(Cu.TYPE)?new Cu(e.data):new xu(e.data):e.type.startsWith(wu.TYPE)?new wu(e.data):e.type.startsWith(Tu.TYPE)?e.type.startsWith(Eu.TYPE)?new Eu(e.data):e.type.startsWith(Du.TYPE)?new Du(e.data):new Tu(e.data):e.type.startsWith(ku.TYPE)?e.type.startsWith(Au.TYPE)?new Au(e.data):new ku(e.data):e.type.startsWith(Ou.TYPE)?new Ou(e.data,e.data):new wu(e.data):null});var Nu=async(e,t)=>{let[n,r]=await t(e);return r==null?[n,r]:r instanceof Sr?[n,new Sr({message:`Cannot reach Core at ${r.url.host}:${r.url.port}`,url:r.url})]:[n,r]},Pu=[`arc`,`builtin`,`channel`,`cluster`,`device`,`framer`,`group`,`label`,`lineplot`,`log`,`node`,`policy`,`rack`,`range`,`range-alias`,`role`,`schematic`,`schematic_symbol`,`status`,`table`,`task`,`user`,`view`,`workspace`],Fu=l.z.enum(Pu),Iu=l.z.string().transform(e=>{let[t,n]=e.split(`:`);return{type:Fu.parse(t),key:n??``}}),R=l.z.object({type:Fu,key:l.z.string()}).or(Iu),Lu={type:`builtin`,key:`root`},z=e=>{let t=t=>({type:e,key:pi.isZero(t)?``:t.toString()});return(e=>Array.isArray(e)?e.map(t):t(e))},Ru=(e=>(typeof e==`string`&&(e=Iu.parse(e)),Array.isArray(e)?e.map(e=>Ru(e)):`${e.type}:${e.key}`)),zu=(e,t)=>e.type===t.type&&e.key===t.key,Bu=e=>{let t=w.toArray(e);return t.length===0?[]:typeof t[0]==`object`&&`id`in t[0]?t.map(({id:e})=>e):t.map(e=>R.parse(e))},Vu=l.z.object({id:R,name:l.z.string(),data:I.unknownZ().optional().nullable()}).transform(e=>({key:Ru(e.id),...e})),Hu=e=>e===`to`?`from`:`to`,Uu=l.z.object({from:R,type:l.z.string(),to:R}).or(l.z.string().transform(e=>{let[t,n,r]=e.split(`->`);return{from:R.parse(t),type:n,to:R.parse(r)}})),Wu=e=>`${Ru(e.from)}->${e.type}->${Ru(e.to)}`,Gu=`parent`,Ku=(e,t)=>!(t.type!=null&&t.type!==e.type||t.from?.type!=null&&t.from.type!==e.from.type||t.to?.type!=null&&t.to.type!==e.to.type||t.from?.key!=null&&t.from.key!==e.from.key||t.to?.key!=null&&t.to.key!==e.to.key),qu=l.z.object({id:R,children:R.array()}),Ju=l.z.object({from:R,to:R,children:R.array()}),Yu=l.z.object({}),Xu=class{client;constructor(e){this.client=e}async addChildren(e,...t){await S(this.client,`/ontology/add-children`,{id:e,children:t},qu,Yu)}async removeChildren(e,...t){await S(this.client,`/ontology/remove-children`,{id:e,children:t},qu,Yu)}async moveChildren(e,t,...n){await S(this.client,`/ontology/move-children`,{from:e,to:t,children:n},Ju,Yu)}},Zu=l.z.object({ids:R.array().optional(),children:l.z.boolean().optional(),parents:l.z.boolean().optional(),excludeFieldData:l.z.boolean().optional(),types:Fu.array().optional(),searchTerm:l.z.string().optional(),limit:l.z.int().optional(),offset:l.z.int().optional()}),Qu=l.z.object({resources:Vu.array()}),$u=class{type=`ontology`;client;writer;constructor(e){this.client=e,this.writer=new Xu(e)}async retrieve(e,t){if(!Array.isArray(e)&&typeof e==`object`&&!(`key`in e))return this.execRetrieve(e);let n=Bu(e),r=await this.execRetrieve({ids:n,...t});if(Array.isArray(e))return r;if(r.length===0)throw new Tu(`No resource found with ID ${mu.naturalLanguageJoin(n.map(e=>Ru(e)))}`);return r[0]}async retrieveChildren(e,t){return await this.execRetrieve({ids:w.toArray(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:w.toArray(e),parents:!0,...t})}async addChildren(e,...t){return await this.writer.addChildren(e,...t)}async removeChildren(e,...t){return await this.writer.removeChildren(e,...t)}async moveChildren(e,t,...n){return await this.writer.moveChildren(e,t,...n)}async execRetrieve(e){let{resources:t}=await S(this.client,`/ontology/retrieve`,e,Zu,Qu);return t}},ed=`sy_ontology_resource_set`,td=`sy_ontology_resource_delete`,nd=`sy_ontology_relationship_set`,rd=`sy_ontology_relationship_delete`,id=o({Client:()=>$u,PARENT_OF_RELATIONSHIP_TYPE:()=>Gu,RELATIONSHIP_DELETE_CHANNEL_NAME:()=>rd,RELATIONSHIP_SET_CHANNEL_NAME:()=>nd,RESOURCE_DELETE_CHANNEL_NAME:()=>td,RESOURCE_SET_CHANNEL_NAME:()=>ed,RESOURCE_TYPES:()=>Pu,ROOT_ID:()=>Lu,createIDFactory:()=>z,idToString:()=>Ru,idZ:()=>R,idsEqual:()=>zu,matchRelationship:()=>Ku,oppositeRelationshipDirection:()=>Hu,parseIDs:()=>Bu,relationshipToString:()=>Wu,relationshipZ:()=>Uu,resourceTypeZ:()=>Fu,resourceZ:()=>Vu}),ad=l.z.uuid(),od=l.z.object({key:ad,name:l.z.string(),objects:w.nullishToEmpty(R),actions:w.nullishToEmpty(d),internal:l.z.boolean().default(!1).optional()}),sd=od.partial({key:!0}),cd=z(`policy`),ld=cd(``),ud=`sy_policy_set`,dd=`sy_policy_delete`,fd=l.z.object({keys:ad.array().optional(),subjects:R.array().optional(),limit:l.z.number().optional(),offset:l.z.number().optional(),internal:l.z.boolean().optional()}),pd=l.z.object({key:ad}).transform(({key:e})=>({keys:[e]})),md=l.z.union([l.z.object({for:R}).transform(({for:e})=>({subjects:[e]})),l.z.object({for:R.array()}).transform(({for:e})=>({subjects:e})),fd]),hd=l.z.union([pd,md]),gd=l.z.object({policies:w.nullishToEmpty(od)}),_d=sd.transform(e=>({policies:[e]})),vd=sd.array().transform(e=>({policies:e})),yd=l.z.union([_d,vd]),bd=l.z.object({policies:od.array()}),xd=l.z.object({keys:ad.array()}),Sd=l.z.object({}),Cd=class{client;constructor(e){this.client=e}async create(e){let t=Array.isArray(e),n=await S(this.client,`/access/policy/create`,e,yd,bd);return t?n.policies:n.policies[0]}async retrieve(e){let t=`key`in e,n=await S(this.client,`/access/policy/retrieve`,e,hd,gd);return t?n.policies[0]:n.policies}async delete(e){await S(this.client,`/access/policy/delete`,{keys:w.toArray(e)},xd,Sd)}},wd=o({Client:()=>Cd,DELETE_CHANNEL_NAME:()=>dd,SET_CHANNEL_NAME:()=>ud,TYPE_ONTOLOGY_ID:()=>ld,createArgsZ:()=>yd,keyZ:()=>ad,multipleCreateArgsZ:()=>vd,newZ:()=>sd,ontologyID:()=>cd,policyZ:()=>od}),Td=l.z.uuid(),Ed=l.z.object({key:Td,name:l.z.string(),description:l.z.string().optional(),internal:l.z.boolean().optional()}),Dd=Ed.partial({key:!0}),Od=z(`role`),kd=Od(``),Ad=l.z.uuid(),jd=l.z.object({key:Ad,username:l.z.string().min(1,`Username is required`),firstName:l.z.string(),lastName:l.z.string(),rootUser:l.z.boolean().default(!1)}),Md=jd.omit({rootUser:!0}).partial({key:!0,firstName:!0,lastName:!0}).extend({password:l.z.string().min(1)});z(`user`)(``);var Nd=l.z.object({keys:Ad.array().optional(),usernames:l.z.string().array().optional()}),Pd=l.z.object({key:Ad}).transform(({key:e})=>({keys:[e]})),Fd=l.z.object({username:l.z.string()}).transform(({username:e})=>({usernames:[e]})),Id=l.z.object({usernames:l.z.string().array()}).transform(({usernames:e})=>({usernames:e})),Ld=l.z.union([Pd,Fd,Id,Nd]),Rd=l.z.object({users:w.nullishToEmpty(jd)}),zd=l.z.object({users:Md.array()}),Bd=l.z.object({users:jd.array()}),Vd=l.z.object({key:Ad,username:l.z.string().min(1)}),Hd=l.z.object({}),Ud=l.z.object({key:Ad,firstName:l.z.string().optional(),lastName:l.z.string().optional()}),Wd=l.z.object({}),Gd=l.z.object({keys:Ad.array()}),Kd=l.z.object({}),qd=`sy_user_set`,Jd=`sy_user_delete`,Yd=class{client;constructor(e){this.client=e}async create(e){let t=Array.isArray(e),n=await S(this.client,`/user/create`,{users:w.toArray(e)},zd,Bd);return t?n.users:n.users[0]}async changeUsername(e,t){await S(this.client,`/user/change-username`,{key:e,username:t},Vd,Hd)}async retrieve(e){let t=`key`in e||`username`in e,n=await S(this.client,`/user/retrieve`,e,Ld,Rd);if(!t)return n.users;if(n.users.length===0)throw new Eu(`No user with ${`key`in e?`key ${e.key}`:`username ${e.username}`} found`);if(n.users.length>1)throw new Du(`Multiple users found with ${`key`in e?`key ${e.key}`:`username ${e.username}`}`);return n.users[0]}async rename(e,t,n){await S(this.client,`/user/rename`,{key:e,firstName:t,lastName:n},Ud,Wd)}async delete(e){await S(this.client,`/user/delete`,{keys:w.toArray(e)},Gd,Kd)}},Xd=z(`user`),Zd=Xd(``),Qd=o({Client:()=>Yd,DELETE_CHANNEL_NAME:()=>Jd,SET_CHANNEL_NAME:()=>qd,TYPE_ONTOLOGY_ID:()=>Zd,keyZ:()=>Ad,newZ:()=>Md,ontologyID:()=>Xd,userZ:()=>jd}),$d=l.z.object({keys:Td.array().optional(),limit:l.z.number().optional(),offset:l.z.number().optional(),internal:l.z.boolean().optional()}),ef=l.z.object({key:Td}).transform(({key:e})=>({keys:[e]})),tf=Dd.transform(e=>({roles:[e]})),nf=Dd.array().transform(e=>({roles:e})),rf=l.z.union([tf,nf]),af=l.z.object({roles:Ed.array()}),of=l.z.object({roles:w.nullishToEmpty(Ed)}),sf=l.z.union([ef,$d]),cf=l.z.object({}),lf=Td.transform(e=>({keys:[e]})).or(Td.array().transform(e=>({keys:e}))),uf=l.z.object({user:Ad,role:Td}),df=l.z.object({}),ff=l.z.object({user:Ad,role:Td}),pf=l.z.object({}),mf=`sy_role_set`,hf=`sy_role_delete`,gf=class{client;constructor(e){this.client=e}async create(e){let t=Array.isArray(e),n=await S(this.client,`/access/role/create`,e,rf,af);return t?n.roles:n.roles[0]}async retrieve(e){let t=`key`in e,n=await S(this.client,`/access/role/retrieve`,e,sf,of);return t?n.roles[0]:n.roles}async delete(e){await S(this.client,`/access/role/delete`,e,lf,cf)}async assign(e){await S(this.client,`/access/role/assign`,e,uf,df)}async unassign(e){await S(this.client,`/access/role/unassign`,e,ff,pf)}},_f=o({Client:()=>gf,DELETE_CHANNEL_NAME:()=>hf,SET_CHANNEL_NAME:()=>mf,TYPE_ONTOLOGY_ID:()=>kd,createArgsZ:()=>rf,keyZ:()=>Td,multipleCreateArgsZ:()=>nf,newZ:()=>Dd,ontologyID:()=>Od,retrieveArgsZ:()=>sf,roleZ:()=>Ed}),vf=class{policies;roles;constructor(e){this.policies=new Cd(e),this.roles=new gf(e)}},yf=(e,t)=>{let n=w.toArray(e.objects),{action:r}=e;for(let e of n){let n=!1;for(let i of t)if(i.actions.includes(r)){for(let t of i.objects)if(t.key===``){if(t.type===e.type){n=!0;break}}else if(t.type===e.type&&t.key===e.key){n=!0;break}if(n)break}if(!n)return!1}return!0},bf=o({ACTIONS:()=>u,Client:()=>vf,actionZ:()=>d,allowRequest:()=>yf,policy:()=>wd,role:()=>_f});Object.freeze({status:`aborted`});function B(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,`_zod`,{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var xf=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Sf=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}},Cf={};function wf(e){return e&&Object.assign(Cf,e),Cf}function Tf(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Ef(e,t){return typeof t==`bigint`?t.toString():t}function Df(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function Of(e){return e==null}function kf(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Af(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=t.toString(),i=(r.split(`.`)[1]||``).length;if(i===0&&/\d?e-\d?/.test(r)){let e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let a=n>i?n:i;return Number.parseInt(e.toFixed(a).replace(`.`,``))%Number.parseInt(t.toFixed(a).replace(`.`,``))/10**a}var jf=Symbol(`evaluating`);function V(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==jf)return r===void 0&&(r=jf,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Mf(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Nf(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function Pf(e){return JSON.stringify(e)}function Ff(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var If=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Lf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Rf=Df(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function zf(e){if(Lf(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(Lf(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function Bf(e){return zf(e)?{...e}:Array.isArray(e)?[...e]:e}var Vf=new Set([`string`,`number`,`symbol`]);function Hf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Uf(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function H(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Wf(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var Gf={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Kf(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Uf(e,Nf(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Mf(this,`shape`,e),e},checks:[]}))}function qf(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Uf(e,Nf(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Mf(this,`shape`,r),r},checks:[]}))}function Jf(e,t){if(!zf(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Uf(e,Nf(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Mf(this,`shape`,n),n}}))}function Yf(e,t){if(!zf(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Uf(e,Nf(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Mf(this,`shape`,n),n}}))}function Xf(e,t){return Uf(e,Nf(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Mf(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function Zf(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Uf(t,Nf(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Mf(this,`shape`,i),i},checks:[]}))}function Qf(e,t,n){return Uf(t,Nf(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Mf(this,`shape`,i),i}}))}function $f(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function ep(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function tp(e){return typeof e==`string`?e:e?.message}function np(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=tp(e.inst?._zod.def?.error?.(e))??tp(t?.error?.(e))??tp(n.customError?.(e))??tp(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function rp(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function ip(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var ap=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,Ef,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},op=B(`$ZodError`,ap),sp=B(`$ZodError`,ap,{Parent:Error});function cp(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function lp(e,t=e=>e.message){let n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>r({issues:e}));else if(i.code===`invalid_key`)r({issues:i.issues});else if(i.code===`invalid_element`)r({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}var up=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new xf;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>np(e,a,wf())));throw If(t,i?.callee),t}return o.value},dp=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>np(e,a,wf())));throw If(t,i?.callee),t}return o.value},fp=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new xf;return a.issues.length?{success:!1,error:new(e??op)(a.issues.map(e=>np(e,i,wf())))}:{success:!0,data:a.value}},pp=fp(sp),mp=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>np(e,i,wf())))}:{success:!0,data:a.value}},hp=mp(sp),gp=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return up(e)(t,n,i)},_p=e=>(t,n,r)=>up(e)(t,n,r),vp=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return dp(e)(t,n,i)},yp=e=>async(t,n,r)=>dp(e)(t,n,r),bp=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return fp(e)(t,n,i)},xp=e=>(t,n,r)=>fp(e)(t,n,r),Sp=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return mp(e)(t,n,i)},Cp=e=>async(t,n,r)=>mp(e)(t,n,r),wp=/^[cC][^\s-]{8,}$/,Tp=/^[0-9a-z]+$/,Ep=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Dp=/^[0-9a-vA-V]{20}$/,Op=/^[A-Za-z0-9]{27}$/,kp=/^[a-zA-Z0-9_-]{21}$/,Ap=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jp=/^([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})$/,Mp=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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)$/,Np=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Pp=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function Fp(){return new RegExp(Pp,`u`)}var Ip=/^(?:(?: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])$/,Lp=/^(([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}|:))$/,Rp=/^((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])$/,zp=/^(([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])$/,Bp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Vp=/^[A-Za-z0-9_-]*$/,Hp=/^\+[1-9]\d{6,14}$/,Up=`(?:(?:\\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])))`,Wp=RegExp(`^${Up}$`);function Gp(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Kp(e){return RegExp(`^${Gp(e)}$`)}function qp(e){let t=Gp({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${Up}T(?:${r})$`)}var Jp=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Yp=/^-?\d+$/,Xp=/^-?\d+(?:\.\d+)?$/,Zp=/^(?:true|false)$/i,Qp=/^[^A-Z]*$/,$p=/^[^a-z]*$/,U=B(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),em={number:`number`,bigint:`bigint`,object:`date`},tm=B(`$ZodCheckLessThan`,(e,t)=>{U.init(e,t);let n=em[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),nm=B(`$ZodCheckGreaterThan`,(e,t)=>{U.init(e,t);let n=em[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rm=B(`$ZodCheckMultipleOf`,(e,t)=>{U.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Af(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),im=B(`$ZodCheckNumberFormat`,(e,t)=>{U.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Gf[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Yp)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),am=B(`$ZodCheckMaxLength`,(e,t)=>{var n;U.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Of(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=rp(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),om=B(`$ZodCheckMinLength`,(e,t)=>{var n;U.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Of(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=rp(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),sm=B(`$ZodCheckLengthEquals`,(e,t)=>{var n;U.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Of(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=rp(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),cm=B(`$ZodCheckStringFormat`,(e,t)=>{var n,r;U.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),lm=B(`$ZodCheckRegex`,(e,t)=>{cm.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),um=B(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Qp,cm.init(e,t)}),dm=B(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=$p,cm.init(e,t)}),fm=B(`$ZodCheckIncludes`,(e,t)=>{U.init(e,t);let n=Hf(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),pm=B(`$ZodCheckStartsWith`,(e,t)=>{U.init(e,t);let n=RegExp(`^${Hf(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),mm=B(`$ZodCheckEndsWith`,(e,t)=>{U.init(e,t);let n=RegExp(`.*${Hf(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),hm=B(`$ZodCheckOverwrite`,(e,t)=>{U.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),gm=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
38
+ `)}},jd=class extends Td.sub(`query`){},Md=class extends jd.sub(`not_found`){},Nd=class extends jd.sub(`multiple_results`){},Pd=class extends Td.sub(`route`){path;constructor(e,t){super(e),this.path=t}},Fd=class extends Td.sub(`control`){},Id=class extends Fd.sub(`unauthorized`){},Ld=class extends Td.sub(`disconnected`){constructor(e=`Operation failed because no Core is connected.`){super(e)}},Rd=class extends Td.sub(`contiguity`){};Gi.register({encode:()=>{throw new Gi.NotImplemented},decode:e=>e.type.startsWith(Td.TYPE)?e.type.startsWith(L.TYPE)?e.type===Ed.TYPE?Ed.decode(e):new L(e.data):e.type.startsWith(Dd.TYPE)?e.type.startsWith(Od.TYPE)?new Od(e.data):e.type.startsWith(kd.TYPE)?new kd(e.data):new Dd(e.data):e.type.startsWith(Ad.TYPE)?new Ad(e.data):e.type.startsWith(jd.TYPE)?e.type.startsWith(Md.TYPE)?new Md(e.data):e.type.startsWith(Nd.TYPE)?new Nd(e.data):new jd(e.data):e.type.startsWith(Fd.TYPE)?e.type.startsWith(Id.TYPE)?new Id(e.data):new Fd(e.data):e.type.startsWith(Pd.TYPE)?new Pd(e.data,e.data):new Ad(e.data):null});var zd=async(e,t)=>{let[n,r]=await t(e);return r==null?[n,r]:r instanceof Zr?[n,new Zr({message:`Cannot reach Core at ${r.url.host}:${r.url.port}`,url:r.url})]:[n,r]},Bd=[`arc`,`builtin`,`channel`,`cluster`,`device`,`framer`,`group`,`label`,`lineplot`,`log`,`node`,`policy`,`rack`,`range`,`range-alias`,`role`,`schematic`,`schematic_symbol`,`status`,`table`,`task`,`user`,`view`,`workspace`],Vd=l.z.enum(Bd),Hd=l.z.string().transform(e=>{let[t,n]=e.split(`:`);return{type:Vd.parse(t),key:n??``}}),R=l.z.object({type:Vd,key:l.z.string()}).or(Hd),Ud={type:`builtin`,key:`root`},z=e=>{let t=t=>({type:e,key:fa.isZero(t)?``:t.toString()});return(e=>Array.isArray(e)?e.map(t):t(e))},Wd=(e=>(typeof e==`string`&&(e=Hd.parse(e)),Array.isArray(e)?e.map(e=>Wd(e)):`${e.type}:${e.key}`)),Gd=(e,t)=>e.type===t.type&&e.key===t.key,Kd=e=>{let t=w.toArray(e);return t.length===0?[]:typeof t[0]==`object`&&`id`in t[0]?t.map(({id:e})=>e):t.map(e=>R.parse(e))},qd=l.z.object({id:R,name:l.z.string(),data:I.unknownZ().optional().nullable()}).transform(e=>({key:Wd(e.id),...e})),Jd=e=>e===`to`?`from`:`to`,Yd=l.z.object({from:R,type:l.z.string(),to:R}).or(l.z.string().transform(e=>{let[t,n,r]=e.split(`->`);return{from:R.parse(t),type:n,to:R.parse(r)}})),Xd=e=>`${Wd(e.from)}->${e.type}->${Wd(e.to)}`,Zd=`parent`,Qd=(e,t)=>!(t.type!=null&&t.type!==e.type||t.from?.type!=null&&t.from.type!==e.from.type||t.to?.type!=null&&t.to.type!==e.to.type||t.from?.key!=null&&t.from.key!==e.from.key||t.to?.key!=null&&t.to.key!==e.to.key),$d=l.z.object({id:R,children:R.array()}),ef=l.z.object({from:R,to:R,children:R.array()}),tf=l.z.object({}),nf=class{client;constructor(e){this.client=e}async addChildren(e,...t){await S(this.client,`/ontology/add-children`,{id:e,children:t},$d,tf)}async removeChildren(e,...t){await S(this.client,`/ontology/remove-children`,{id:e,children:t},$d,tf)}async moveChildren(e,t,...n){await S(this.client,`/ontology/move-children`,{from:e,to:t,children:n},ef,tf)}},rf=l.z.object({ids:R.array().optional(),children:l.z.boolean().optional(),parents:l.z.boolean().optional(),excludeFieldData:l.z.boolean().optional(),types:Vd.array().optional(),searchTerm:l.z.string().optional(),limit:l.z.int().optional(),offset:l.z.int().optional()}),af=l.z.object({resources:qd.array()}),of=class{type=`ontology`;client;writer;constructor(e){this.client=e,this.writer=new nf(e)}async retrieve(e,t){if(!Array.isArray(e)&&typeof e==`object`&&!(`key`in e))return this.execRetrieve(e);let n=Kd(e),r=await this.execRetrieve({ids:n,...t});if(Array.isArray(e))return r;if(r.length===0)throw new jd(`No resource found with ID ${bd.naturalLanguageJoin(n.map(e=>Wd(e)))}`);return r[0]}async retrieveChildren(e,t){return await this.execRetrieve({ids:w.toArray(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:w.toArray(e),parents:!0,...t})}async addChildren(e,...t){return await this.writer.addChildren(e,...t)}async removeChildren(e,...t){return await this.writer.removeChildren(e,...t)}async moveChildren(e,t,...n){return await this.writer.moveChildren(e,t,...n)}async execRetrieve(e){let{resources:t}=await S(this.client,`/ontology/retrieve`,e,rf,af);return t}},sf=`sy_ontology_resource_set`,cf=`sy_ontology_resource_delete`,lf=`sy_ontology_relationship_set`,uf=`sy_ontology_relationship_delete`,df=o({Client:()=>of,PARENT_OF_RELATIONSHIP_TYPE:()=>Zd,RELATIONSHIP_DELETE_CHANNEL_NAME:()=>uf,RELATIONSHIP_SET_CHANNEL_NAME:()=>lf,RESOURCE_DELETE_CHANNEL_NAME:()=>cf,RESOURCE_SET_CHANNEL_NAME:()=>sf,RESOURCE_TYPES:()=>Bd,ROOT_ID:()=>Ud,createIDFactory:()=>z,idToString:()=>Wd,idZ:()=>R,idsEqual:()=>Gd,matchRelationship:()=>Qd,oppositeRelationshipDirection:()=>Jd,parseIDs:()=>Kd,relationshipToString:()=>Xd,relationshipZ:()=>Yd,resourceTypeZ:()=>Vd,resourceZ:()=>qd}),ff=l.z.uuid(),pf=l.z.object({key:ff,name:l.z.string(),objects:w.nullishToEmpty(R),actions:w.nullishToEmpty(d),internal:l.z.boolean().default(!1).optional()}),mf=pf.partial({key:!0}),hf=z(`policy`),gf=hf(``),_f=`sy_policy_set`,vf=`sy_policy_delete`,yf=l.z.object({keys:ff.array().optional(),subjects:R.array().optional(),limit:l.z.number().optional(),offset:l.z.number().optional(),internal:l.z.boolean().optional()}),bf=l.z.object({key:ff}).transform(({key:e})=>({keys:[e]})),xf=l.z.union([l.z.object({for:R}).transform(({for:e})=>({subjects:[e]})),l.z.object({for:R.array()}).transform(({for:e})=>({subjects:e})),yf]),Sf=l.z.union([bf,xf]),Cf=l.z.object({policies:w.nullishToEmpty(pf)}),wf=mf.transform(e=>({policies:[e]})),Tf=mf.array().transform(e=>({policies:e})),Ef=l.z.union([wf,Tf]),Df=l.z.object({policies:pf.array()}),Of=l.z.object({keys:ff.array()}),kf=l.z.object({}),Af=class{client;constructor(e){this.client=e}async create(e){let t=Array.isArray(e),n=await S(this.client,`/access/policy/create`,e,Ef,Df);return t?n.policies:n.policies[0]}async retrieve(e){let t=`key`in e,n=await S(this.client,`/access/policy/retrieve`,e,Sf,Cf);return t?n.policies[0]:n.policies}async delete(e){await S(this.client,`/access/policy/delete`,{keys:w.toArray(e)},Of,kf)}},jf=o({Client:()=>Af,DELETE_CHANNEL_NAME:()=>vf,SET_CHANNEL_NAME:()=>_f,TYPE_ONTOLOGY_ID:()=>gf,createArgsZ:()=>Ef,keyZ:()=>ff,multipleCreateArgsZ:()=>Tf,newZ:()=>mf,ontologyID:()=>hf,policyZ:()=>pf}),Mf=l.z.uuid(),Nf=l.z.object({key:Mf,name:l.z.string(),description:l.z.string().optional(),internal:l.z.boolean().optional()}),Pf=Nf.partial({key:!0}),Ff=z(`role`),If=Ff(``),Lf=l.z.uuid(),Rf=l.z.object({key:Lf,username:l.z.string().min(1,`Username is required`),firstName:l.z.string(),lastName:l.z.string(),rootUser:l.z.boolean().default(!1)}),zf=Rf.omit({rootUser:!0}).partial({key:!0,firstName:!0,lastName:!0}).extend({password:l.z.string().min(1)});z(`user`)(``);var Bf=l.z.object({keys:Lf.array().optional(),usernames:l.z.string().array().optional()}),Vf=l.z.object({key:Lf}).transform(({key:e})=>({keys:[e]})),Hf=l.z.object({username:l.z.string()}).transform(({username:e})=>({usernames:[e]})),Uf=l.z.object({usernames:l.z.string().array()}).transform(({usernames:e})=>({usernames:e})),Wf=l.z.union([Vf,Hf,Uf,Bf]),Gf=l.z.object({users:w.nullishToEmpty(Rf)}),Kf=l.z.object({users:zf.array()}),qf=l.z.object({users:Rf.array()}),Jf=l.z.object({key:Lf,username:l.z.string().min(1)}),Yf=l.z.object({}),Xf=l.z.object({key:Lf,firstName:l.z.string().optional(),lastName:l.z.string().optional()}),Zf=l.z.object({}),Qf=l.z.object({keys:Lf.array()}),$f=l.z.object({}),ep=`sy_user_set`,tp=`sy_user_delete`,np=class{client;constructor(e){this.client=e}async create(e){let t=Array.isArray(e),n=await S(this.client,`/user/create`,{users:w.toArray(e)},Kf,qf);return t?n.users:n.users[0]}async changeUsername(e,t){await S(this.client,`/user/change-username`,{key:e,username:t},Jf,Yf)}async retrieve(e){let t=`key`in e||`username`in e,n=await S(this.client,`/user/retrieve`,e,Wf,Gf);if(!t)return n.users;if(n.users.length===0)throw new Md(`No user with ${`key`in e?`key ${e.key}`:`username ${e.username}`} found`);if(n.users.length>1)throw new Nd(`Multiple users found with ${`key`in e?`key ${e.key}`:`username ${e.username}`}`);return n.users[0]}async rename(e,t,n){await S(this.client,`/user/rename`,{key:e,firstName:t,lastName:n},Xf,Zf)}async delete(e){await S(this.client,`/user/delete`,{keys:w.toArray(e)},Qf,$f)}},rp=z(`user`),ip=rp(``),ap=o({Client:()=>np,DELETE_CHANNEL_NAME:()=>tp,SET_CHANNEL_NAME:()=>ep,TYPE_ONTOLOGY_ID:()=>ip,keyZ:()=>Lf,newZ:()=>zf,ontologyID:()=>rp,userZ:()=>Rf}),op=l.z.object({keys:Mf.array().optional(),limit:l.z.number().optional(),offset:l.z.number().optional(),internal:l.z.boolean().optional()}),sp=l.z.object({key:Mf}).transform(({key:e})=>({keys:[e]})),cp=Pf.transform(e=>({roles:[e]})),lp=Pf.array().transform(e=>({roles:e})),up=l.z.union([cp,lp]),dp=l.z.object({roles:Nf.array()}),fp=l.z.object({roles:w.nullishToEmpty(Nf)}),pp=l.z.union([sp,op]),mp=l.z.object({}),hp=Mf.transform(e=>({keys:[e]})).or(Mf.array().transform(e=>({keys:e}))),gp=l.z.object({user:Lf,role:Mf}),_p=l.z.object({}),vp=l.z.object({user:Lf,role:Mf}),yp=l.z.object({}),bp=`sy_role_set`,xp=`sy_role_delete`,Sp=class{client;constructor(e){this.client=e}async create(e){let t=Array.isArray(e),n=await S(this.client,`/access/role/create`,e,up,dp);return t?n.roles:n.roles[0]}async retrieve(e){let t=`key`in e,n=await S(this.client,`/access/role/retrieve`,e,pp,fp);return t?n.roles[0]:n.roles}async delete(e){await S(this.client,`/access/role/delete`,e,hp,mp)}async assign(e){await S(this.client,`/access/role/assign`,e,gp,_p)}async unassign(e){await S(this.client,`/access/role/unassign`,e,vp,yp)}},Cp=o({Client:()=>Sp,DELETE_CHANNEL_NAME:()=>xp,SET_CHANNEL_NAME:()=>bp,TYPE_ONTOLOGY_ID:()=>If,createArgsZ:()=>up,keyZ:()=>Mf,multipleCreateArgsZ:()=>lp,newZ:()=>Pf,ontologyID:()=>Ff,retrieveArgsZ:()=>pp,roleZ:()=>Nf}),wp=class{policies;roles;constructor(e){this.policies=new Af(e),this.roles=new Sp(e)}},Tp=(e,t)=>{let n=w.toArray(e.objects),{action:r}=e;for(let e of n){let n=!1;for(let i of t)if(i.actions.includes(r)){for(let t of i.objects)if(t.key===``){if(t.type===e.type){n=!0;break}}else if(t.type===e.type&&t.key===e.key){n=!0;break}if(n)break}if(!n)return!1}return!0},Ep=o({ACTIONS:()=>u,Client:()=>wp,actionZ:()=>d,allowRequest:()=>Tp,policy:()=>jf,role:()=>Cp});Object.freeze({status:`aborted`});function B(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,`_zod`,{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var Dp=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Op=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}},kp={};function Ap(e){return e&&Object.assign(kp,e),kp}function jp(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Mp(e,t){return typeof t==`bigint`?t.toString():t}function Np(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function Pp(e){return e==null}function Fp(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ip(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=t.toString(),i=(r.split(`.`)[1]||``).length;if(i===0&&/\d?e-\d?/.test(r)){let e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let a=n>i?n:i;return Number.parseInt(e.toFixed(a).replace(`.`,``))%Number.parseInt(t.toFixed(a).replace(`.`,``))/10**a}var Lp=Symbol(`evaluating`);function V(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Lp)return r===void 0&&(r=Lp,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Rp(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function zp(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function Bp(e){return JSON.stringify(e)}function Vp(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var Hp=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Up(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Wp=Np(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Gp(e){if(Up(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(Up(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function Kp(e){return Gp(e)?{...e}:Array.isArray(e)?[...e]:e}var qp=new Set([`string`,`number`,`symbol`]);function Jp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Yp(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function H(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Xp(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var Zp={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Qp(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Yp(e,zp(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Rp(this,`shape`,e),e},checks:[]}))}function $p(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Yp(e,zp(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Rp(this,`shape`,r),r},checks:[]}))}function em(e,t){if(!Gp(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Yp(e,zp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Rp(this,`shape`,n),n}}))}function tm(e,t){if(!Gp(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Yp(e,zp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Rp(this,`shape`,n),n}}))}function nm(e,t){return Yp(e,zp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Rp(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function rm(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Yp(t,zp(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Rp(this,`shape`,i),i},checks:[]}))}function im(e,t,n){return Yp(t,zp(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Rp(this,`shape`,i),i}}))}function am(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function om(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function sm(e){return typeof e==`string`?e:e?.message}function cm(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=sm(e.inst?._zod.def?.error?.(e))??sm(t?.error?.(e))??sm(n.customError?.(e))??sm(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function lm(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function um(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var dm=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,Mp,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},fm=B(`$ZodError`,dm),pm=B(`$ZodError`,dm,{Parent:Error});function mm(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function hm(e,t=e=>e.message){let n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>r({issues:e}));else if(i.code===`invalid_key`)r({issues:i.issues});else if(i.code===`invalid_element`)r({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}var gm=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Dp;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>cm(e,a,Ap())));throw Hp(t,i?.callee),t}return o.value},_m=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>cm(e,a,Ap())));throw Hp(t,i?.callee),t}return o.value},vm=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Dp;return a.issues.length?{success:!1,error:new(e??fm)(a.issues.map(e=>cm(e,i,Ap())))}:{success:!0,data:a.value}},ym=vm(pm),bm=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>cm(e,i,Ap())))}:{success:!0,data:a.value}},xm=bm(pm),Sm=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return gm(e)(t,n,i)},Cm=e=>(t,n,r)=>gm(e)(t,n,r),wm=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return _m(e)(t,n,i)},Tm=e=>async(t,n,r)=>_m(e)(t,n,r),Em=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return vm(e)(t,n,i)},Dm=e=>(t,n,r)=>vm(e)(t,n,r),Om=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return bm(e)(t,n,i)},km=e=>async(t,n,r)=>bm(e)(t,n,r),Am=/^[cC][^\s-]{8,}$/,jm=/^[0-9a-z]+$/,Mm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Nm=/^[0-9a-vA-V]{20}$/,Pm=/^[A-Za-z0-9]{27}$/,Fm=/^[a-zA-Z0-9_-]{21}$/,Im=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Lm=/^([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})$/,Rm=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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)$/,zm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Bm=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function Vm(){return new RegExp(Bm,`u`)}var Hm=/^(?:(?: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])$/,Um=/^(([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}|:))$/,Wm=/^((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])$/,Gm=/^(([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])$/,Km=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,qm=/^[A-Za-z0-9_-]*$/,Jm=/^\+[1-9]\d{6,14}$/,Ym=`(?:(?:\\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])))`,Xm=RegExp(`^${Ym}$`);function Zm(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Qm(e){return RegExp(`^${Zm(e)}$`)}function $m(e){let t=Zm({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${Ym}T(?:${r})$`)}var eh=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},th=/^-?\d+$/,nh=/^-?\d+(?:\.\d+)?$/,rh=/^(?:true|false)$/i,ih=/^[^A-Z]*$/,ah=/^[^a-z]*$/,U=B(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),oh={number:`number`,bigint:`bigint`,object:`date`},sh=B(`$ZodCheckLessThan`,(e,t)=>{U.init(e,t);let n=oh[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ch=B(`$ZodCheckGreaterThan`,(e,t)=>{U.init(e,t);let n=oh[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),lh=B(`$ZodCheckMultipleOf`,(e,t)=>{U.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Ip(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),uh=B(`$ZodCheckNumberFormat`,(e,t)=>{U.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Zp[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=th)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),dh=B(`$ZodCheckMaxLength`,(e,t)=>{var n;U.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Pp(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=lm(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),fh=B(`$ZodCheckMinLength`,(e,t)=>{var n;U.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Pp(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=lm(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ph=B(`$ZodCheckLengthEquals`,(e,t)=>{var n;U.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Pp(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=lm(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),mh=B(`$ZodCheckStringFormat`,(e,t)=>{var n,r;U.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),hh=B(`$ZodCheckRegex`,(e,t)=>{mh.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),gh=B(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=ih,mh.init(e,t)}),_h=B(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=ah,mh.init(e,t)}),vh=B(`$ZodCheckIncludes`,(e,t)=>{U.init(e,t);let n=Jp(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),yh=B(`$ZodCheckStartsWith`,(e,t)=>{U.init(e,t);let n=RegExp(`^${Jp(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),bh=B(`$ZodCheckEndsWith`,(e,t)=>{U.init(e,t);let n=RegExp(`.*${Jp(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),xh=B(`$ZodCheckOverwrite`,(e,t)=>{U.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Sh=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
22
39
  `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
23
- `))}},_m={major:4,minor:3,patch:6},W=B(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=_m;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=$f(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new xf;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=$f(e,t))});else{if(e.issues.length===t)continue;r||=$f(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if($f(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new xf;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new xf;return o.then(e=>t(e,r,a))}return t(o,r,a)}}V(e,`~standard`,()=>({validate:t=>{try{let n=pp(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return hp(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),vm=B(`$ZodString`,(e,t)=>{W.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Jp(e._zod.bag),e._zod.parse=(n,r)=>{if(t.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:e}),n}}),G=B(`$ZodStringFormat`,(e,t)=>{cm.init(e,t),vm.init(e,t)}),ym=B(`$ZodGUID`,(e,t)=>{t.pattern??=jp,G.init(e,t)}),bm=B(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Mp(e)}else t.pattern??=Mp();G.init(e,t)}),xm=B(`$ZodEmail`,(e,t)=>{t.pattern??=Np,G.init(e,t)}),Sm=B(`$ZodURL`,(e,t)=>{G.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Cm=B(`$ZodEmoji`,(e,t)=>{t.pattern??=Fp(),G.init(e,t)}),wm=B(`$ZodNanoID`,(e,t)=>{t.pattern??=kp,G.init(e,t)}),Tm=B(`$ZodCUID`,(e,t)=>{t.pattern??=wp,G.init(e,t)}),Em=B(`$ZodCUID2`,(e,t)=>{t.pattern??=Tp,G.init(e,t)}),Dm=B(`$ZodULID`,(e,t)=>{t.pattern??=Ep,G.init(e,t)}),Om=B(`$ZodXID`,(e,t)=>{t.pattern??=Dp,G.init(e,t)}),km=B(`$ZodKSUID`,(e,t)=>{t.pattern??=Op,G.init(e,t)}),Am=B(`$ZodISODateTime`,(e,t)=>{t.pattern??=qp(t),G.init(e,t)}),jm=B(`$ZodISODate`,(e,t)=>{t.pattern??=Wp,G.init(e,t)}),Mm=B(`$ZodISOTime`,(e,t)=>{t.pattern??=Kp(t),G.init(e,t)}),Nm=B(`$ZodISODuration`,(e,t)=>{t.pattern??=Ap,G.init(e,t)}),Pm=B(`$ZodIPv4`,(e,t)=>{t.pattern??=Ip,G.init(e,t),e._zod.bag.format=`ipv4`}),Fm=B(`$ZodIPv6`,(e,t)=>{t.pattern??=Lp,G.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Im=B(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Rp,G.init(e,t)}),Lm=B(`$ZodCIDRv6`,(e,t)=>{t.pattern??=zp,G.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function Rm(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var zm=B(`$ZodBase64`,(e,t)=>{t.pattern??=Bp,G.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Rm(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Bm(e){if(!Vp.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Rm(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Vm=B(`$ZodBase64URL`,(e,t)=>{t.pattern??=Vp,G.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Bm(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Hm=B(`$ZodE164`,(e,t)=>{t.pattern??=Hp,G.init(e,t)});function Um(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var Wm=B(`$ZodJWT`,(e,t)=>{G.init(e,t),e._zod.check=n=>{Um(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Gm=B(`$ZodNumber`,(e,t)=>{W.init(e,t),e._zod.pattern=e._zod.bag.pattern??Xp,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Km=B(`$ZodNumberFormat`,(e,t)=>{im.init(e,t),Gm.init(e,t)}),qm=B(`$ZodBoolean`,(e,t)=>{W.init(e,t),e._zod.pattern=Zp,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Jm=B(`$ZodUnknown`,(e,t)=>{W.init(e,t),e._zod.parse=e=>e}),Ym=B(`$ZodNever`,(e,t)=>{W.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Xm(e,t,n){e.issues.length&&t.issues.push(...ep(n,e.issues)),t.value[n]=e.value}var Zm=B(`$ZodArray`,(e,t)=>{W.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>Xm(t,n,e))):Xm(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Qm(e,t,n,r,i){if(e.issues.length){if(i&&!(n in r))return;t.issues.push(...ep(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function $m(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Wf(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function eh(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optout===`optional`;for(let i in t){if(s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Qm(e,n,i,t,u))):Qm(a,n,i,t,u)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var th=B(`$ZodObject`,(e,t)=>{if(W.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,`shape`,{get:()=>{let n={...e};return Object.defineProperty(t,`shape`,{value:n}),n}})}let n=Df(()=>$m(t));V(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Lf,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optout===`optional`,i=n._zod.run({value:s[e],issues:[]},o);i instanceof Promise?c.push(i.then(n=>Qm(n,t,e,s,r))):Qm(i,t,e,s,r)}return i?eh(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),nh=B(`$ZodObjectJIT`,(e,t)=>{th.init(e,t);let n=e._zod.parse,r=Df(()=>$m(t)),i=e=>{let t=new gm([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Pf(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=Pf(r),s=e[r]?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),s?t.write(`
40
+ `))}},Ch={major:4,minor:3,patch:6},W=B(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ch;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=am(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Dp;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=am(e,t))});else{if(e.issues.length===t)continue;r||=am(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(am(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Dp;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new Dp;return o.then(e=>t(e,r,a))}return t(o,r,a)}}V(e,`~standard`,()=>({validate:t=>{try{let n=ym(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return xm(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),wh=B(`$ZodString`,(e,t)=>{W.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??eh(e._zod.bag),e._zod.parse=(n,r)=>{if(t.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:e}),n}}),G=B(`$ZodStringFormat`,(e,t)=>{mh.init(e,t),wh.init(e,t)}),Th=B(`$ZodGUID`,(e,t)=>{t.pattern??=Lm,G.init(e,t)}),Eh=B(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Rm(e)}else t.pattern??=Rm();G.init(e,t)}),Dh=B(`$ZodEmail`,(e,t)=>{t.pattern??=zm,G.init(e,t)}),Oh=B(`$ZodURL`,(e,t)=>{G.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),kh=B(`$ZodEmoji`,(e,t)=>{t.pattern??=Vm(),G.init(e,t)}),Ah=B(`$ZodNanoID`,(e,t)=>{t.pattern??=Fm,G.init(e,t)}),jh=B(`$ZodCUID`,(e,t)=>{t.pattern??=Am,G.init(e,t)}),Mh=B(`$ZodCUID2`,(e,t)=>{t.pattern??=jm,G.init(e,t)}),Nh=B(`$ZodULID`,(e,t)=>{t.pattern??=Mm,G.init(e,t)}),Ph=B(`$ZodXID`,(e,t)=>{t.pattern??=Nm,G.init(e,t)}),Fh=B(`$ZodKSUID`,(e,t)=>{t.pattern??=Pm,G.init(e,t)}),Ih=B(`$ZodISODateTime`,(e,t)=>{t.pattern??=$m(t),G.init(e,t)}),Lh=B(`$ZodISODate`,(e,t)=>{t.pattern??=Xm,G.init(e,t)}),Rh=B(`$ZodISOTime`,(e,t)=>{t.pattern??=Qm(t),G.init(e,t)}),zh=B(`$ZodISODuration`,(e,t)=>{t.pattern??=Im,G.init(e,t)}),Bh=B(`$ZodIPv4`,(e,t)=>{t.pattern??=Hm,G.init(e,t),e._zod.bag.format=`ipv4`}),Vh=B(`$ZodIPv6`,(e,t)=>{t.pattern??=Um,G.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Hh=B(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Wm,G.init(e,t)}),Uh=B(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Gm,G.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function Wh(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Gh=B(`$ZodBase64`,(e,t)=>{t.pattern??=Km,G.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Wh(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Kh(e){if(!qm.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Wh(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var qh=B(`$ZodBase64URL`,(e,t)=>{t.pattern??=qm,G.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Kh(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Jh=B(`$ZodE164`,(e,t)=>{t.pattern??=Jm,G.init(e,t)});function Yh(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var Xh=B(`$ZodJWT`,(e,t)=>{G.init(e,t),e._zod.check=n=>{Yh(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Zh=B(`$ZodNumber`,(e,t)=>{W.init(e,t),e._zod.pattern=e._zod.bag.pattern??nh,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Qh=B(`$ZodNumberFormat`,(e,t)=>{uh.init(e,t),Zh.init(e,t)}),$h=B(`$ZodBoolean`,(e,t)=>{W.init(e,t),e._zod.pattern=rh,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),eg=B(`$ZodUnknown`,(e,t)=>{W.init(e,t),e._zod.parse=e=>e}),tg=B(`$ZodNever`,(e,t)=>{W.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function ng(e,t,n){e.issues.length&&t.issues.push(...om(n,e.issues)),t.value[n]=e.value}var rg=B(`$ZodArray`,(e,t)=>{W.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>ng(t,n,e))):ng(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function ig(e,t,n,r,i){if(e.issues.length){if(i&&!(n in r))return;t.issues.push(...om(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function ag(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Xp(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function og(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optout===`optional`;for(let i in t){if(s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>ig(e,n,i,t,u))):ig(a,n,i,t,u)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var sg=B(`$ZodObject`,(e,t)=>{if(W.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,`shape`,{get:()=>{let n={...e};return Object.defineProperty(t,`shape`,{value:n}),n}})}let n=Np(()=>ag(t));V(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Up,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optout===`optional`,i=n._zod.run({value:s[e],issues:[]},o);i instanceof Promise?c.push(i.then(n=>ig(n,t,e,s,r))):ig(i,t,e,s,r)}return i?og(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),cg=B(`$ZodObjectJIT`,(e,t)=>{sg.init(e,t);let n=e._zod.parse,r=Np(()=>ag(t)),i=e=>{let t=new Sh([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Bp(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=Bp(r),s=e[r]?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),s?t.write(`
24
41
  if (${n}.issues.length) {
25
42
  if (${o} in input) {
26
43
  payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
@@ -54,30 +71,30 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
54
71
  newResult[${o}] = ${n}.value;
55
72
  }
56
73
 
57
- `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Lf,s=!Cf.jitless,c=s&&Rf.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?eh([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function rh(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!$f(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>np(e,r,wf())))}),t)}var ih=B(`$ZodUnion`,(e,t)=>{W.init(e,t),V(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),V(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),V(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),V(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>kf(e.source)).join(`|`)})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,a)=>{if(n)return r(i,a);let o=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},a);if(t instanceof Promise)s.push(t),o=!0;else{if(t.issues.length===0)return t;s.push(t)}}return o?Promise.all(s).then(t=>rh(t,i,e,a)):rh(s,i,e,a)}}),ah=B(`$ZodIntersection`,(e,t)=>{W.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>sh(e,t,n)):sh(e,i,a)}});function oh(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(zf(e)&&zf(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=oh(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=oh(i,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 sh(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),$f(e))return e;let o=oh(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var ch=B(`$ZodEnum`,(e,t)=>{W.init(e,t);let n=Tf(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Vf.has(typeof e)).map(e=>typeof e==`string`?Hf(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),lh=B(`$ZodTransform`,(e,t)=>{W.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Sf(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new xf;return n.value=i,n}});function uh(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var dh=B(`$ZodOptional`,(e,t)=>{W.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,V(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),V(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${kf(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>uh(t,e.value)):uh(r,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),fh=B(`$ZodExactOptional`,(e,t)=>{dh.init(e,t),V(e._zod,`values`,()=>t.innerType._zod.values),V(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),ph=B(`$ZodNullable`,(e,t)=>{W.init(e,t),V(e._zod,`optin`,()=>t.innerType._zod.optin),V(e._zod,`optout`,()=>t.innerType._zod.optout),V(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${kf(e.source)}|null)$`):void 0}),V(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),mh=B(`$ZodDefault`,(e,t)=>{W.init(e,t),e._zod.optin=`optional`,V(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>hh(e,t)):hh(r,t)}});function hh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var gh=B(`$ZodPrefault`,(e,t)=>{W.init(e,t),e._zod.optin=`optional`,V(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),_h=B(`$ZodNonOptional`,(e,t)=>{W.init(e,t),V(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>vh(t,e)):vh(i,e)}});function vh(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var yh=B(`$ZodCatch`,(e,t)=>{W.init(e,t),V(e._zod,`optin`,()=>t.innerType._zod.optin),V(e._zod,`optout`,()=>t.innerType._zod.optout),V(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>np(e,n,wf()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>np(e,n,wf()))},input:e.value}),e.issues=[]),e)}}),bh=B(`$ZodPipe`,(e,t)=>{W.init(e,t),V(e._zod,`values`,()=>t.in._zod.values),V(e._zod,`optin`,()=>t.in._zod.optin),V(e._zod,`optout`,()=>t.out._zod.optout),V(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>xh(e,t.in,n)):xh(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>xh(e,t.out,n)):xh(r,t.out,n)}});function xh(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var Sh=B(`$ZodReadonly`,(e,t)=>{W.init(e,t),V(e._zod,`propValues`,()=>t.innerType._zod.propValues),V(e._zod,`values`,()=>t.innerType._zod.values),V(e._zod,`optin`,()=>t.innerType?._zod?.optin),V(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Ch):Ch(r)}});function Ch(e){return e.value=Object.freeze(e.value),e}var wh=B(`$ZodCustom`,(e,t)=>{U.init(e,t),W.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Th(t,n,r,e));Th(i,n,r,e)}});function Th(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(ip(e))}}var Eh,Dh=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Oh(){return new Dh}(Eh=globalThis).__zod_globalRegistry??(Eh.__zod_globalRegistry=Oh());var kh=globalThis.__zod_globalRegistry;function Ah(e,t){return new e({type:`string`,...H(t)})}function jh(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...H(t)})}function Mh(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...H(t)})}function Nh(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...H(t)})}function Ph(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...H(t)})}function Fh(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...H(t)})}function Ih(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...H(t)})}function Lh(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...H(t)})}function Rh(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...H(t)})}function zh(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...H(t)})}function Bh(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...H(t)})}function Vh(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...H(t)})}function Hh(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...H(t)})}function Uh(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...H(t)})}function Wh(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...H(t)})}function Gh(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...H(t)})}function Kh(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...H(t)})}function qh(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...H(t)})}function Jh(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...H(t)})}function Yh(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...H(t)})}function Xh(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...H(t)})}function Zh(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...H(t)})}function Qh(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...H(t)})}function $h(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...H(t)})}function eg(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...H(t)})}function tg(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...H(t)})}function ng(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...H(t)})}function rg(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...H(t)})}function ig(e,t){return new e({type:`boolean`,...H(t)})}function ag(e){return new e({type:`unknown`})}function og(e,t){return new e({type:`never`,...H(t)})}function sg(e,t){return new tm({check:`less_than`,...H(t),value:e,inclusive:!1})}function cg(e,t){return new tm({check:`less_than`,...H(t),value:e,inclusive:!0})}function lg(e,t){return new nm({check:`greater_than`,...H(t),value:e,inclusive:!1})}function ug(e,t){return new nm({check:`greater_than`,...H(t),value:e,inclusive:!0})}function dg(e,t){return new rm({check:`multiple_of`,...H(t),value:e})}function fg(e,t){return new am({check:`max_length`,...H(t),maximum:e})}function pg(e,t){return new om({check:`min_length`,...H(t),minimum:e})}function mg(e,t){return new sm({check:`length_equals`,...H(t),length:e})}function hg(e,t){return new lm({check:`string_format`,format:`regex`,...H(t),pattern:e})}function gg(e){return new um({check:`string_format`,format:`lowercase`,...H(e)})}function _g(e){return new dm({check:`string_format`,format:`uppercase`,...H(e)})}function vg(e,t){return new fm({check:`string_format`,format:`includes`,...H(t),includes:e})}function yg(e,t){return new pm({check:`string_format`,format:`starts_with`,...H(t),prefix:e})}function bg(e,t){return new mm({check:`string_format`,format:`ends_with`,...H(t),suffix:e})}function xg(e){return new hm({check:`overwrite`,tx:e})}function Sg(e){return xg(t=>t.normalize(e))}function Cg(){return xg(e=>e.trim())}function wg(){return xg(e=>e.toLowerCase())}function Tg(){return xg(e=>e.toUpperCase())}function Eg(){return xg(e=>Ff(e))}function Dg(e,t,n){return new e({type:`array`,element:t,...H(n)})}function Og(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...H(n)})}function kg(e){let t=Ag(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(ip(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(ip(r))}},e(n.value,n)));return t}function Ag(e,t){let n=new U({check:`custom`,...H(t)});return n._zod.check=e,n}function jg(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??kh,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function K(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,K(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&q(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Mg(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
74
+ `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Up,s=!kp.jitless,c=s&&Wp.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?og([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function lg(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!am(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>cm(e,r,Ap())))}),t)}var ug=B(`$ZodUnion`,(e,t)=>{W.init(e,t),V(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),V(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),V(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),V(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>Fp(e.source)).join(`|`)})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,a)=>{if(n)return r(i,a);let o=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},a);if(t instanceof Promise)s.push(t),o=!0;else{if(t.issues.length===0)return t;s.push(t)}}return o?Promise.all(s).then(t=>lg(t,i,e,a)):lg(s,i,e,a)}}),dg=B(`$ZodIntersection`,(e,t)=>{W.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>pg(e,t,n)):pg(e,i,a)}});function fg(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Gp(e)&&Gp(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=fg(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=fg(i,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 pg(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),am(e))return e;let o=fg(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var mg=B(`$ZodEnum`,(e,t)=>{W.init(e,t);let n=jp(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>qp.has(typeof e)).map(e=>typeof e==`string`?Jp(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),hg=B(`$ZodTransform`,(e,t)=>{W.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Op(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Dp;return n.value=i,n}});function gg(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var _g=B(`$ZodOptional`,(e,t)=>{W.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,V(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),V(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Fp(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>gg(t,e.value)):gg(r,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),vg=B(`$ZodExactOptional`,(e,t)=>{_g.init(e,t),V(e._zod,`values`,()=>t.innerType._zod.values),V(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),yg=B(`$ZodNullable`,(e,t)=>{W.init(e,t),V(e._zod,`optin`,()=>t.innerType._zod.optin),V(e._zod,`optout`,()=>t.innerType._zod.optout),V(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Fp(e.source)}|null)$`):void 0}),V(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),bg=B(`$ZodDefault`,(e,t)=>{W.init(e,t),e._zod.optin=`optional`,V(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>xg(e,t)):xg(r,t)}});function xg(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Sg=B(`$ZodPrefault`,(e,t)=>{W.init(e,t),e._zod.optin=`optional`,V(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Cg=B(`$ZodNonOptional`,(e,t)=>{W.init(e,t),V(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>wg(t,e)):wg(i,e)}});function wg(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var Tg=B(`$ZodCatch`,(e,t)=>{W.init(e,t),V(e._zod,`optin`,()=>t.innerType._zod.optin),V(e._zod,`optout`,()=>t.innerType._zod.optout),V(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>cm(e,n,Ap()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>cm(e,n,Ap()))},input:e.value}),e.issues=[]),e)}}),Eg=B(`$ZodPipe`,(e,t)=>{W.init(e,t),V(e._zod,`values`,()=>t.in._zod.values),V(e._zod,`optin`,()=>t.in._zod.optin),V(e._zod,`optout`,()=>t.out._zod.optout),V(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Dg(e,t.in,n)):Dg(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Dg(e,t.out,n)):Dg(r,t.out,n)}});function Dg(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var Og=B(`$ZodReadonly`,(e,t)=>{W.init(e,t),V(e._zod,`propValues`,()=>t.innerType._zod.propValues),V(e._zod,`values`,()=>t.innerType._zod.values),V(e._zod,`optin`,()=>t.innerType?._zod?.optin),V(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(kg):kg(r)}});function kg(e){return e.value=Object.freeze(e.value),e}var Ag=B(`$ZodCustom`,(e,t)=>{U.init(e,t),W.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>jg(t,n,r,e));jg(i,n,r,e)}});function jg(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(um(e))}}var Mg,Ng=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Pg(){return new Ng}(Mg=globalThis).__zod_globalRegistry??(Mg.__zod_globalRegistry=Pg());var Fg=globalThis.__zod_globalRegistry;function Ig(e,t){return new e({type:`string`,...H(t)})}function Lg(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...H(t)})}function Rg(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...H(t)})}function zg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...H(t)})}function Bg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...H(t)})}function Vg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...H(t)})}function Hg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...H(t)})}function Ug(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...H(t)})}function Wg(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...H(t)})}function Gg(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...H(t)})}function Kg(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...H(t)})}function qg(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...H(t)})}function Jg(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...H(t)})}function Yg(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...H(t)})}function Xg(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...H(t)})}function Zg(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...H(t)})}function Qg(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...H(t)})}function $g(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...H(t)})}function e_(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...H(t)})}function t_(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...H(t)})}function n_(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...H(t)})}function r_(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...H(t)})}function i_(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...H(t)})}function a_(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...H(t)})}function o_(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...H(t)})}function s_(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...H(t)})}function c_(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...H(t)})}function l_(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...H(t)})}function u_(e,t){return new e({type:`boolean`,...H(t)})}function d_(e){return new e({type:`unknown`})}function f_(e,t){return new e({type:`never`,...H(t)})}function p_(e,t){return new sh({check:`less_than`,...H(t),value:e,inclusive:!1})}function m_(e,t){return new sh({check:`less_than`,...H(t),value:e,inclusive:!0})}function h_(e,t){return new ch({check:`greater_than`,...H(t),value:e,inclusive:!1})}function g_(e,t){return new ch({check:`greater_than`,...H(t),value:e,inclusive:!0})}function __(e,t){return new lh({check:`multiple_of`,...H(t),value:e})}function v_(e,t){return new dh({check:`max_length`,...H(t),maximum:e})}function y_(e,t){return new fh({check:`min_length`,...H(t),minimum:e})}function b_(e,t){return new ph({check:`length_equals`,...H(t),length:e})}function x_(e,t){return new hh({check:`string_format`,format:`regex`,...H(t),pattern:e})}function S_(e){return new gh({check:`string_format`,format:`lowercase`,...H(e)})}function C_(e){return new _h({check:`string_format`,format:`uppercase`,...H(e)})}function w_(e,t){return new vh({check:`string_format`,format:`includes`,...H(t),includes:e})}function T_(e,t){return new yh({check:`string_format`,format:`starts_with`,...H(t),prefix:e})}function E_(e,t){return new bh({check:`string_format`,format:`ends_with`,...H(t),suffix:e})}function D_(e){return new xh({check:`overwrite`,tx:e})}function O_(e){return D_(t=>t.normalize(e))}function k_(){return D_(e=>e.trim())}function A_(){return D_(e=>e.toLowerCase())}function j_(){return D_(e=>e.toUpperCase())}function M_(){return D_(e=>Vp(e))}function N_(e,t,n){return new e({type:`array`,element:t,...H(n)})}function P_(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...H(n)})}function F_(e){let t=I_(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(um(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(um(r))}},e(n.value,n)));return t}function I_(e,t){let n=new U({check:`custom`,...H(t)});return n._zod.check=e,n}function L_(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Fg,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function K(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,K(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&q(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function R_(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
58
75
 
59
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Ng(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?i.$defs=a:i.definitions=a);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:Fg(t,`input`,e.processors),output:Fg(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function q(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return q(r.element,n);if(r.type===`set`)return q(r.valueType,n);if(r.type===`lazy`)return q(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return q(r.innerType,n);if(r.type===`intersection`)return q(r.left,n)||q(r.right,n);if(r.type===`record`||r.type===`map`)return q(r.keyType,n)||q(r.valueType,n);if(r.type===`pipe`)return q(r.in,n)||q(r.out,n);if(r.type===`object`){for(let e in r.shape)if(q(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(q(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(q(e,n))return!0;return!!(r.rest&&q(r.rest,n))}return!1}var Pg=(e,t={})=>n=>{let r=jg({...n,processors:t});return K(e,r),Mg(r,e),Ng(r,e)},Fg=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=jg({...i??{},target:a,io:t,processors:n});return K(e,o),Mg(o,e),Ng(o,e)},Ig={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Lg=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Ig[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Rg=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`,typeof u==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof a==`number`&&(i.minimum=a,typeof u==`number`&&t.target!==`draft-04`&&(u>=a?delete i.minimum:delete i.exclusiveMinimum)),typeof l==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o==`number`&&(i.maximum=o,typeof l==`number`&&t.target!==`draft-04`&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c==`number`&&(i.multipleOf=c)},zg=(e,t,n,r)=>{n.type=`boolean`},Bg=(e,t,n,r)=>{n.not={}},Vg=(e,t,n,r)=>{let i=e._zod.def,a=Tf(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Hg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Ug=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Wg=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=K(a.element,t,{...r,path:[...r.path,`items`]})},Gg=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=K(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=K(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Kg=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>K(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},qg=(e,t,n,r)=>{let i=e._zod.def,a=K(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=K(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Jg=(e,t,n,r)=>{let i=e._zod.def,a=K(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Yg=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xg=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Zg=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Qg=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},$g=(e,t,n,r)=>{let i=e._zod.def,a=t.io===`input`?i.in._zod.def.type===`transform`?i.out:i.in:i.out;K(a,t,r);let o=t.seen.get(e);o.ref=a},e_=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},t_=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},n_=B(`ZodISODateTime`,(e,t)=>{Am.init(e,t),Y.init(e,t)});function r_(e){return $h(n_,e)}var i_=B(`ZodISODate`,(e,t)=>{jm.init(e,t),Y.init(e,t)});function a_(e){return eg(i_,e)}var o_=B(`ZodISOTime`,(e,t)=>{Mm.init(e,t),Y.init(e,t)});function s_(e){return tg(o_,e)}var c_=B(`ZodISODuration`,(e,t)=>{Nm.init(e,t),Y.init(e,t)});function l_(e){return ng(c_,e)}var u_=(e,t)=>{op.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>lp(e,t)},flatten:{value:t=>cp(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Ef,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Ef,2)}},isEmpty:{get(){return e.issues.length===0}}})};B(`ZodError`,u_);var d_=B(`ZodError`,u_,{Parent:Error}),f_=up(d_),p_=dp(d_),m_=fp(d_),h_=mp(d_),g_=gp(d_),__=_p(d_),v_=vp(d_),y_=yp(d_),b_=bp(d_),x_=xp(d_),S_=Sp(d_),C_=Cp(d_),J=B(`ZodType`,(e,t)=>(W.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Fg(e,`input`),output:Fg(e,`output`)}}),e.toJSONSchema=Pg(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone(Nf(t,{checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>Uf(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>f_(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>m_(e,t,n),e.parseAsync=async(t,n)=>p_(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>h_(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>g_(e,t,n),e.decode=(t,n)=>__(e,t,n),e.encodeAsync=async(t,n)=>v_(e,t,n),e.decodeAsync=async(t,n)=>y_(e,t,n),e.safeEncode=(t,n)=>b_(e,t,n),e.safeDecode=(t,n)=>x_(e,t,n),e.safeEncodeAsync=async(t,n)=>S_(e,t,n),e.safeDecodeAsync=async(t,n)=>C_(e,t,n),e.refine=(t,n)=>e.check(Mv(t,n)),e.superRefine=t=>e.check(Nv(t)),e.overwrite=t=>e.check(xg(t)),e.optional=()=>mv(e),e.exactOptional=()=>gv(e),e.nullable=()=>vv(e),e.nullish=()=>mv(vv(e)),e.nonoptional=t=>wv(e,t),e.array=()=>nv(e),e.or=t=>ov([e,t]),e.and=t=>cv(e,t),e.transform=t=>Ov(e,fv(t)),e.default=t=>bv(e,t),e.prefault=t=>Sv(e,t),e.catch=t=>Ev(e,t),e.pipe=t=>Ov(e,t),e.readonly=()=>Av(e),e.describe=t=>{let n=e.clone();return kh.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return kh.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return kh.get(e);let n=e.clone();return kh.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),w_=B(`_ZodString`,(e,t)=>{vm.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lg(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(hg(...t)),e.includes=(...t)=>e.check(vg(...t)),e.startsWith=(...t)=>e.check(yg(...t)),e.endsWith=(...t)=>e.check(bg(...t)),e.min=(...t)=>e.check(pg(...t)),e.max=(...t)=>e.check(fg(...t)),e.length=(...t)=>e.check(mg(...t)),e.nonempty=(...t)=>e.check(pg(1,...t)),e.lowercase=t=>e.check(gg(t)),e.uppercase=t=>e.check(_g(t)),e.trim=()=>e.check(Cg()),e.normalize=(...t)=>e.check(Sg(...t)),e.toLowerCase=()=>e.check(wg()),e.toUpperCase=()=>e.check(Tg()),e.slugify=()=>e.check(Eg())}),T_=B(`ZodString`,(e,t)=>{vm.init(e,t),w_.init(e,t),e.email=t=>e.check(jh(D_,t)),e.url=t=>e.check(Lh(A_,t)),e.jwt=t=>e.check(Qh(G_,t)),e.emoji=t=>e.check(Rh(j_,t)),e.guid=t=>e.check(Mh(O_,t)),e.uuid=t=>e.check(Nh(k_,t)),e.uuidv4=t=>e.check(Ph(k_,t)),e.uuidv6=t=>e.check(Fh(k_,t)),e.uuidv7=t=>e.check(Ih(k_,t)),e.nanoid=t=>e.check(zh(M_,t)),e.guid=t=>e.check(Mh(O_,t)),e.cuid=t=>e.check(Bh(N_,t)),e.cuid2=t=>e.check(Vh(P_,t)),e.ulid=t=>e.check(Hh(F_,t)),e.base64=t=>e.check(Yh(H_,t)),e.base64url=t=>e.check(Xh(U_,t)),e.xid=t=>e.check(Uh(I_,t)),e.ksuid=t=>e.check(Wh(L_,t)),e.ipv4=t=>e.check(Gh(R_,t)),e.ipv6=t=>e.check(Kh(z_,t)),e.cidrv4=t=>e.check(qh(B_,t)),e.cidrv6=t=>e.check(Jh(V_,t)),e.e164=t=>e.check(Zh(W_,t)),e.datetime=t=>e.check(r_(t)),e.date=t=>e.check(a_(t)),e.time=t=>e.check(s_(t)),e.duration=t=>e.check(l_(t))});function E_(e){return Ah(T_,e)}var Y=B(`ZodStringFormat`,(e,t)=>{G.init(e,t),w_.init(e,t)}),D_=B(`ZodEmail`,(e,t)=>{xm.init(e,t),Y.init(e,t)}),O_=B(`ZodGUID`,(e,t)=>{ym.init(e,t),Y.init(e,t)}),k_=B(`ZodUUID`,(e,t)=>{bm.init(e,t),Y.init(e,t)}),A_=B(`ZodURL`,(e,t)=>{Sm.init(e,t),Y.init(e,t)}),j_=B(`ZodEmoji`,(e,t)=>{Cm.init(e,t),Y.init(e,t)}),M_=B(`ZodNanoID`,(e,t)=>{wm.init(e,t),Y.init(e,t)}),N_=B(`ZodCUID`,(e,t)=>{Tm.init(e,t),Y.init(e,t)}),P_=B(`ZodCUID2`,(e,t)=>{Em.init(e,t),Y.init(e,t)}),F_=B(`ZodULID`,(e,t)=>{Dm.init(e,t),Y.init(e,t)}),I_=B(`ZodXID`,(e,t)=>{Om.init(e,t),Y.init(e,t)}),L_=B(`ZodKSUID`,(e,t)=>{km.init(e,t),Y.init(e,t)}),R_=B(`ZodIPv4`,(e,t)=>{Pm.init(e,t),Y.init(e,t)}),z_=B(`ZodIPv6`,(e,t)=>{Fm.init(e,t),Y.init(e,t)}),B_=B(`ZodCIDRv4`,(e,t)=>{Im.init(e,t),Y.init(e,t)}),V_=B(`ZodCIDRv6`,(e,t)=>{Lm.init(e,t),Y.init(e,t)}),H_=B(`ZodBase64`,(e,t)=>{zm.init(e,t),Y.init(e,t)}),U_=B(`ZodBase64URL`,(e,t)=>{Vm.init(e,t),Y.init(e,t)}),W_=B(`ZodE164`,(e,t)=>{Hm.init(e,t),Y.init(e,t)}),G_=B(`ZodJWT`,(e,t)=>{Wm.init(e,t),Y.init(e,t)}),K_=B(`ZodNumber`,(e,t)=>{Gm.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rg(e,t,n,r),e.gt=(t,n)=>e.check(lg(t,n)),e.gte=(t,n)=>e.check(ug(t,n)),e.min=(t,n)=>e.check(ug(t,n)),e.lt=(t,n)=>e.check(sg(t,n)),e.lte=(t,n)=>e.check(cg(t,n)),e.max=(t,n)=>e.check(cg(t,n)),e.int=t=>e.check(J_(t)),e.safe=t=>e.check(J_(t)),e.positive=t=>e.check(lg(0,t)),e.nonnegative=t=>e.check(ug(0,t)),e.negative=t=>e.check(sg(0,t)),e.nonpositive=t=>e.check(cg(0,t)),e.multipleOf=(t,n)=>e.check(dg(t,n)),e.step=(t,n)=>e.check(dg(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null}),q_=B(`ZodNumberFormat`,(e,t)=>{Km.init(e,t),K_.init(e,t)});function J_(e){return rg(q_,e)}var Y_=B(`ZodBoolean`,(e,t)=>{qm.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zg(e,t,n,r)});function X_(e){return ig(Y_,e)}var Z_=B(`ZodUnknown`,(e,t)=>{Jm.init(e,t),J.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Q_(){return ag(Z_)}var $_=B(`ZodNever`,(e,t)=>{Ym.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bg(e,t,n,r)});function ev(e){return og($_,e)}var tv=B(`ZodArray`,(e,t)=>{Zm.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wg(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(pg(t,n)),e.nonempty=t=>e.check(pg(1,t)),e.max=(t,n)=>e.check(fg(t,n)),e.length=(t,n)=>e.check(mg(t,n)),e.unwrap=()=>e.element});function nv(e,t){return Dg(tv,e,t)}var rv=B(`ZodObject`,(e,t)=>{nh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gg(e,t,n,r),V(e,`shape`,()=>t.shape),e.keyof=()=>uv(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Q_()}),e.loose=()=>e.clone({...e._zod.def,catchall:Q_()}),e.strict=()=>e.clone({...e._zod.def,catchall:ev()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Jf(e,t),e.safeExtend=t=>Yf(e,t),e.merge=t=>Xf(e,t),e.pick=t=>Kf(e,t),e.omit=t=>qf(e,t),e.partial=(...t)=>Zf(pv,e,t[0]),e.required=(...t)=>Qf(Cv,e,t[0])});function iv(e,t){return new rv({type:`object`,shape:e??{},...H(t)})}var av=B(`ZodUnion`,(e,t)=>{ih.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kg(e,t,n,r),e.options=t.options});function ov(e,t){return new av({type:`union`,options:e,...H(t)})}var sv=B(`ZodIntersection`,(e,t)=>{ah.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qg(e,t,n,r)});function cv(e,t){return new sv({type:`intersection`,left:e,right:t})}var lv=B(`ZodEnum`,(e,t)=>{ch.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vg(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new lv({...t,checks:[],...H(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new lv({...t,checks:[],...H(r),entries:i})}});function uv(e,t){return new lv({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...H(t)})}var dv=B(`ZodTransform`,(e,t)=>{lh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ug(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Sf(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(ip(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(ip(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function fv(e){return new dv({type:`transform`,transform:e})}var pv=B(`ZodOptional`,(e,t)=>{dh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>t_(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function mv(e){return new pv({type:`optional`,innerType:e})}var hv=B(`ZodExactOptional`,(e,t)=>{fh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>t_(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function gv(e){return new hv({type:`optional`,innerType:e})}var _v=B(`ZodNullable`,(e,t)=>{ph.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function vv(e){return new _v({type:`nullable`,innerType:e})}var yv=B(`ZodDefault`,(e,t)=>{mh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function bv(e,t){return new yv({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Bf(t)}})}var xv=B(`ZodPrefault`,(e,t)=>{gh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Sv(e,t){return new xv({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Bf(t)}})}var Cv=B(`ZodNonOptional`,(e,t)=>{_h.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wv(e,t){return new Cv({type:`nonoptional`,innerType:e,...H(t)})}var Tv=B(`ZodCatch`,(e,t)=>{yh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ev(e,t){return new Tv({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Dv=B(`ZodPipe`,(e,t)=>{bh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$g(e,t,n,r),e.in=t.in,e.out=t.out});function Ov(e,t){return new Dv({type:`pipe`,in:e,out:t})}var kv=B(`ZodReadonly`,(e,t)=>{Sh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>e_(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Av(e){return new kv({type:`readonly`,innerType:e})}var jv=B(`ZodCustom`,(e,t)=>{wh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hg(e,t,n,r)});function Mv(e,t={}){return Og(jv,e,t)}function Nv(e){return kg(e)}var Pv=function(e){return e[e.invalid=0]=`invalid`,e[e.u8=1]=`u8`,e[e.u16=2]=`u16`,e[e.u32=3]=`u32`,e[e.u64=4]=`u64`,e[e.i8=5]=`i8`,e[e.i16=6]=`i16`,e[e.i32=7]=`i32`,e[e.i64=8]=`i64`,e[e.f32=9]=`f32`,e[e.f64=10]=`f64`,e[e.string=11]=`string`,e[e.chan=14]=`chan`,e[e.series=15]=`series`,e[e.variable=16]=`variable`,e[e.numeric_constant=17]=`numeric_constant`,e[e.integer_constant=18]=`integer_constant`,e[e.float_constant=19]=`float_constant`,e[e.exact_integer_float_constant=20]=`exact_integer_float_constant`,e[e.function=21]=`function`,e[e.sequence=22]=`sequence`,e[e.stage=23]=`stage`,e}({}),Fv=l.z.enum(Pv),Iv=function(e){return e[e.none=0]=`none`,e[e.read=1]=`read`,e[e.write=2]=`write`,e}({}),Lv=l.z.enum(Iv),Rv=l.z.object({read:l.z.record(l.z.uint32(),l.z.string()),write:l.z.record(l.z.uint32(),l.z.string())}),zv=l.z.object({length:N.int8,mass:N.int8,time:N.int8,current:N.int8,temperature:N.int8,angle:N.int8,count:N.int8,data:N.int8}),Bv=l.z.object({dimensions:zv,scale:l.z.number(),name:l.z.string()}),Vv=l.z.object({get inputs(){return Uv.optional()},get outputs(){return Uv.optional()},get config(){return Uv.optional()}}).extend({kind:Fv,name:l.z.string(),get elem(){return Vv.optional()},unit:Bv.optional(),get constraint(){return Vv.optional()},chanDirection:Lv.optional()}),Hv=l.z.object({name:l.z.string(),type:Vv,value:l.z.unknown().optional()}),Uv=w.nullishToEmpty(Hv),Wv=o({EdgeKind:()=>Gv,authoritiesZ:()=>Xv,bodyZ:()=>Jv,edgeKindZ:()=>Kv,edgeZ:()=>Qv,edgesZ:()=>ny,functionZ:()=>$v,functionsZ:()=>ry,handleZ:()=>qv,irZ:()=>cy,nodeZ:()=>Yv,nodesZ:()=>ey,sequenceZ:()=>ay,sequencesZ:()=>sy,stageZ:()=>iy,stagesZ:()=>oy,strataZ:()=>ty,stratumZ:()=>Zv}),Gv=function(e){return e[e.unspecified=0]=`unspecified`,e[e.continuous=1]=`continuous`,e[e.one_shot=2]=`one_shot`,e}({}),Kv=l.z.enum(Gv),qv=l.z.object({node:l.z.string(),param:l.z.string()}),Jv=l.z.object({raw:l.z.string()}),Yv=l.z.object({key:l.z.string(),type:l.z.string(),config:Uv.optional(),inputs:Uv.optional(),outputs:Uv.optional(),channels:Rv.optional()}),Xv=l.z.object({default:N.uint8.optional(),channels:l.z.record(l.z.uint32(),N.uint8).optional()}),Zv=w.nullishToEmpty(l.z.string()),Qv=l.z.object({source:qv,target:qv,kind:Kv.optional()}),$v=l.z.object({key:l.z.string(),body:Jv.optional(),config:Uv.optional(),inputs:Uv.optional(),outputs:Uv.optional(),channels:Rv.optional()}),ey=w.nullishToEmpty(Yv),ty=w.nullishToEmpty(Zv),ny=w.nullishToEmpty(Qv),ry=w.nullishToEmpty($v),iy=l.z.object({key:l.z.string(),nodes:w.nullishToEmpty(l.z.string()),strata:ty}),ay=l.z.object({key:l.z.string(),stages:w.nullishToEmpty(iy)}),oy=w.nullishToEmpty(iy),sy=w.nullishToEmpty(ay),cy=l.z.object({functions:ry.optional(),nodes:ey.optional(),edges:ny.optional(),strata:ty.optional(),sequences:sy.optional(),authorities:Xv.optional()}),ly=o({graphZ:()=>py,nodeZ:()=>uy,nodesZ:()=>fy,viewportZ:()=>dy}),uy=l.z.object({key:l.z.string(),type:l.z.string(),config:I.nullishToEmpty(),position:xo.xyZ}),dy=l.z.object({position:xo.xyZ,zoom:l.z.number()}),fy=w.nullishToEmpty(uy),py=l.z.object({viewport:dy,functions:ry,edges:ny,nodes:fy}),my=o({outputZ:()=>hy}),hy=l.z.object({wasm:l.z.instanceof(Uint8Array),outputMemoryBases:l.z.record(l.z.string(),l.z.uint32())}),gy=cy.extend(hy.shape),_y=o({textZ:()=>vy}),vy=l.z.object({raw:l.z.string()}),yy=[`text`,`graph`],by=l.z.enum(yy),xy=l.z.object({running:l.z.boolean()}),Sy=l.z.uuid(),Cy=cu.statusZ({details:xy}),wy=l.z.object({key:Sy.optional(),name:l.z.string(),mode:by,graph:py,text:vy}),Ty=l.z.object({key:Sy,name:l.z.string(),mode:by,graph:py,text:vy,program:gy.optional(),status:Cy.optional()}),Ey=z(`arc`),Dy=Ey(``),Oy=(e,t,{convertNumericStrings:n=!0}={})=>{let r=!Array.isArray(e),i=w.toArray(e),a=i[0],o=typeof a,s;return o===`string`&&n&&!isNaN(parseInt(a,10))&&`number`in t?(s=t.number,i=i.map(e=>parseInt(e,10))):s=t[o],{single:r,variant:s,normalized:i,actual:e}},X=(e,t,n,r)=>{if(r){if(n.length===0)throw new Eu(`${e} not found matching ${JSON.stringify(t)}`);if(n.length>1)throw new Du(`Expected one ${e} matching ${JSON.stringify(t)}, but found ${n.length}`)}},ky=`sy_arc_set`,Ay=`sy_arc_delete`,jy=iv({keys:Sy.array().optional(),names:E_().array().optional(),searchTerm:E_().optional(),limit:J_().optional(),offset:J_().optional(),includeStatus:X_().optional()}),My=iv({arcs:wy.array()}),Ny=iv({keys:Sy.array()}),Py=iv({arcs:w.nullishToEmpty(Ty)}),Fy=iv({arcs:Ty.array()}),Iy=iv({}),Ly=iv({content:E_()}),Ry=ov([iv({key:Sy,includeStatus:X_().optional()}).transform(({key:e,includeStatus:t})=>({keys:[e],includeStatus:t})),iv({name:E_(),includeStatus:X_().optional()}).transform(({name:e,includeStatus:t})=>({names:[e],includeStatus:t}))]),zy=ov([Ry,jy]),By=class{client;streamClient;constructor(e,t){this.client=e,this.streamClient=t}async create(e){let t=Array.isArray(e),n=await S(this.client,`/arc/create`,{arcs:w.toArray(e)},My,Fy);return t?n.arcs:n.arcs[0]}async retrieve(e){let t=`key`in e||`name`in e,n=await S(this.client,`/arc/retrieve`,e,zy,Py);return X(`Arc`,e,n.arcs,t),t?n.arcs[0]:n.arcs}async delete(e){await S(this.client,`/arc/delete`,{keys:w.toArray(e)},Ny,Iy)}async openLSP(){return await this.streamClient.stream(`/arc/lsp`,Ly,Ly)}},Vy=o({moduleZ:()=>Hy}),Hy=cy.extend(hy.shape),Uy=o({Client:()=>By,DELETE_CHANNEL_NAME:()=>Ay,MODES:()=>yy,SET_CHANNEL_NAME:()=>ky,TYPE_ONTOLOGY_ID:()=>Dy,arcZ:()=>Ty,compiler:()=>my,graph:()=>ly,ir:()=>Wv,keyZ:()=>Sy,lspMessageZ:()=>Ly,modeZ:()=>by,module:()=>Vy,newZ:()=>wy,ontologyID:()=>Ey,singleRetrieveArgsZ:()=>Ry,statusDetailsZ:()=>xy,statusZ:()=>Cy,text:()=>_y}),Wy=Error(`request for lock canceled`),Gy=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Ky=class{constructor(e,t=Wy){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=Jy(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return Gy(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),qy(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw 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){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function qy(e,t){let n=Jy(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function Jy(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var Yy=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Xy=class{constructor(e){this._semaphore=new Ky(1,e)}acquire(){return Yy(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}},Zy=N.uint12,Z=l.z.uint32().or(l.z.string().refine(e=>!isNaN(Number(e))).transform(Number)),Qy=N.uint20,$y=[`min`,`max`,`avg`,`none`],eb=l.z.enum($y),tb=l.z.object({type:eb,resetChannel:Z.default(0),duration:us.timeSpanZ.default(O.ZERO)}),nb=l.z.string().min(1,`Name is required`),rb=cu.statusZ(),ib=l.z.object({key:Z,name:nb,leaseholder:Zy,dataType:us.dataTypeZ,isIndex:l.z.boolean(),index:Z,alias:l.z.string().optional(),virtual:l.z.boolean().default(!1),internal:l.z.boolean().default(!1),expression:l.z.string().default(``),operations:N.nullToUndefined(tb.array()),concurrency:F.concurrencyZ.default(F.Concurrency.exclusive).optional(),status:rb.optional()}),ab=ib.omit({leaseholder:!0}).partial({key:!0,index:!0,isIndex:!0,internal:!0,virtual:!0,expression:!0}).extend({leaseholder:N.uint12.optional()}),ob=z(`channel`),sb=ob(0),Q=l.z.uuid(),cb=l.z.object({key:Q,name:l.z.string().min(1),timeRange:us.timeRangeZ,color:Nc.colorZ.optional()}),lb=cb.extend({labels:N.nullToUndefined(fl.labelZ.array()),get parent(){return lb.optional()}}),ub=cb.omit({timeRange:!0}).extend({labels:N.nullToUndefined(fl.labelZ.array()),get parent(){return ub.optional()},timeRange:us.timeRangeBoundedZ}),db=ub.omit({parent:!0,labels:!0}).partial({key:!0}),fb=z(`range`),pb=fb(``),mb=l.z.object({nodeKey:N.uint12.optional(),keys:Z.array().optional(),names:l.z.string().array().optional(),searchTerm:l.z.string().optional(),rangeKey:Q.optional(),limit:l.z.int().optional(),offset:l.z.int().optional(),dataTypes:j.z.array().optional(),notDataTypes:j.z.array().optional(),virtual:l.z.boolean().optional(),isIndex:l.z.boolean().optional(),internal:l.z.boolean().optional(),legacyCalculated:l.z.boolean().optional()}),hb=l.z.object({channels:w.nullishToEmpty(ib)}),gb=e=>(Array.isArray(e)&&e.length>0&&typeof e[0]==`object`?e=e.map(e=>e.key):typeof e==`object`&&`key`in e&&(e=[e.key]),Oy(e,{number:`keys`,string:`names`})),_b=class{client;constructor(e){this.client=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e==`object`)return await this.execute(e);let n=gb(e),{variant:r}=n,{normalized:i}=n;return r===`keys`&&i.indexOf(0)!==-1&&(i=i.filter(e=>e!==0)),i.length===0?[]:await this.execute({[r]:i,...t})}async execute(e){return(await S(this.client,`/channel/retrieve`,e,mb,hb)).channels}},vb=class{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e==`object`)return await this.wrapped.retrieve(e);let{normalized:n}=gb(e),r=[],i=[];if(n.forEach(e=>{let t=this.get(e);t==null?i.push(e):r.push(...t)}),i.length===0)return r;let a=await this.wrapped.retrieve(i,t);return this.set(a),r.concat(a)}delete(e){let{variant:t,normalized:n}=gb(e);t===`names`?n.forEach(e=>{let t=this.namesToKeys.get(e);t!=null&&(t.forEach(e=>this.cache.delete(e)),this.namesToKeys.delete(e))}):n.forEach(e=>{let t=this.cache.get(e);t!=null&&(this.cache.delete(e),this.namesToKeys.delete(t.name))})}rename(e,t){e.forEach((e,n)=>{let r=t[n],i=this.cache.get(e);if(i==null)return;this.cache.delete(e);let a=this.namesToKeys.get(i.name);a!=null&&(a.delete(e),a.size===0&&this.namesToKeys.delete(i.name)),i.name=r,this.cache.set(e,i);let o=this.namesToKeys.get(r);o==null?this.namesToKeys.set(r,new Set([e])):o.add(e)})}set(e){e.forEach(e=>{this.cache.set(e.key,e);let t=this.namesToKeys.get(e.name);t==null?this.namesToKeys.set(e.name,new Set([e.key])):t.add(e.key)})}get(e){if(typeof e==`number`){let t=this.cache.get(e);return t==null?void 0:[t]}let t=this.namesToKeys.get(e);if(t==null)return;let n=[];if(t.forEach(e=>{let t=this.cache.get(e);t!=null&&n.push(t)}),n.length!==0)return n}},yb=class{mu=new Xy;requests=new Map;wrapped;debouncedRun;constructor(e,t){this.wrapped=e,this.debouncedRun=Jc(()=>{this.run()},t)}async retrieve(e){if(!Array.isArray(e)&&typeof e==`object`)return await this.wrapped.retrieve(e);let{normalized:t,variant:n}=gb(e);return n===`names`?await this.wrapped.retrieve(t):await new Promise((e,n)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:e,reject:n}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{let e=new Set;this.requests.forEach((t,n)=>n.forEach(t=>e.add(t)));try{let t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((e,n)=>e.resolve(t.filter(e=>n.includes(e.key))))}catch(e){this.requests.forEach(t=>t.reject(e))}finally{this.requests.clear()}})}},bb=async(e,t)=>{let{normalized:n}=gb(t),r=await e.retrieve(n),i=[];if(n.forEach(e=>{r.find(t=>t.name===e||t.key===e)??i.push(e)}),i.length>0)throw new Tu(`Could not find channels: ${JSON.stringify(i)}`);return r},xb=l.z.uuid(),Sb=l.z.object({key:xb,name:l.z.string()}),Cb=z(`group`),wb=Cb(``),Tb=`sy_group_set`,Eb=`sy_group_delete`,Db=l.default.object({group:Sb}),Ob=l.default.object({parent:R,key:xb.optional(),name:l.default.string()}),kb=l.default.object({key:xb,name:l.default.string()}),Ab=l.default.object({keys:l.default.array(xb)}),jb=class{client;constructor(e){this.client=e}async create(e){return(await S(this.client,`/ontology/create-group`,e,Ob,Db)).group}async rename(e,t){await S(this.client,`/ontology/rename-group`,{key:e,name:t},kb,l.default.object({}))}async delete(e){await S(this.client,`/ontology/delete-group`,{keys:w.toArray(e)},Ab,l.default.object({}))}},Mb=o({Client:()=>jb,DELETE_CHANNEL_NAME:()=>Eb,SET_CHANNEL_NAME:()=>Tb,TYPE_ONTOLOGY_ID:()=>wb,groupZ:()=>Sb,keyZ:()=>xb,ontologyID:()=>Cb}),Nb=`sy_channel_set`,Pb=`sy_channel_delete`,Fb=class{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;operations;status;constructor({dataType:e,name:t,leaseholder:n=0,key:r=0,isIndex:i=!1,index:a=0,internal:o=!1,virtual:s=!1,frameClient:c,alias:l,status:u,expression:d=``,operations:f=[]}){this.key=Z.parse(r),this.name=t,this.dataType=new j(e),this.leaseholder=n,this.index=Z.parse(a),this.isIndex=i,this.internal=o,this.alias=l,this.virtual=s,this.expression=d,this.operations=f,u!=null&&(this.status=cu.create(u)),this._frameClient=c??null}get framer(){if(this._frameClient==null)throw new L(`cannot read from a channel that has not been created`);return this._frameClient}get payload(){return ib.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,expression:this.expression,status:this.status,operations:this.operations})}get isCalculated(){return zb(this.payload)}get ontologyID(){return ob(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}},Ib=l.z.object({}),Lb=l.z.object({group:Sb}),Rb=class{frameClient;client;retriever;writer;constructor(e,t,n,r){this.frameClient=e,this.retriever=t,this.client=n,this.writer=r}async create(e,t={}){let{retrieveIfNameExists:n=!1}=t,r=!Array.isArray(e),i=w.toArray(e),a=[];if(n){let e=await this.retriever.retrieve(i.map(e=>e.name)),t=new Set(e.map(e=>e.name));i=i.filter(e=>!t.has(e.name)),a=this.sugar(e)}return a=a.concat(this.sugar(await this.writer.create(i))),r?a[0]:a}async retrieve(e,t){if(typeof e==`object`&&!Array.isArray(e))return this.sugar(await this.retriever.retrieve(e));let n=!Array.isArray(e),r=this.sugar(await this.retriever.retrieve(e,t));return X(`channel`,e,r,n),n?r[0]:r}async delete(e){let{normalized:t,variant:n}=gb(e);return n===`keys`?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(w.toArray(e),w.toArray(t))}createDebouncedBatchRetriever(e=10){return new vb(new yb(new _b(this.client),e))}sugar(e){let{frameClient:t}=this;return Array.isArray(e)?e.map(e=>new Fb({...e,frameClient:t})):new Fb({...e,frameClient:t})}async retrieveGroup(){return(await S(this.client,`/channel/retrieve-group`,{},Ib,Lb)).group}},zb=({virtual:e,expression:t})=>e&&t!==``,Bb=l.z.union([N.toArray(Z),N.toArray(nb),N.toArray(ib).transform(e=>e.map(e=>e.key))]),Vb=/[a-zA-Z0-9_]/,Hb=/^[a-zA-Z_][a-zA-Z0-9_]*$/,Ub=(e,t=!1)=>{if(e===``)return t?`_`:``;if(e.match(Hb))return e;let n=``;for(let t of e)t.match(Vb)?n+=t:n+=`_`;return n[0].match(/^\d/)&&(n=`_${n}`),n},Wb=e=>Ru(ob(e)),Gb=l.z.object({channels:ab.array()}),Kb=l.z.object({channels:ib.array()}),qb=l.z.object({keys:Z.array().optional(),names:nb.array().optional()}),Jb=l.z.object({}),Yb=l.z.object({keys:Z.array(),names:nb.array()}),Xb=l.z.object({}),Zb=class{client;cache;constructor(e,t){this.client=e,this.cache=t}async create(e){let{channels:t}=await S(this.client,`/channel/create`,{channels:e.map(e=>({...e,dataType:e.dataType}))},Gb,Kb);return this.cache.set(t),t}async delete(e){let t=Z.array().parse(e.keys??[]);await S(this.client,`/channel/delete`,e,qb,Jb),t.length>0&&this.cache.delete(t),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await S(this.client,`/channel/rename`,{keys:e,names:t},Yb,Xb),this.cache.rename(e,t)}},Qb=o({CacheRetriever:()=>vb,Channel:()=>Fb,Client:()=>Rb,ClusterRetriever:()=>_b,DELETE_CHANNEL_NAME:()=>Pb,DebouncedBatchRetriever:()=>yb,OPERATION_TYPES:()=>$y,SET_CHANNEL_NAME:()=>Nb,TYPE_ONTOLOGY_ID:()=>sb,Writer:()=>Zb,analyzeParams:()=>gb,escapeInvalidName:()=>Ub,isCalculated:()=>zb,keyZ:()=>Z,localKeyZ:()=>Qy,nameZ:()=>nb,newZ:()=>ab,ontologyID:()=>ob,operationTypeZ:()=>eb,operationZ:()=>tb,paramsZ:()=>Bb,payloadZ:()=>ib,retrieveRequired:()=>bb,statusKey:()=>Wb,statusZ:()=>rb}),$b=l.z.object({username:l.z.string(),password:l.z.string()}),ex=l.z.object({token:l.z.string(),user:jd}),tx=`/auth/login`,nx=3,rx=l.z.object({username:l.z.string(),password:l.z.string(),newPassword:l.z.string().min(1)}),ix=l.z.object({}),ax=[Su,Cu],ox=class{client;credentials;authState={authenticated:!1};authenticating;retryCount;constructor(e,t){this.client=e,this.credentials=t,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;let{authState:e}=this;if(!e.authenticated)throw Error(`Authentication failed: user not available`);return e.user}async changePassword(e){if(!this.authenticated)throw Error(`Not authenticated`);await S(this.client,`/auth/change-password`,{username:this.credentials.username,password:this.credentials.password,newPassword:e},rx,ix),this.credentials.password=e}middleware(){let e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(tx)){this.authenticating??=new Promise((e,t)=>{this.client.send(tx,this.credentials,$b,ex).then(([t,n])=>{if(n!=null)return e(n);if(t==null)return e(Error(`No response from login`));this.authState={authenticated:!0,user:t.user,token:t.token},e(null)}).catch(t)});let e=await this.authenticating;if(e!=null)return[t,e]}t.params.Authorization=`Bearer ${this.token}`;let[r,i]=await n(t);return ax.some(e=>e.matches(i))&&this.retryCount<nx?(this.authState={authenticated:!1},this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[r,i])};return e}},sx=o({Checker:()=>mx,stateZ:()=>lx,statusZ:()=>cx}),cx=l.z.enum([`disconnected`,`connecting`,`connected`,`failed`]),lx=l.z.object({status:cx,error:l.z.instanceof(Error).optional(),message:l.z.string().optional(),clusterKey:l.z.string(),clientVersion:l.z.string(),clientServerCompatible:l.z.boolean(),nodeVersion:l.z.string().optional()}),ux=l.z.object({clusterKey:l.z.string(),nodeVersion:l.z.string().optional()}),dx=l.z.void(),fx={clusterKey:``,status:`disconnected`,error:void 0,message:`Disconnected`,clientServerCompatible:!1,clientVersion:`0.54.0`},px=(e,t,n)=>{let r=n?`Core`:`client`;return`Synnax Core version ${e==null?``:`${e} `}is too ${n?`old`:`new`} for client version ${t}.
76
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function z_(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?i.$defs=a:i.definitions=a);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:V_(t,`input`,e.processors),output:V_(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function q(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return q(r.element,n);if(r.type===`set`)return q(r.valueType,n);if(r.type===`lazy`)return q(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return q(r.innerType,n);if(r.type===`intersection`)return q(r.left,n)||q(r.right,n);if(r.type===`record`||r.type===`map`)return q(r.keyType,n)||q(r.valueType,n);if(r.type===`pipe`)return q(r.in,n)||q(r.out,n);if(r.type===`object`){for(let e in r.shape)if(q(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(q(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(q(e,n))return!0;return!!(r.rest&&q(r.rest,n))}return!1}var B_=(e,t={})=>n=>{let r=L_({...n,processors:t});return K(e,r),R_(r,e),z_(r,e)},V_=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=L_({...i??{},target:a,io:t,processors:n});return K(e,o),R_(o,e),z_(o,e)},H_={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},U_=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=H_[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},W_=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`,typeof u==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof a==`number`&&(i.minimum=a,typeof u==`number`&&t.target!==`draft-04`&&(u>=a?delete i.minimum:delete i.exclusiveMinimum)),typeof l==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o==`number`&&(i.maximum=o,typeof l==`number`&&t.target!==`draft-04`&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c==`number`&&(i.multipleOf=c)},G_=(e,t,n,r)=>{n.type=`boolean`},K_=(e,t,n,r)=>{n.not={}},q_=(e,t,n,r)=>{let i=e._zod.def,a=jp(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},J_=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Y_=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},X_=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=K(a.element,t,{...r,path:[...r.path,`items`]})},Z_=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=K(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=K(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Q_=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>K(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},$_=(e,t,n,r)=>{let i=e._zod.def,a=K(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=K(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},ev=(e,t,n,r)=>{let i=e._zod.def,a=K(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},tv=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},nv=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},rv=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},iv=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},av=(e,t,n,r)=>{let i=e._zod.def,a=t.io===`input`?i.in._zod.def.type===`transform`?i.out:i.in:i.out;K(a,t,r);let o=t.seen.get(e);o.ref=a},ov=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},sv=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},cv=B(`ZodISODateTime`,(e,t)=>{Ih.init(e,t),Y.init(e,t)});function lv(e){return a_(cv,e)}var uv=B(`ZodISODate`,(e,t)=>{Lh.init(e,t),Y.init(e,t)});function dv(e){return o_(uv,e)}var fv=B(`ZodISOTime`,(e,t)=>{Rh.init(e,t),Y.init(e,t)});function pv(e){return s_(fv,e)}var mv=B(`ZodISODuration`,(e,t)=>{zh.init(e,t),Y.init(e,t)});function hv(e){return c_(mv,e)}var gv=(e,t)=>{fm.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>hm(e,t)},flatten:{value:t=>mm(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Mp,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Mp,2)}},isEmpty:{get(){return e.issues.length===0}}})};B(`ZodError`,gv);var _v=B(`ZodError`,gv,{Parent:Error}),vv=gm(_v),yv=_m(_v),bv=vm(_v),xv=bm(_v),Sv=Sm(_v),Cv=Cm(_v),wv=wm(_v),Tv=Tm(_v),Ev=Em(_v),Dv=Dm(_v),Ov=Om(_v),kv=km(_v),J=B(`ZodType`,(e,t)=>(W.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:V_(e,`input`),output:V_(e,`output`)}}),e.toJSONSchema=B_(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone(zp(t,{checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>Yp(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>vv(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>bv(e,t,n),e.parseAsync=async(t,n)=>yv(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>xv(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Sv(e,t,n),e.decode=(t,n)=>Cv(e,t,n),e.encodeAsync=async(t,n)=>wv(e,t,n),e.decodeAsync=async(t,n)=>Tv(e,t,n),e.safeEncode=(t,n)=>Ev(e,t,n),e.safeDecode=(t,n)=>Dv(e,t,n),e.safeEncodeAsync=async(t,n)=>Ov(e,t,n),e.safeDecodeAsync=async(t,n)=>kv(e,t,n),e.refine=(t,n)=>e.check(Ry(t,n)),e.superRefine=t=>e.check(zy(t)),e.overwrite=t=>e.check(D_(t)),e.optional=()=>by(e),e.exactOptional=()=>Sy(e),e.nullable=()=>wy(e),e.nullish=()=>by(wy(e)),e.nonoptional=t=>Ay(e,t),e.array=()=>cy(e),e.or=t=>fy([e,t]),e.and=t=>my(e,t),e.transform=t=>Py(e,vy(t)),e.default=t=>Ey(e,t),e.prefault=t=>Oy(e,t),e.catch=t=>My(e,t),e.pipe=t=>Py(e,t),e.readonly=()=>Iy(e),e.describe=t=>{let n=e.clone();return Fg.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return Fg.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return Fg.get(e);let n=e.clone();return Fg.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),Av=B(`_ZodString`,(e,t)=>{wh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>U_(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(x_(...t)),e.includes=(...t)=>e.check(w_(...t)),e.startsWith=(...t)=>e.check(T_(...t)),e.endsWith=(...t)=>e.check(E_(...t)),e.min=(...t)=>e.check(y_(...t)),e.max=(...t)=>e.check(v_(...t)),e.length=(...t)=>e.check(b_(...t)),e.nonempty=(...t)=>e.check(y_(1,...t)),e.lowercase=t=>e.check(S_(t)),e.uppercase=t=>e.check(C_(t)),e.trim=()=>e.check(k_()),e.normalize=(...t)=>e.check(O_(...t)),e.toLowerCase=()=>e.check(A_()),e.toUpperCase=()=>e.check(j_()),e.slugify=()=>e.check(M_())}),jv=B(`ZodString`,(e,t)=>{wh.init(e,t),Av.init(e,t),e.email=t=>e.check(Lg(Nv,t)),e.url=t=>e.check(Ug(Iv,t)),e.jwt=t=>e.check(i_(Zv,t)),e.emoji=t=>e.check(Wg(Lv,t)),e.guid=t=>e.check(Rg(Pv,t)),e.uuid=t=>e.check(zg(Fv,t)),e.uuidv4=t=>e.check(Bg(Fv,t)),e.uuidv6=t=>e.check(Vg(Fv,t)),e.uuidv7=t=>e.check(Hg(Fv,t)),e.nanoid=t=>e.check(Gg(Rv,t)),e.guid=t=>e.check(Rg(Pv,t)),e.cuid=t=>e.check(Kg(zv,t)),e.cuid2=t=>e.check(qg(Bv,t)),e.ulid=t=>e.check(Jg(Vv,t)),e.base64=t=>e.check(t_(Jv,t)),e.base64url=t=>e.check(n_(Yv,t)),e.xid=t=>e.check(Yg(Hv,t)),e.ksuid=t=>e.check(Xg(Uv,t)),e.ipv4=t=>e.check(Zg(Wv,t)),e.ipv6=t=>e.check(Qg(Gv,t)),e.cidrv4=t=>e.check($g(Kv,t)),e.cidrv6=t=>e.check(e_(qv,t)),e.e164=t=>e.check(r_(Xv,t)),e.datetime=t=>e.check(lv(t)),e.date=t=>e.check(dv(t)),e.time=t=>e.check(pv(t)),e.duration=t=>e.check(hv(t))});function Mv(e){return Ig(jv,e)}var Y=B(`ZodStringFormat`,(e,t)=>{G.init(e,t),Av.init(e,t)}),Nv=B(`ZodEmail`,(e,t)=>{Dh.init(e,t),Y.init(e,t)}),Pv=B(`ZodGUID`,(e,t)=>{Th.init(e,t),Y.init(e,t)}),Fv=B(`ZodUUID`,(e,t)=>{Eh.init(e,t),Y.init(e,t)}),Iv=B(`ZodURL`,(e,t)=>{Oh.init(e,t),Y.init(e,t)}),Lv=B(`ZodEmoji`,(e,t)=>{kh.init(e,t),Y.init(e,t)}),Rv=B(`ZodNanoID`,(e,t)=>{Ah.init(e,t),Y.init(e,t)}),zv=B(`ZodCUID`,(e,t)=>{jh.init(e,t),Y.init(e,t)}),Bv=B(`ZodCUID2`,(e,t)=>{Mh.init(e,t),Y.init(e,t)}),Vv=B(`ZodULID`,(e,t)=>{Nh.init(e,t),Y.init(e,t)}),Hv=B(`ZodXID`,(e,t)=>{Ph.init(e,t),Y.init(e,t)}),Uv=B(`ZodKSUID`,(e,t)=>{Fh.init(e,t),Y.init(e,t)}),Wv=B(`ZodIPv4`,(e,t)=>{Bh.init(e,t),Y.init(e,t)}),Gv=B(`ZodIPv6`,(e,t)=>{Vh.init(e,t),Y.init(e,t)}),Kv=B(`ZodCIDRv4`,(e,t)=>{Hh.init(e,t),Y.init(e,t)}),qv=B(`ZodCIDRv6`,(e,t)=>{Uh.init(e,t),Y.init(e,t)}),Jv=B(`ZodBase64`,(e,t)=>{Gh.init(e,t),Y.init(e,t)}),Yv=B(`ZodBase64URL`,(e,t)=>{qh.init(e,t),Y.init(e,t)}),Xv=B(`ZodE164`,(e,t)=>{Jh.init(e,t),Y.init(e,t)}),Zv=B(`ZodJWT`,(e,t)=>{Xh.init(e,t),Y.init(e,t)}),Qv=B(`ZodNumber`,(e,t)=>{Zh.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>W_(e,t,n,r),e.gt=(t,n)=>e.check(h_(t,n)),e.gte=(t,n)=>e.check(g_(t,n)),e.min=(t,n)=>e.check(g_(t,n)),e.lt=(t,n)=>e.check(p_(t,n)),e.lte=(t,n)=>e.check(m_(t,n)),e.max=(t,n)=>e.check(m_(t,n)),e.int=t=>e.check(ey(t)),e.safe=t=>e.check(ey(t)),e.positive=t=>e.check(h_(0,t)),e.nonnegative=t=>e.check(g_(0,t)),e.negative=t=>e.check(p_(0,t)),e.nonpositive=t=>e.check(m_(0,t)),e.multipleOf=(t,n)=>e.check(__(t,n)),e.step=(t,n)=>e.check(__(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null}),$v=B(`ZodNumberFormat`,(e,t)=>{Qh.init(e,t),Qv.init(e,t)});function ey(e){return l_($v,e)}var ty=B(`ZodBoolean`,(e,t)=>{$h.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>G_(e,t,n,r)});function ny(e){return u_(ty,e)}var ry=B(`ZodUnknown`,(e,t)=>{eg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function iy(){return d_(ry)}var ay=B(`ZodNever`,(e,t)=>{tg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>K_(e,t,n,r)});function oy(e){return f_(ay,e)}var sy=B(`ZodArray`,(e,t)=>{rg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>X_(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(y_(t,n)),e.nonempty=t=>e.check(y_(1,t)),e.max=(t,n)=>e.check(v_(t,n)),e.length=(t,n)=>e.check(b_(t,n)),e.unwrap=()=>e.element});function cy(e,t){return N_(sy,e,t)}var ly=B(`ZodObject`,(e,t)=>{cg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Z_(e,t,n,r),V(e,`shape`,()=>t.shape),e.keyof=()=>gy(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:iy()}),e.loose=()=>e.clone({...e._zod.def,catchall:iy()}),e.strict=()=>e.clone({...e._zod.def,catchall:oy()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>em(e,t),e.safeExtend=t=>tm(e,t),e.merge=t=>nm(e,t),e.pick=t=>Qp(e,t),e.omit=t=>$p(e,t),e.partial=(...t)=>rm(yy,e,t[0]),e.required=(...t)=>im(ky,e,t[0])});function uy(e,t){return new ly({type:`object`,shape:e??{},...H(t)})}var dy=B(`ZodUnion`,(e,t)=>{ug.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Q_(e,t,n,r),e.options=t.options});function fy(e,t){return new dy({type:`union`,options:e,...H(t)})}var py=B(`ZodIntersection`,(e,t)=>{dg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$_(e,t,n,r)});function my(e,t){return new py({type:`intersection`,left:e,right:t})}var hy=B(`ZodEnum`,(e,t)=>{mg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>q_(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new hy({...t,checks:[],...H(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new hy({...t,checks:[],...H(r),entries:i})}});function gy(e,t){return new hy({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...H(t)})}var _y=B(`ZodTransform`,(e,t)=>{hg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Y_(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Op(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(um(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(um(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function vy(e){return new _y({type:`transform`,transform:e})}var yy=B(`ZodOptional`,(e,t)=>{_g.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sv(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function by(e){return new yy({type:`optional`,innerType:e})}var xy=B(`ZodExactOptional`,(e,t)=>{vg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sv(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Sy(e){return new xy({type:`optional`,innerType:e})}var Cy=B(`ZodNullable`,(e,t)=>{yg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ev(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wy(e){return new Cy({type:`nullable`,innerType:e})}var Ty=B(`ZodDefault`,(e,t)=>{bg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nv(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ey(e,t){return new Ty({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Kp(t)}})}var Dy=B(`ZodPrefault`,(e,t)=>{Sg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rv(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Oy(e,t){return new Dy({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Kp(t)}})}var ky=B(`ZodNonOptional`,(e,t)=>{Cg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tv(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ay(e,t){return new ky({type:`nonoptional`,innerType:e,...H(t)})}var jy=B(`ZodCatch`,(e,t)=>{Tg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>iv(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function My(e,t){return new jy({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Ny=B(`ZodPipe`,(e,t)=>{Eg.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>av(e,t,n,r),e.in=t.in,e.out=t.out});function Py(e,t){return new Ny({type:`pipe`,in:e,out:t})}var Fy=B(`ZodReadonly`,(e,t)=>{Og.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ov(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Iy(e){return new Fy({type:`readonly`,innerType:e})}var Ly=B(`ZodCustom`,(e,t)=>{Ag.init(e,t),J.init(e,t),e._zod.processJSONSchema=(t,n,r)=>J_(e,t,n,r)});function Ry(e,t={}){return P_(Ly,e,t)}function zy(e){return F_(e)}var By=function(e){return e[e.invalid=0]=`invalid`,e[e.u8=1]=`u8`,e[e.u16=2]=`u16`,e[e.u32=3]=`u32`,e[e.u64=4]=`u64`,e[e.i8=5]=`i8`,e[e.i16=6]=`i16`,e[e.i32=7]=`i32`,e[e.i64=8]=`i64`,e[e.f32=9]=`f32`,e[e.f64=10]=`f64`,e[e.string=11]=`string`,e[e.chan=14]=`chan`,e[e.series=15]=`series`,e[e.variable=16]=`variable`,e[e.numeric_constant=17]=`numeric_constant`,e[e.integer_constant=18]=`integer_constant`,e[e.float_constant=19]=`float_constant`,e[e.exact_integer_float_constant=20]=`exact_integer_float_constant`,e[e.function=21]=`function`,e[e.sequence=22]=`sequence`,e[e.stage=23]=`stage`,e}({}),Vy=l.z.enum(By),Hy=function(e){return e[e.none=0]=`none`,e[e.read=1]=`read`,e[e.write=2]=`write`,e}({}),Uy=l.z.enum(Hy),Wy=l.z.object({read:l.z.record(l.z.uint32(),l.z.string()),write:l.z.record(l.z.uint32(),l.z.string())}),Gy=l.z.object({length:D.int8,mass:D.int8,time:D.int8,current:D.int8,temperature:D.int8,angle:D.int8,count:D.int8,data:D.int8}),Ky=l.z.object({dimensions:Gy,scale:l.z.number(),name:l.z.string()}),qy=l.z.object({get inputs(){return Yy.optional()},get outputs(){return Yy.optional()},get config(){return Yy.optional()}}).extend({kind:Vy,name:l.z.string(),get elem(){return qy.optional()},unit:Ky.optional(),get constraint(){return qy.optional()},chanDirection:Uy.optional()}),Jy=l.z.object({name:l.z.string(),type:qy,value:l.z.unknown().optional()}),Yy=w.nullishToEmpty(Jy),Xy=o({EdgeKind:()=>Zy,authoritiesZ:()=>nb,bodyZ:()=>eb,edgeKindZ:()=>Qy,edgeZ:()=>ib,edgesZ:()=>cb,functionZ:()=>ab,functionsZ:()=>lb,handleZ:()=>$y,irZ:()=>mb,nodeZ:()=>tb,nodesZ:()=>ob,sequenceZ:()=>db,sequencesZ:()=>pb,stageZ:()=>ub,stagesZ:()=>fb,strataZ:()=>sb,stratumZ:()=>rb}),Zy=function(e){return e[e.unspecified=0]=`unspecified`,e[e.continuous=1]=`continuous`,e[e.conditional=2]=`conditional`,e}({}),Qy=l.z.enum(Zy),$y=l.z.object({node:l.z.string(),param:l.z.string()}),eb=l.z.object({raw:l.z.string()}),tb=l.z.object({key:l.z.string(),type:l.z.string(),config:Yy.optional(),inputs:Yy.optional(),outputs:Yy.optional(),channels:Wy.optional()}),nb=l.z.object({default:D.uint8.optional(),channels:l.z.record(l.z.uint32(),D.uint8).optional()}),rb=w.nullishToEmpty(l.z.string()),ib=l.z.object({source:$y,target:$y,kind:Qy.optional()}),ab=l.z.object({key:l.z.string(),body:eb.optional(),config:Yy.optional(),inputs:Yy.optional(),outputs:Yy.optional(),channels:Wy.optional()}),ob=w.nullishToEmpty(tb),sb=w.nullishToEmpty(rb),cb=w.nullishToEmpty(ib),lb=w.nullishToEmpty(ab),ub=l.z.object({key:l.z.string(),nodes:w.nullishToEmpty(l.z.string()),strata:sb}),db=l.z.object({key:l.z.string(),stages:w.nullishToEmpty(ub)}),fb=w.nullishToEmpty(ub),pb=w.nullishToEmpty(db),mb=l.z.object({functions:lb.optional(),nodes:ob.optional(),edges:cb.optional(),strata:sb.optional(),sequences:pb.optional(),authorities:nb.optional()}),hb=o({graphZ:()=>yb,nodeZ:()=>gb,nodesZ:()=>vb,viewportZ:()=>_b}),gb=l.z.object({key:l.z.string(),type:l.z.string(),config:I.nullishToEmpty(),position:ac.xyZ}),_b=l.z.object({position:ac.xyZ,zoom:l.z.number()}),vb=w.nullishToEmpty(gb),yb=l.z.object({viewport:_b,functions:lb,edges:cb,nodes:vb}),bb=o({outputZ:()=>xb}),xb=l.z.object({wasm:l.z.instanceof(Uint8Array),outputMemoryBases:l.z.record(l.z.string(),l.z.uint32())}),Sb=mb.extend(xb.shape),Cb=o({textZ:()=>wb}),wb=l.z.object({raw:l.z.string()}),Tb=[`text`,`graph`],Eb=l.z.enum(Tb),Db=l.z.object({running:l.z.boolean()}),Ob=l.z.uuid(),kb=md.statusZ({details:Db}),Ab=l.z.object({key:Ob.optional(),name:l.z.string(),mode:Eb,graph:yb,text:wb}),jb=l.z.object({key:Ob,name:l.z.string(),mode:Eb,graph:yb,text:wb,program:Sb.optional(),status:kb.optional()}),Mb=z(`arc`),Nb=Mb(``),Pb=(e,t,{convertNumericStrings:n=!0}={})=>{let r=!Array.isArray(e),i=w.toArray(e),a=i[0],o=typeof a,s;return o===`string`&&n&&!isNaN(parseInt(a,10))&&`number`in t?(s=t.number,i=i.map(e=>parseInt(e,10))):s=t[o],{single:r,variant:s,normalized:i,actual:e}},X=(e,t,n,r)=>{if(r){if(n.length===0)throw new Md(`${e} not found matching ${JSON.stringify(t)}`);if(n.length>1)throw new Nd(`Expected one ${e} matching ${JSON.stringify(t)}, but found ${n.length}`)}},Fb=`sy_arc_set`,Ib=`sy_arc_delete`,Lb=uy({keys:Ob.array().optional(),names:Mv().array().optional(),searchTerm:Mv().optional(),limit:ey().optional(),offset:ey().optional(),includeStatus:ny().optional()}),Rb=uy({arcs:Ab.array()}),zb=uy({keys:Ob.array()}),Bb=uy({arcs:w.nullishToEmpty(jb)}),Vb=uy({arcs:jb.array()}),Hb=uy({}),Ub=uy({content:Mv()}),Wb=fy([uy({key:Ob,includeStatus:ny().optional()}).transform(({key:e,includeStatus:t})=>({keys:[e],includeStatus:t})),uy({name:Mv(),includeStatus:ny().optional()}).transform(({name:e,includeStatus:t})=>({names:[e],includeStatus:t}))]),Gb=fy([Wb,Lb]),Kb=class{client;streamClient;constructor(e,t){this.client=e,this.streamClient=t}async create(e){let t=Array.isArray(e),n=await S(this.client,`/arc/create`,{arcs:w.toArray(e)},Rb,Vb);return t?n.arcs:n.arcs[0]}async retrieve(e){let t=`key`in e||`name`in e,n=await S(this.client,`/arc/retrieve`,e,Gb,Bb);return X(`Arc`,e,n.arcs,t),t?n.arcs[0]:n.arcs}async delete(e){await S(this.client,`/arc/delete`,{keys:w.toArray(e)},zb,Hb)}async openLSP(){return await this.streamClient.stream(`/arc/lsp`,Ub,Ub)}},qb=o({moduleZ:()=>Jb}),Jb=mb.extend(xb.shape),Yb=o({Client:()=>Kb,DELETE_CHANNEL_NAME:()=>Ib,MODES:()=>Tb,SET_CHANNEL_NAME:()=>Fb,TYPE_ONTOLOGY_ID:()=>Nb,arcZ:()=>jb,compiler:()=>bb,graph:()=>hb,ir:()=>Xy,keyZ:()=>Ob,lspMessageZ:()=>Ub,modeZ:()=>Eb,module:()=>qb,newZ:()=>Ab,ontologyID:()=>Mb,singleRetrieveArgsZ:()=>Wb,statusDetailsZ:()=>Db,statusZ:()=>kb,text:()=>Cb}),Xb=Error(`request for lock canceled`),Zb=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Qb=class{constructor(e,t=Xb){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=ex(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return Zb(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),$b(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw 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){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function $b(e,t){let n=ex(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function ex(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var tx=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},nx=class{constructor(e){this._semaphore=new Qb(1,e)}acquire(){return tx(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}},rx=D.uint12,Z=l.z.uint32().or(l.z.string().refine(e=>!isNaN(Number(e))).transform(Number)),ix=D.uint20,ax=[`min`,`max`,`avg`,`none`,`derivative`],ox=l.z.enum(ax),sx=l.z.object({type:ox,resetChannel:Z.default(0),duration:Jc.timeSpanZ.default(k.ZERO)}),cx=l.z.string().min(1,`Name is required`),lx=md.statusZ(),ux=l.z.object({key:Z,name:cx,leaseholder:rx,dataType:Jc.dataTypeZ,isIndex:l.z.boolean(),index:Z,alias:l.z.string().optional(),virtual:l.z.boolean().default(!1),internal:l.z.boolean().default(!1),expression:l.z.string().default(``),operations:D.nullToUndefined(sx.array()),concurrency:F.concurrencyZ.default(F.Concurrency.exclusive).optional(),status:lx.optional()}),dx=ux.omit({leaseholder:!0}).partial({key:!0,index:!0,isIndex:!0,internal:!0,virtual:!0,expression:!0}).extend({leaseholder:D.uint12.optional()}),fx=z(`channel`),px=fx(0),Q=l.z.uuid(),mx=l.z.object({key:Q,name:l.z.string().min(1),timeRange:Jc.timeRangeZ,color:Ql.colorZ.optional()}),hx=mx.extend({labels:D.nullToUndefined(mu.labelZ.array()),get parent(){return hx.optional()}}),gx=mx.omit({timeRange:!0}).extend({labels:D.nullToUndefined(mu.labelZ.array()),get parent(){return gx.optional()},timeRange:Jc.timeRangeBoundedZ}),_x=gx.omit({parent:!0,labels:!0}).partial({key:!0}),vx=z(`range`),yx=vx(``),bx=l.z.object({nodeKey:D.uint12.optional(),keys:Z.array().optional(),names:l.z.string().array().optional(),searchTerm:l.z.string().optional(),rangeKey:Q.optional(),limit:l.z.int().optional(),offset:l.z.int().optional(),dataTypes:M.z.array().optional(),notDataTypes:M.z.array().optional(),virtual:l.z.boolean().optional(),isIndex:l.z.boolean().optional(),internal:l.z.boolean().optional(),legacyCalculated:l.z.boolean().optional()}),xx=l.z.object({channels:w.nullishToEmpty(ux)}),Sx=e=>(Array.isArray(e)&&e.length>0&&typeof e[0]==`object`?e=e.map(e=>e.key):typeof e==`object`&&`key`in e&&(e=[e.key]),Pb(e,{number:`keys`,string:`names`})),Cx=class{client;constructor(e){this.client=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e==`object`)return await this.execute(e);let n=Sx(e),{variant:r}=n,{normalized:i}=n;return r===`keys`&&i.indexOf(0)!==-1&&(i=i.filter(e=>e!==0)),i.length===0?[]:await this.execute({[r]:i,...t})}async execute(e){return(await S(this.client,`/channel/retrieve`,e,bx,xx)).channels}},wx=class{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e==`object`)return await this.wrapped.retrieve(e);let{normalized:n}=Sx(e),r=[],i=[];if(n.forEach(e=>{let t=this.get(e);t==null?i.push(e):r.push(...t)}),i.length===0)return r;let a=await this.wrapped.retrieve(i,t);return this.set(a),r.concat(a)}delete(e){let{variant:t,normalized:n}=Sx(e);t===`names`?n.forEach(e=>{let t=this.namesToKeys.get(e);t!=null&&(t.forEach(e=>this.cache.delete(e)),this.namesToKeys.delete(e))}):n.forEach(e=>{let t=this.cache.get(e);t!=null&&(this.cache.delete(e),this.namesToKeys.delete(t.name))})}rename(e,t){e.forEach((e,n)=>{let r=t[n],i=this.cache.get(e);if(i==null)return;this.cache.delete(e);let a=this.namesToKeys.get(i.name);a!=null&&(a.delete(e),a.size===0&&this.namesToKeys.delete(i.name)),i.name=r,this.cache.set(e,i);let o=this.namesToKeys.get(r);o==null?this.namesToKeys.set(r,new Set([e])):o.add(e)})}set(e){e.forEach(e=>{this.cache.set(e.key,e);let t=this.namesToKeys.get(e.name);t==null?this.namesToKeys.set(e.name,new Set([e.key])):t.add(e.key)})}get(e){if(typeof e==`number`){let t=this.cache.get(e);return t==null?void 0:[t]}let t=this.namesToKeys.get(e);if(t==null)return;let n=[];if(t.forEach(e=>{let t=this.cache.get(e);t!=null&&n.push(t)}),n.length!==0)return n}},Tx=class{mu=new nx;requests=new Map;wrapped;debouncedRun;constructor(e,t){this.wrapped=e,this.debouncedRun=pu(()=>{this.run()},t)}async retrieve(e){if(!Array.isArray(e)&&typeof e==`object`)return await this.wrapped.retrieve(e);let{normalized:t,variant:n}=Sx(e);return n===`names`?await this.wrapped.retrieve(t):await new Promise((e,n)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:e,reject:n}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{let e=new Set;this.requests.forEach((t,n)=>n.forEach(t=>e.add(t)));try{let t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((e,n)=>e.resolve(t.filter(e=>n.includes(e.key))))}catch(e){this.requests.forEach(t=>t.reject(e))}finally{this.requests.clear()}})}},Ex=async(e,t)=>{let{normalized:n}=Sx(t),r=await e.retrieve(n),i=[];if(n.forEach(e=>{r.find(t=>t.name===e||t.key===e)??i.push(e)}),i.length>0)throw new jd(`Could not find channels: ${JSON.stringify(i)}`);return r},Dx=l.z.uuid(),Ox=l.z.object({key:Dx,name:l.z.string()}),kx=z(`group`),Ax=kx(``),jx=`sy_group_set`,Mx=`sy_group_delete`,Nx=l.default.object({group:Ox}),Px=l.default.object({parent:R,key:Dx.optional(),name:l.default.string()}),Fx=l.default.object({key:Dx,name:l.default.string()}),Ix=l.default.object({keys:l.default.array(Dx)}),Lx=class{client;constructor(e){this.client=e}async create(e){return(await S(this.client,`/ontology/create-group`,e,Px,Nx)).group}async rename(e,t){await S(this.client,`/ontology/rename-group`,{key:e,name:t},Fx,l.default.object({}))}async delete(e){await S(this.client,`/ontology/delete-group`,{keys:w.toArray(e)},Ix,l.default.object({}))}},Rx=o({Client:()=>Lx,DELETE_CHANNEL_NAME:()=>Mx,SET_CHANNEL_NAME:()=>jx,TYPE_ONTOLOGY_ID:()=>Ax,groupZ:()=>Ox,keyZ:()=>Dx,ontologyID:()=>kx}),zx=`sy_channel_set`,Bx=`sy_channel_delete`,Vx=class{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;operations;status;constructor({dataType:e,name:t,leaseholder:n=0,key:r=0,isIndex:i=!1,index:a=0,internal:o=!1,virtual:s=!1,frameClient:c,alias:l,status:u,expression:d=``,operations:f=[]}){this.key=Z.parse(r),this.name=t,this.dataType=new M(e),this.leaseholder=n,this.index=Z.parse(a),this.isIndex=i,this.internal=o,this.alias=l,this.virtual=s,this.expression=d,this.operations=f,u!=null&&(this.status=md.create(u)),this._frameClient=c??null}get framer(){if(this._frameClient==null)throw new L(`cannot read from a channel that has not been created`);return this._frameClient}get payload(){return ux.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,expression:this.expression,status:this.status,operations:this.operations})}get isCalculated(){return Gx(this.payload)}get ontologyID(){return fx(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}},Hx=l.z.object({}),Ux=l.z.object({group:Ox}),Wx=class{frameClient;client;retriever;writer;constructor(e,t,n,r){this.frameClient=e,this.retriever=t,this.client=n,this.writer=r}async create(e,t={}){let{retrieveIfNameExists:n=!1}=t,r=!Array.isArray(e),i=w.toArray(e),a=[];if(n){let e=await this.retriever.retrieve(i.map(e=>e.name)),t=new Set(e.map(e=>e.name));i=i.filter(e=>!t.has(e.name)),a=this.sugar(e)}return a=a.concat(this.sugar(await this.writer.create(i))),r?a[0]:a}async retrieve(e,t){if(typeof e==`object`&&!Array.isArray(e))return this.sugar(await this.retriever.retrieve(e));let n=!Array.isArray(e),r=this.sugar(await this.retriever.retrieve(e,t));return X(`channel`,e,r,n),n?r[0]:r}async delete(e){let{normalized:t,variant:n}=Sx(e);return n===`keys`?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(w.toArray(e),w.toArray(t))}createDebouncedBatchRetriever(e=10){return new wx(new Tx(new Cx(this.client),e))}sugar(e){let{frameClient:t}=this;return Array.isArray(e)?e.map(e=>new Vx({...e,frameClient:t})):new Vx({...e,frameClient:t})}async retrieveGroup(){return(await S(this.client,`/channel/retrieve-group`,{},Hx,Ux)).group}},Gx=({virtual:e,expression:t})=>e&&t!==``,Kx=l.z.union([D.toArray(Z),D.toArray(cx),D.toArray(ux).transform(e=>e.map(e=>e.key))]),qx=/[a-zA-Z0-9_]/,Jx=/^[a-zA-Z_][a-zA-Z0-9_]*$/,Yx=(e,t=!1)=>{if(e===``)return t?`_`:``;if(e.match(Jx))return e;let n=``;for(let t of e)t.match(qx)?n+=t:n+=`_`;return n[0].match(/^\d/)&&(n=`_${n}`),n},Xx=e=>Wd(fx(e)),Zx=l.z.object({channels:dx.array()}),Qx=l.z.object({channels:ux.array()}),$x=l.z.object({keys:Z.array().optional(),names:cx.array().optional()}),eS=l.z.object({}),tS=l.z.object({keys:Z.array(),names:cx.array()}),nS=l.z.object({}),rS=class{client;cache;constructor(e,t){this.client=e,this.cache=t}async create(e){let{channels:t}=await S(this.client,`/channel/create`,{channels:e.map(e=>({...e,dataType:e.dataType}))},Zx,Qx);return this.cache.set(t),t}async delete(e){let t=Z.array().parse(e.keys??[]);await S(this.client,`/channel/delete`,e,$x,eS),t.length>0&&this.cache.delete(t),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await S(this.client,`/channel/rename`,{keys:e,names:t},tS,nS),this.cache.rename(e,t)}},iS=o({CacheRetriever:()=>wx,Channel:()=>Vx,Client:()=>Wx,ClusterRetriever:()=>Cx,DELETE_CHANNEL_NAME:()=>Bx,DebouncedBatchRetriever:()=>Tx,OPERATION_TYPES:()=>ax,SET_CHANNEL_NAME:()=>zx,TYPE_ONTOLOGY_ID:()=>px,Writer:()=>rS,analyzeParams:()=>Sx,escapeInvalidName:()=>Yx,isCalculated:()=>Gx,keyZ:()=>Z,localKeyZ:()=>ix,nameZ:()=>cx,newZ:()=>dx,ontologyID:()=>fx,operationTypeZ:()=>ox,operationZ:()=>sx,paramsZ:()=>Kx,payloadZ:()=>ux,retrieveRequired:()=>Ex,statusKey:()=>Xx,statusZ:()=>lx}),aS=l.z.object({username:l.z.string(),password:l.z.string()}),oS=l.z.object({token:l.z.string(),user:Rf}),sS=`/auth/login`,cS=3,lS=l.z.object({username:l.z.string(),password:l.z.string(),newPassword:l.z.string().min(1)}),uS=l.z.object({}),dS=[Od,kd],fS=class{client;credentials;authState={authenticated:!1};authenticating;retryCount;constructor(e,t){this.client=e,this.credentials=t,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;let{authState:e}=this;if(!e.authenticated)throw Error(`Authentication failed: user not available`);return e.user}async changePassword(e){if(!this.authenticated)throw Error(`Not authenticated`);await S(this.client,`/auth/change-password`,{username:this.credentials.username,password:this.credentials.password,newPassword:e},lS,uS),this.credentials.password=e}middleware(){let e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(sS)){this.authenticating??=new Promise((e,t)=>{this.client.send(sS,this.credentials,aS,oS).then(([t,n])=>{if(n!=null)return e(n);if(t==null)return e(Error(`No response from login`));this.authState={authenticated:!0,user:t.user,token:t.token},e(null)}).catch(t)});let e=await this.authenticating;if(e!=null)return[t,e]}t.params.Authorization=`Bearer ${this.token}`;let[r,i]=await n(t);return dS.some(e=>e.matches(i))&&this.retryCount<cS?(this.authState={authenticated:!1},this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[r,i])};return e}},pS=o({Checker:()=>bS,stateZ:()=>hS,statusZ:()=>mS}),mS=l.z.enum([`disconnected`,`connecting`,`connected`,`failed`]),hS=l.z.object({status:mS,error:l.z.instanceof(Error).optional(),message:l.z.string().optional(),clusterKey:l.z.string(),clientVersion:l.z.string(),clientServerCompatible:l.z.boolean(),nodeVersion:l.z.string().optional()}),gS=l.z.object({clusterKey:l.z.string(),nodeVersion:l.z.string().optional()}),_S=l.z.void(),vS={clusterKey:``,status:`disconnected`,error:void 0,message:`Disconnected`,clientServerCompatible:!1,clientVersion:`0.54.2`},yS=(e,t,n)=>{let r=n?`Core`:`client`;return`Synnax Core version ${e==null?``:`${e} `}is too ${n?`old`:`new`} for client version ${t}.
60
77
  This may cause compatibility issues. We recommend updating the ${r}. For more information, see
61
- https://docs.synnaxlabs.com/reference/client/resources/troubleshooting#old-${r}-version`},mx=class{static DEFAULT=fx;_state;pollFrequency=O.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=lx;versionWarned=!1;constructor(e,t=O.seconds(30),n,r){this._state={...fx},this.client=e,this.pollFrequency=t,this.clientVersion=n,this.name=r,this.check(),this.start()}stop(){this.interval!=null&&clearInterval(this.interval)}async check(){let e=this._state.status;try{let e=await S(this.client,`/connectivity/check`,void 0,dx,ux),t=e.nodeVersion,n=this.clientVersion,r=this.versionWarned;t==null?(this._state.clientServerCompatible=!1,r||(console.warn(px(null,n,!0)),this.versionWarned=!0)):gl.versionsEqual(n,t,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,r||(console.warn(px(t,n,gl.semVerNewer(n,t))),this.versionWarned=!0)),this._state.status=`connected`,this._state.message=`Connected to ${this.name??`cluster`}`,this._state.clusterKey=e.clusterKey,this._state.nodeVersion=e.nodeVersion,this._state.clientVersion=this.clientVersion}catch(e){this._state.status=`failed`,this._state.error=e,this._state.message=this.state.error?.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(e=>e(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}start(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}},hx=l.z.object({keys:Z.array().optional(),bounds:A.z,names:nb.array().optional()}),gx=l.z.object({}),_x=class{client;constructor(e){this.client=e}async delete(e){await S(this.client,`/frame/delete`,e,hx,gx)}},vx=e=>{let t=w.toArray(e);return t.length===0?null:typeof t[0]==`number`||!isNaN(parseInt(t[0],10))?`key`:`name`},yx=(e,t)=>{let n=w.toArray(e);if(n.length===t.length)return;let r=vx(e);throw r===null?new L(`[Frame] - channel keys or names must be provided when constructing a frame.`):new L(`[Frame] - ${r}s and series must be the same length.
62
- Got ${n.length} ${r}s and ${t.length} series.`)},$=class e{columns=[];series=[];constructor(t=[],n=[]){if(t instanceof e){this.columns=t.columns,this.series=t.series;return}if(t instanceof Map){t.forEach((e,t)=>this.push(t,...w.toArray(e)));return}if(typeof t==`object`&&!Array.isArray(t)){if(`keys`in t&&`series`in t){let e=t;e.series??=[],e.keys??=[];let n=e.series.map(e=>xx(e));yx(e.keys,n),e.keys.forEach((e,t)=>this.push(e,n[t]))}else Object.entries(t).forEach(([e,t])=>{let n=parseInt(e,10);if(!isNaN(n))return this.push(n,...w.toArray(t));this.push(e,...w.toArray(t))});return}if(Array.isArray(t)||[`string`,`number`].includes(typeof t)){let e=w.toArray(n),r=w.toArray(t);yx(r,e),e.forEach((e,t)=>this.push(r[t],e));return}throw new L(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
78
+ https://docs.synnaxlabs.com/reference/client/resources/troubleshooting#old-${r}-version`},bS=class{static DEFAULT=vS;_state;pollFrequency=k.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=hS;versionWarned=!1;constructor(e,t=k.seconds(30),n,r){this._state={...vS},this.client=e,this.pollFrequency=t,this.clientVersion=n,this.name=r,this.check(),this.start()}stop(){this.interval!=null&&clearInterval(this.interval)}async check(){let e=this._state.status;try{let e=await S(this.client,`/connectivity/check`,void 0,_S,gS),t=e.nodeVersion,n=this.clientVersion,r=this.versionWarned;t==null?(this._state.clientServerCompatible=!1,r||(console.warn(yS(null,n,!0)),this.versionWarned=!0)):vu.versionsEqual(n,t,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,r||(console.warn(yS(t,n,vu.semVerNewer(n,t))),this.versionWarned=!0)),this._state.status=`connected`,this._state.message=`Connected to ${this.name??`cluster`}`,this._state.clusterKey=e.clusterKey,this._state.nodeVersion=e.nodeVersion,this._state.clientVersion=this.clientVersion}catch(e){this._state.status=`failed`,this._state.error=e,this._state.message=this.state.error?.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(e=>e(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}start(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}},xS=l.z.object({keys:Z.array().optional(),bounds:j.z,names:cx.array().optional()}),SS=l.z.object({}),CS=class{client;constructor(e){this.client=e}async delete(e){await S(this.client,`/frame/delete`,e,xS,SS)}},wS=e=>{let t=w.toArray(e);return t.length===0?null:typeof t[0]==`number`||!isNaN(parseInt(t[0],10))?`key`:`name`},TS=(e,t)=>{let n=w.toArray(e);if(n.length===t.length)return;let r=wS(e);throw r===null?new L(`[Frame] - channel keys or names must be provided when constructing a frame.`):new L(`[Frame] - ${r}s and series must be the same length.
79
+ Got ${n.length} ${r}s and ${t.length} series.`)},$=class e{columns=[];series=[];constructor(t=[],n=[]){if(t instanceof e){this.columns=t.columns,this.series=t.series;return}if(t instanceof Map){t.forEach((e,t)=>this.push(t,...w.toArray(e)));return}if(typeof t==`object`&&!Array.isArray(t)){if(`keys`in t&&`series`in t){let e=t;e.series??=[],e.keys??=[];let n=e.series.map(e=>DS(e));TS(e.keys,n),e.keys.forEach((e,t)=>this.push(e,n[t]))}else Object.entries(t).forEach(([e,t])=>{let n=parseInt(e,10);if(!isNaN(n))return this.push(n,...w.toArray(t));this.push(e,...w.toArray(t))});return}if(Array.isArray(t)||[`string`,`number`].includes(typeof t)){let e=w.toArray(n),r=w.toArray(t);TS(r,e),e.forEach((e,t)=>this.push(r[t],e));return}throw new L(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
63
80
  payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
64
- 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 wu(`colType is not key`);return this.columns??[]}get uniqueKeys(){return vi.unique(this.keys)}get names(){if(this.colType===`key`)throw new wu(`colType is not name`);return this.columns??[]}get uniqueNames(){return vi.unique(this.names)}get uniqueColumns(){return this.colType===`key`?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Sx(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;let e=this.timeRanges;return e.every(t=>t.equals(e[0]))}timeRange(e){if(e==null)return this.columns.length===0?A.ZERO:new A(D.min(...this.series.map(e=>e.timeRange.start)),D.max(...this.series.map(e=>e.timeRange.end)));let t=this.get(e);return t==null?A.ZERO:t.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):new os(this.series.filter((t,n)=>this.columns[n]===e))}push(t,...n){if(t instanceof e){if(t.colType!=null&&this.colType!==null&&t.colType!==this.colType)throw new L(`keyVariant must match`);this.series.push(...t.series),this.columns.push(...t.columns)}else{if(this.series.push(...n),typeof t==`string`&&this.colType===`key`||typeof t!=`string`&&this.colType===`name`)throw new L(`keyVariant must match`);this.columns.push(...Array.from({length:n.length},()=>t))}}concat(t){return new e([...this.columns,...t.columns],[...this.series,...t.series])}has(e){return typeof e==`string`&&this.colType===`key`||typeof e==`number`&&this.colType===`name`?!1:this.columns.includes(e)}map(t){let n=new e;return this.forEach((e,r,i)=>n.push(...t(e,r,i))),n}mapFilter(t){let n=new e;return this.forEach((e,r,i)=>{let[a,o,s]=t(e,r,i);s&&n.push(a,o)}),n}forEach(e){this.columns.forEach((t,n)=>{let r=this.series[n];e(t,r,n)})}forEachUnique(e){this.uniqueColumns.forEach((t,n)=>e(t,this.get(t),n))}at(e,t=!1){let n={};return this.uniqueColumns.forEach(r=>{n[r]=this.get(r).at(e,t)}),n}filter(t){let n=new e;return this.columns.forEach((e,r)=>{let i=this.series[r];t(e,i,r)&&n.push(e,i)}),n}get byteLength(){return new Oo(this.series.reduce((e,t)=>e.add(t.byteLength),Oo.ZERO))}get digest(){let e={};return this.keys.forEach((t,n)=>{let r=this.series[n].digest;t in e?e[t].push(r):e[t]=[r]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}toString(){let e=`Frame{
65
- `;return this.uniqueColumns.forEach(t=>{e+=` ${t}: ${this.get(t).series.map(e=>e.toString()).join(`,`)}\n`}),e+=`}`,e}},bx=l.z.object({keys:l.z.union([l.z.null().transform(()=>[]),l.z.number().array().default([])]),series:l.z.union([l.z.null().transform(()=>[]),Qo.crudeZ.array().default([])])}),xx=e=>{let{dataType:t,data:n,timeRange:r,alignment:i}=e;return new Qo({data:n,dataType:t,timeRange:r,glBufferUsage:`static`,alignment:i})},Sx=e=>({timeRange:e.timeRange,dataType:e.dataType,data:new Uint8Array(e.data.buffer),alignment:e.alignment}),Cx=function(e){return e[e.Open=0]=`Open`,e[e.Write=1]=`Write`,e[e.Commit=2]=`Commit`,e[e.SetAuthority=3]=`SetAuthority`,e}({}),wx=l.z.enum(Cx),Tx=e=>e.data.byteLength/e.dataType.density.valueOf(),Ex=e=>{let{keys:t,series:n}=e;t.forEach((e,t)=>{n[t].key=e}),n.sort((e,t)=>e.key-t.key),t.sort((e,t)=>e-t),n.forEach(e=>delete e.key)},Dx=5,Ox=4,kx=3,Ax=2,jx=1,Mx=0,Nx=j.TIMESTAMP.density.valueOf(),Px=8,Fx=4,Ix=4,Lx=4,Rx=1,zx=class{contentType=`application/sy-framer`;states=new Map;currState;seqNum=0;constructor(e=[],t=[]){(e.length>0||t.length>0)&&this.update(e,t)}update(e,t){this.seqNum++;let n={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((e,r)=>{let i=t[r];n.keyDataTypes.set(e,i),i.isVariable&&(n.hasVariableDataTypes=!0)}),n.keys.sort(),this.states.set(this.seqNum,n),this.currState=n}throwIfNotUpdated(e){if(this.seqNum<1)throw new L(`
81
+ 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 Ad(`colType is not key`);return this.columns??[]}get uniqueKeys(){return Yo.unique(this.keys)}get names(){if(this.colType===`key`)throw new Ad(`colType is not name`);return this.columns??[]}get uniqueNames(){return Yo.unique(this.names)}get uniqueColumns(){return this.colType===`key`?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>OS(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;let e=this.timeRanges;return e.every(t=>t.equals(e[0]))}timeRange(e){if(e==null)return this.columns.length===0?j.ZERO:new j(O.min(...this.series.map(e=>e.timeRange.start)),O.max(...this.series.map(e=>e.timeRange.end)));let t=this.get(e);return t==null?j.ZERO:t.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):new Wc(this.series.filter((t,n)=>this.columns[n]===e))}push(t,...n){if(t instanceof e){if(t.colType!=null&&this.colType!==null&&t.colType!==this.colType)throw new L(`keyVariant must match`);this.series.push(...t.series),this.columns.push(...t.columns)}else{if(this.series.push(...n),typeof t==`string`&&this.colType===`key`||typeof t!=`string`&&this.colType===`name`)throw new L(`keyVariant must match`);this.columns.push(...Array.from({length:n.length},()=>t))}}concat(t){return new e([...this.columns,...t.columns],[...this.series,...t.series])}has(e){return typeof e==`string`&&this.colType===`key`||typeof e==`number`&&this.colType===`name`?!1:this.columns.includes(e)}map(t){let n=new e;return this.forEach((e,r,i)=>n.push(...t(e,r,i))),n}mapFilter(t){let n=new e;return this.forEach((e,r,i)=>{let[a,o,s]=t(e,r,i);s&&n.push(a,o)}),n}forEach(e){this.columns.forEach((t,n)=>{let r=this.series[n];e(t,r,n)})}forEachUnique(e){this.uniqueColumns.forEach((t,n)=>e(t,this.get(t),n))}at(e,t=!1){let n={};return this.uniqueColumns.forEach(r=>{n[r]=this.get(r).at(e,t)}),n}filter(t){let n=new e;return this.columns.forEach((e,r)=>{let i=this.series[r];t(e,i,r)&&n.push(e,i)}),n}get byteLength(){return new fc(this.series.reduce((e,t)=>e.add(t.byteLength),fc.ZERO))}get digest(){let e={};return this.keys.forEach((t,n)=>{let r=this.series[n].digest;t in e?e[t].push(r):e[t]=[r]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}toString(){let e=`Frame{
82
+ `;return this.uniqueColumns.forEach(t=>{e+=` ${t}: ${this.get(t).series.map(e=>e.toString()).join(`,`)}\n`}),e+=`}`,e}},ES=l.z.object({keys:l.z.union([l.z.null().transform(()=>[]),l.z.number().array().default([])]),series:l.z.union([l.z.null().transform(()=>[]),Ic.crudeZ.array().default([])])}),DS=e=>{let{dataType:t,data:n,timeRange:r,alignment:i}=e;return new Ic({data:n,dataType:t,timeRange:r,glBufferUsage:`static`,alignment:i})},OS=e=>({timeRange:e.timeRange,dataType:e.dataType,data:new Uint8Array(e.data.buffer),alignment:e.alignment}),kS=function(e){return e[e.Open=0]=`Open`,e[e.Write=1]=`Write`,e[e.Commit=2]=`Commit`,e[e.SetAuthority=3]=`SetAuthority`,e}({}),AS=l.z.enum(kS),jS=e=>e.data.byteLength/e.dataType.density.valueOf(),MS=e=>{let{keys:t,series:n}=e;t.forEach((e,t)=>{n[t].key=e}),n.sort((e,t)=>e.key-t.key),t.sort((e,t)=>e-t),n.forEach(e=>delete e.key)},NS=5,PS=4,FS=3,IS=2,LS=1,RS=0,zS=M.TIMESTAMP.density.valueOf(),BS=8,VS=4,HS=4,US=4,WS=1,GS=class{contentType=`application/sy-framer`;states=new Map;currState;seqNum=0;constructor(e=[],t=[]){(e.length>0||t.length>0)&&this.update(e,t)}update(e,t){this.seqNum++;let n={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((e,r)=>{let i=t[r];n.keyDataTypes.set(e,i),i.isVariable&&(n.hasVariableDataTypes=!0)}),n.keys.sort(),this.states.set(this.seqNum,n),this.currState=n}throwIfNotUpdated(e){if(this.seqNum<1)throw new L(`
66
83
  The codec has not been updated with a list of channels and data types.
67
84
  Please call the update method before calling ${e}.
68
- `)}encode(e,t=0){this.throwIfNotUpdated(`encode`);let n=e;typeof e==`object`&&e&&`toPayload`in e&&(n=e.toPayload()),Ex(n);let r=-1,i,a,o,s=t+Rx+Lx,c=!this.currState?.hasVariableDataTypes,l=!0,u=!0,d=!0,f=!0,p=!0;n.keys.length!==this.currState?.keys.length&&(d=!1,s+=n.keys.length*Ix),n.series.forEach((e,t)=>{let u=Tx(e),d=n.keys[t],p=this.currState?.keyDataTypes.get(d);if(p==null)throw new L(`Channel ${d} was not provided in the list of channels when opening the writer`);if(!p.equals(e.dataType))throw new L(`Series data type of ${e.dataType.toString()} does not match the data type of ${p.toString()} for channel ${d}`);if(s+=e.data.byteLength,r===-1){r=u,i=e.timeRange?.start,a=e.timeRange?.end,o=BigInt(e.alignment??0n);return}r!==u&&(c=!1),(i?.valueOf()!==e.timeRange?.start.valueOf()||a?.valueOf()!==e.timeRange?.end.valueOf())&&(l=!1),o!==BigInt(e.alignment??0)&&(f=!1)}),u=l&&i==null&&a==null,p=f&&(o===void 0||o===0n),c?s+=Fx:s+=n.keys.length*Fx,u||(l?s+=Nx*2:s+=n.keys.length*Nx*2),p||(f?s+=Px:s+=n.keys.length*Px);let m=new Uint8Array(s),h=new DataView(m.buffer),g=t;return m[g]=Number(p)<<Dx|Number(f)<<Ox|Number(c)<<kx|Number(l)<<Ax|Number(u)<<jx|Number(d)<<Mx,g++,h.setUint32(g,this.seqNum,!0),g+=Lx,c&&(h.setUint32(g,r,!0),g+=Fx),l&&!u&&(h.setBigUint64(g,i?.valueOf()??0n,!0),g+=Nx,h.setBigUint64(g,a?.valueOf()??0n,!0),g+=Nx),f&&!p&&(h.setBigUint64(g,o??0n,!0),g+=Px),n.series.forEach((e,t)=>{if(d||(h.setUint32(g,n.keys[t],!0),g+=Ix),!c){let t=e.data.byteLength;e.dataType.isVariable||(t=Tx(e)),h.setUint32(g,t,!0),g+=Fx}m.set(new Uint8Array(e.data),g),g+=e.data.byteLength,!l&&!u&&(h.setBigUint64(g,e.timeRange?.start.valueOf()??0n,!0),g+=Nx,h.setBigUint64(g,e.timeRange?.end.valueOf()??0n,!0),g+=Nx),!f&&!p&&(h.setBigUint64(g,e.alignment??0n,!0),g+=Px)}),m}decode(e,t=0){this.throwIfNotUpdated(`decode`);let n=e instanceof Uint8Array?e:new Uint8Array(e),r={keys:[],series:[]},i=t,a=0,o=0,s,c,l,u=new DataView(n.buffer,n.byteOffset,n.byteLength),d=!!(n[i]>>Dx&1),f=!!(n[i]>>Ox&1),p=!!(n[i]>>kx&1),m=!!(n[i]>>Ax&1),h=!!(n[i]>>jx&1),g=!!(n[i]>>Mx&1);i++;let ee=u.getUint32(i,!0);i+=Lx;let te=this.states.get(ee);if(te==null)return r;if(p){if(i+Fx>u.byteLength)return r;a=u.getUint32(i,!0),i+=Fx}if(m&&!h){if(i+Nx>u.byteLength)return r;s=new D(u.getBigUint64(i,!0)),i+=Nx,c=new D(u.getBigUint64(i,!0)),i+=Nx}if(f&&!d){if(i+Px>u.byteLength)return r;l=u.getBigUint64(i,!0),i+=Px}return g&&(r.keys=[...te.keys]),te.keys.forEach((e,t)=>{if(!g){if(i>=u.byteLength||u.getUint32(i,!0)!==e)return;i+=Ix,r.keys.push(e)}let ee=te.keyDataTypes.get(e);if(o=0,p)o=a;else{if(i+Fx>u.byteLength)return;o=u.getUint32(i,!0),i+=Fx}let ne=o;if(ee.isVariable||(ne*=ee.density.valueOf()),i+ne>u.byteLength){r.keys.splice(t,1);return}let re={dataType:ee,data:n.slice(i,i+ne).buffer};if(i+=ne,!m&&!h){if(i+Nx*2>u.byteLength)return;let e=u.getBigUint64(i,!0);i+=Nx;let t=u.getBigUint64(i,!0);i+=Nx,re.timeRange=new A({start:e,end:t})}else h?re.timeRange=new A({start:0n,end:0n}):re.timeRange=new A({start:s?.valueOf()??0n,end:c?.valueOf()??0n});if(!f&&!d){if(i+Px>u.byteLength)return;l=u.getBigUint64(i,!0),i+=Px,re.alignment=l}else d?re.alignment=0n:re.alignment=l;r.series.push(re)}),r}},Bx=new Uint8Array([254]),Vx=new Uint8Array([255]),Hx=`application/sy-framer`,Ux=class{contentType=Hx;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=ai.JSON_CODEC}encode(e){let t=e;if(t.type==`close`||t.payload?.command!=Cx.Write){let e=this.lowPerfCodec.encode(t),n=new Uint8Array({length:e.byteLength+1});return n.set(Bx,0),n.set(new Uint8Array(e),1),n}let n=this.base.encode(t.payload?.frame,1);return n.set(Vx,0),n}decode(e,t){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===254)return this.lowPerfCodec.decode(e.slice(1),t);let n={type:`data`},r=this.base.decode(e,1);return n.payload={command:Cx.Write,frame:r},n}},Wx=class{contentType=Hx;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=ai.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,t){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===254?this.lowPerfCodec.decode(e.slice(1),t):{type:`data`,payload:{frame:this.base.decode(e,1)}}}},Gx=class e{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=new Set,this.codec=new zx}static async open(t,n){let r=new e(t);return await r.update(n),r}async update(e){let{variant:t,normalized:n}=gb(e),r=await this.retriever.retrieve(n),i=r.map(e=>e.key);if(Fi.uniqueUnorderedPrimitiveArrays(Array.from(this.keys),i)===Fi.EQUAL)return!1;if(this.codec.update(i,r.map(e=>e.dataType)),t===`keys`)return this.adapter=null,this.keys=new Set(n),!0;let a=new Map;return this.adapter=a,n.forEach(e=>{let t=r.find(t=>t.name===e);if(t==null)throw Error(`Channel ${e} not found`);a.set(t.key,t.name)}),this.keys=new Set(this.adapter.keys()),!0}adapt(e){if(this.adapter==null){let t=!1;return e.forEach(e=>{this.keys.has(e)||(t=!0)}),t?e.filter(e=>this.keys.has(e)):e}let t=this.adapter;return e.mapFilter((e,n)=>{if(typeof e==`number`){let r=t.get(e);return r==null?[e,n,!1]:[r,n,!0]}return[e,n,!0]})}},Kx=class e{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new zx}static async open(t,n){let r=new e(t);return await r.update(n),r}async adaptParams(e){let t=Bb.parse(e);return await Promise.all(t.map(async e=>await this.adaptToKey(e)))}async update(e){let t=await bb(this.retriever,e),n=t.map(e=>e.key),r=new Set(this.keys),i=new Set(n),a=!i.isSubsetOf(r),o=!r.isSubsetOf(i);return a||o?(this.adapter=new Map(t.map(e=>[e.name,e.key])),this.keys=n,this.codec.update(this.keys,t.map(e=>e.dataType)),!0):!1}async fetchChannel(e){let t=await this.retriever.retrieve(e);if(t.length===0)throw Error(`Channel ${JSON.stringify(e)} not found`);return t[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,t){if(typeof e==`string`||typeof e==`number`){if(t==null)throw new L(`
85
+ `)}encode(e,t=0){this.throwIfNotUpdated(`encode`);let n=e;typeof e==`object`&&e&&`toPayload`in e&&(n=e.toPayload()),MS(n);let r=-1,i,a,o,s=t+WS+US,c=!this.currState?.hasVariableDataTypes,l=!0,u=!0,d=!0,f=!0,p=!0;n.keys.length!==this.currState?.keys.length&&(d=!1,s+=n.keys.length*HS),n.series.forEach((e,t)=>{let u=jS(e),d=n.keys[t],p=this.currState?.keyDataTypes.get(d);if(p==null)throw new L(`Channel ${d} was not provided in the list of channels when opening the writer`);if(!p.equals(e.dataType))throw new L(`Series data type of ${e.dataType.toString()} does not match the data type of ${p.toString()} for channel ${d}`);if(s+=e.data.byteLength,r===-1){r=u,i=e.timeRange?.start,a=e.timeRange?.end,o=BigInt(e.alignment??0n);return}r!==u&&(c=!1),(i?.valueOf()!==e.timeRange?.start.valueOf()||a?.valueOf()!==e.timeRange?.end.valueOf())&&(l=!1),o!==BigInt(e.alignment??0)&&(f=!1)}),u=l&&i==null&&a==null,p=f&&(o===void 0||o===0n),c?s+=VS:s+=n.keys.length*VS,u||(l?s+=zS*2:s+=n.keys.length*zS*2),p||(f?s+=BS:s+=n.keys.length*BS);let m=new Uint8Array(s),h=new DataView(m.buffer),g=t;return m[g]=Number(p)<<NS|Number(f)<<PS|Number(c)<<FS|Number(l)<<IS|Number(u)<<LS|Number(d)<<RS,g++,h.setUint32(g,this.seqNum,!0),g+=US,c&&(h.setUint32(g,r,!0),g+=VS),l&&!u&&(h.setBigUint64(g,i?.valueOf()??0n,!0),g+=zS,h.setBigUint64(g,a?.valueOf()??0n,!0),g+=zS),f&&!p&&(h.setBigUint64(g,o??0n,!0),g+=BS),n.series.forEach((e,t)=>{if(d||(h.setUint32(g,n.keys[t],!0),g+=HS),!c){let t=e.data.byteLength;e.dataType.isVariable||(t=jS(e)),h.setUint32(g,t,!0),g+=VS}m.set(new Uint8Array(e.data),g),g+=e.data.byteLength,!l&&!u&&(h.setBigUint64(g,e.timeRange?.start.valueOf()??0n,!0),g+=zS,h.setBigUint64(g,e.timeRange?.end.valueOf()??0n,!0),g+=zS),!f&&!p&&(h.setBigUint64(g,e.alignment??0n,!0),g+=BS)}),m}decode(e,t=0){this.throwIfNotUpdated(`decode`);let n=e instanceof Uint8Array?e:new Uint8Array(e),r={keys:[],series:[]},i=t,a=0,o=0,s,c,l,u=new DataView(n.buffer,n.byteOffset,n.byteLength),d=!!(n[i]>>NS&1),f=!!(n[i]>>PS&1),p=!!(n[i]>>FS&1),m=!!(n[i]>>IS&1),h=!!(n[i]>>LS&1),g=!!(n[i]>>RS&1);i++;let ee=u.getUint32(i,!0);i+=US;let te=this.states.get(ee);if(te==null)return r;if(p){if(i+VS>u.byteLength)return r;a=u.getUint32(i,!0),i+=VS}if(m&&!h){if(i+zS>u.byteLength)return r;s=new O(u.getBigUint64(i,!0)),i+=zS,c=new O(u.getBigUint64(i,!0)),i+=zS}if(f&&!d){if(i+BS>u.byteLength)return r;l=u.getBigUint64(i,!0),i+=BS}return g&&(r.keys=[...te.keys]),te.keys.forEach((e,t)=>{if(!g){if(i>=u.byteLength||u.getUint32(i,!0)!==e)return;i+=HS,r.keys.push(e)}let ee=te.keyDataTypes.get(e);if(o=0,p)o=a;else{if(i+VS>u.byteLength)return;o=u.getUint32(i,!0),i+=VS}let ne=o;if(ee.isVariable||(ne*=ee.density.valueOf()),i+ne>u.byteLength){r.keys.splice(t,1);return}let re={dataType:ee,data:n.slice(i,i+ne).buffer};if(i+=ne,!m&&!h){if(i+zS*2>u.byteLength)return;let e=u.getBigUint64(i,!0);i+=zS;let t=u.getBigUint64(i,!0);i+=zS,re.timeRange=new j({start:e,end:t})}else h?re.timeRange=new j({start:0n,end:0n}):re.timeRange=new j({start:s?.valueOf()??0n,end:c?.valueOf()??0n});if(!f&&!d){if(i+BS>u.byteLength)return;l=u.getBigUint64(i,!0),i+=BS,re.alignment=l}else d?re.alignment=0n:re.alignment=l;r.series.push(re)}),r}},KS=new Uint8Array([254]),qS=new Uint8Array([255]),JS=`application/sy-framer`,YS=class{contentType=JS;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=Vo.JSON_CODEC}encode(e){let t=e;if(t.type==`close`||t.payload?.command!=kS.Write){let e=this.lowPerfCodec.encode(t),n=new Uint8Array({length:e.byteLength+1});return n.set(KS,0),n.set(new Uint8Array(e),1),n}let n=this.base.encode(t.payload?.frame,1);return n.set(qS,0),n}decode(e,t){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===254)return this.lowPerfCodec.decode(e.slice(1),t);let n={type:`data`},r=this.base.decode(e,1);return n.payload={command:kS.Write,frame:r},n}},XS=class{contentType=JS;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=Vo.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,t){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===254?this.lowPerfCodec.decode(e.slice(1),t):{type:`data`,payload:{frame:this.base.decode(e,1)}}}},ZS=class e{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=new Set,this.codec=new GS}static async open(t,n){let r=new e(t);return await r.update(n),r}async update(e){let{variant:t,normalized:n}=Sx(e),r=await this.retriever.retrieve(n),i=r.map(e=>e.key);if(fs.uniqueUnorderedPrimitiveArrays(Array.from(this.keys),i)===fs.EQUAL)return!1;if(this.codec.update(i,r.map(e=>e.dataType)),t===`keys`)return this.adapter=null,this.keys=new Set(n),!0;let a=new Map;return this.adapter=a,n.forEach(e=>{let t=r.find(t=>t.name===e);if(t==null)throw Error(`Channel ${e} not found`);a.set(t.key,t.name)}),this.keys=new Set(this.adapter.keys()),!0}adapt(e){if(this.adapter==null){let t=!1;return e.forEach(e=>{this.keys.has(e)||(t=!0)}),t?e.filter(e=>this.keys.has(e)):e}let t=this.adapter;return e.mapFilter((e,n)=>{if(typeof e==`number`){let r=t.get(e);return r==null?[e,n,!1]:[r,n,!0]}return[e,n,!0]})}},QS=class e{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new GS}static async open(t,n){let r=new e(t);return await r.update(n),r}async adaptParams(e){let t=Kx.parse(e);return await Promise.all(t.map(async e=>await this.adaptToKey(e)))}async update(e){let t=await Ex(this.retriever,e),n=t.map(e=>e.key),r=new Set(this.keys),i=new Set(n),a=!i.isSubsetOf(r),o=!r.isSubsetOf(i);return a||o?(this.adapter=new Map(t.map(e=>[e.name,e.key])),this.keys=n,this.codec.update(this.keys,t.map(e=>e.dataType)),!0):!1}async fetchChannel(e){let t=await this.retriever.retrieve(e);if(t.length===0)throw Error(`Channel ${JSON.stringify(e)} not found`);return t[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,t){if(typeof e==`string`||typeof e==`number`){if(t==null)throw new L(`
69
86
  Received a single channel name or key but no series.
70
- `);if(Array.isArray(t)){if(t.some(e=>e instanceof Qo||Array.isArray(e)))throw new L(`
87
+ `);if(Array.isArray(t)){if(t.some(e=>e instanceof Ic||Array.isArray(e)))throw new L(`
71
88
  Received a single channel name or key but multiple series.
72
- `);t=t}let n=await this.fetchChannel(e),r=new Qo({data:t,dataType:n.dataType});return new $(n.key,r)}if(Array.isArray(e)){if(t==null)throw new L(`
89
+ `);t=t}let n=await this.fetchChannel(e),r=new Ic({data:t,dataType:n.dataType});return new $(n.key,r)}if(Array.isArray(e)){if(t==null)throw new L(`
73
90
  Received an array of channel names or keys but no series.
74
91
  `);if(!Array.isArray(t))throw new L(`
75
92
  Received an array of channel names or keys but no array of series.
76
93
  `);let n=[],r=[];for(let i=0;i<e.length;i++){let a=await this.fetchChannel(e[i]);if(i>=t.length)throw new L(`
77
94
  Received an array of channel names or keys but not enough series.
78
- `);let o=new Qo({data:t[i],dataType:a.dataType});n.push(a.key),r.push(o)}return new $(n,r)}if(e instanceof $||e instanceof Map){let t=new $(e);return this.adapter==null?t:new $(t.columns.map(e=>{let t=typeof e==`string`?this.adapter?.get(e):e;if(t==null)throw new L(`
95
+ `);let o=new Ic({data:t[i],dataType:a.dataType});n.push(a.key),r.push(o)}return new $(n,r)}if(e instanceof $||e instanceof Map){let t=new $(e);return this.adapter==null?t:new $(t.columns.map(e=>{let t=typeof e==`string`?this.adapter?.get(e):e;if(t==null)throw new L(`
79
96
  Channel ${e} was not provided in the list of channels when opening the writer
80
- `);return t}),t.series)}let n=[],r=[],i=Object.entries(e);for(let e=0;e<i.length;e++){let[t,a]=i[e],o=await this.fetchChannel(t),s=new Qo({data:a,dataType:o.dataType});n.push(o.key),r.push(s)}return new $(n,r)}},qx=class{name;stream;constructor(e,t){this.stream=t,this.name=e}async receive(){let[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){let[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on ${JSON.stringify(e)} closure.
81
- Please report this error to the Synnax team.`),t!=null){if(br.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){let t=this.stream.send(e);if(t!=null)throw t}},Jx=new O(-1),Yx=function(e){return e[e.Open=0]=`Open`,e[e.Next=1]=`Next`,e[e.Prev=2]=`Prev`,e[e.SeekFirst=3]=`SeekFirst`,e[e.SeekLast=4]=`SeekLast`,e[e.SeekLE=5]=`SeekLE`,e[e.SeekGE=6]=`SeekGE`,e[e.Valid=7]=`Valid`,e[e.Error=8]=`Error`,e}(Yx||{}),Xx=function(e){return e[e.None=0]=`None`,e[e.Ack=1]=`Ack`,e[e.Data=2]=`Data`,e}(Xx||{}),Zx=l.z.object({command:l.z.enum(Yx),span:O.z.optional(),bounds:A.z.optional(),stamp:D.z.optional(),keys:Z.array().optional(),chunkSize:l.z.number().optional(),downsampleFactor:l.z.int().optional()}),Qx=l.z.object({variant:l.z.enum(Xx),ack:l.z.boolean(),command:l.z.enum(Yx),error:Zc.payloadZ.optional().nullable(),frame:bx.optional()}),$x=class e{stream;adapter;value;constructor(e,t){this.stream=new qx(`Iterator`,e),this.value=new $,this.adapter=t}static async _open(t,n,r,i,a={}){let o=await Gx.open(r,n),s=new e(await i.stream(`/frame/iterate`,Zx,Qx),o);return await s.execute({command:Yx.Open,keys:Array.from(o.keys),bounds:new A(t),chunkSize:a.chunkSize??1e5,downsampleFactor:a.downsampleFactor??1}),s}async next(e=Jx){return await this.execute({command:Yx.Next,span:new O(e)})}async prev(e=Jx){return await this.execute({command:Yx.Prev,span:new O(e)})}async seekFirst(){return await this.execute({command:Yx.SeekFirst})}async seekLast(){return await this.execute({command:Yx.SeekLast})}async seekLE(e){return await this.execute({command:Yx.SeekLE,stamp:new D(e)})}async seekGE(e){return await this.execute({command:Yx.SeekGE,stamp:new D(e)})}async valid(){return await this.execute({command:Yx.Valid})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new eS(this)}async execute(e){for(this.stream.send(e),this.value=new $;;){let e=await this.stream.receive();if(e.variant===Xx.Ack)return e.ack;this.value.push(this.adapter.adapt(new $(e.frame)))}}},eS=class{iter;open=!1;constructor(e){this.iter=e}async next(){try{let e=!0;return this.open||=(await this.iter.seekFirst()||(e=!1),!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}}},tS=class{retriever;streamClient;constructor(e,t){this.retriever=e,this.streamClient=t}async read(e){let{channels:t,timeRange:n,channelNames:r,iteratorConfig:i}=e,a=await this.retriever.retrieve(t),o=new Set;a.forEach(e=>{o.add(e.key),e.index!==0&&o.add(e.index)});let s=Array.from(o).filter(e=>!a.some(t=>t.key===e));if(s.length>0){let e=await this.retriever.retrieve(s);a.push(...e)}return nS({iterator:await $x._open(n,Array.from(o),this.retriever,this.streamClient,i),channelPayloads:a,headers:r})}},nS=({iterator:e,channelPayloads:t,headers:n})=>{let r=Wl.getOS()===`Windows`?`\r
97
+ `);return t}),t.series)}let n=[],r=[],i=Object.entries(e);for(let e=0;e<i.length;e++){let[t,a]=i[e],o=await this.fetchChannel(t),s=new Ic({data:a,dataType:o.dataType});n.push(o.key),r.push(s)}return new $(n,r)}},$S=class{name;stream;constructor(e,t){this.stream=t,this.name=e}async receive(){let[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){let[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on ${JSON.stringify(e)} closure.
98
+ Please report this error to the Synnax team.`),t!=null){if(Yr.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){let t=this.stream.send(e);if(t!=null)throw t}},eC=new k(-1),tC=function(e){return e[e.Open=0]=`Open`,e[e.Next=1]=`Next`,e[e.Prev=2]=`Prev`,e[e.SeekFirst=3]=`SeekFirst`,e[e.SeekLast=4]=`SeekLast`,e[e.SeekLE=5]=`SeekLE`,e[e.SeekGE=6]=`SeekGE`,e[e.Valid=7]=`Valid`,e[e.Error=8]=`Error`,e}(tC||{}),nC=function(e){return e[e.None=0]=`None`,e[e.Ack=1]=`Ack`,e[e.Data=2]=`Data`,e}(nC||{}),rC=l.z.object({command:l.z.enum(tC),span:k.z.optional(),bounds:j.z.optional(),stamp:O.z.optional(),keys:Z.array().optional(),chunkSize:l.z.number().optional(),downsampleFactor:l.z.int().optional()}),iC=l.z.object({variant:l.z.enum(nC),ack:l.z.boolean(),command:l.z.enum(tC),error:Gi.payloadZ.optional().nullable(),frame:ES.optional()}),aC=class e{stream;adapter;value;constructor(e,t){this.stream=new $S(`Iterator`,e),this.value=new $,this.adapter=t}static async _open(t,n,r,i,a={}){let o=await ZS.open(r,n),s=new e(await i.stream(`/frame/iterate`,rC,iC),o);return await s.execute({command:tC.Open,keys:Array.from(o.keys),bounds:new j(t),chunkSize:a.chunkSize??1e5,downsampleFactor:a.downsampleFactor??1}),s}async next(e=eC){return await this.execute({command:tC.Next,span:new k(e)})}async prev(e=eC){return await this.execute({command:tC.Prev,span:new k(e)})}async seekFirst(){return await this.execute({command:tC.SeekFirst})}async seekLast(){return await this.execute({command:tC.SeekLast})}async seekLE(e){return await this.execute({command:tC.SeekLE,stamp:new O(e)})}async seekGE(e){return await this.execute({command:tC.SeekGE,stamp:new O(e)})}async valid(){return await this.execute({command:tC.Valid})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new oC(this)}async execute(e){for(this.stream.send(e),this.value=new $;;){let e=await this.stream.receive();if(e.variant===nC.Ack)return e.ack;this.value.push(this.adapter.adapt(new $(e.frame)))}}},oC=class{iter;open=!1;constructor(e){this.iter=e}async next(){try{let e=!0;return this.open||=(await this.iter.seekFirst()||(e=!1),!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}}},sC=class{retriever;streamClient;constructor(e,t){this.retriever=e,this.streamClient=t}async read(e){let{channels:t,timeRange:n,channelNames:r,iteratorConfig:i}=e,a=await this.retriever.retrieve(t),o=new Set;a.forEach(e=>{o.add(e.key),e.index!==0&&o.add(e.index)});let s=Array.from(o).filter(e=>!a.some(t=>t.key===e));if(s.length>0){let e=await this.retriever.retrieve(s);a.push(...e)}return cC({iterator:await aC._open(n,Array.from(o),this.retriever,this.streamClient,i),channelPayloads:a,headers:r})}},cC=({iterator:e,channelPayloads:t,headers:n})=>{let r=Ku.getOS()===`Windows`?`\r
82
99
  `:`
83
- `,i=new TextEncoder,a=!1,o=!1,s=rS(t),{columns:c,columnsByIndexKey:l,emptyGroupStrings:u}=iS(t,s,n),d=[],f=0,p=[],m=e=>{for(let[t]of s){let n=e.get(t);if(n.length===0)continue;let r=(l.get(t)??[]).map(t=>e.get(t.key));for(let e=0;e<n.length;e++){let i=n.at(e,!0),a=r.map(t=>Wc.formatValue(t.at(e,!0)));p.push({time:i,values:a,indexKey:t})}}},h=(e,t=!1)=>{p.length>0&&(p.sort((e,t)=>Number(e.time-t.time)),f>0&&(d=d.slice(f),f=0),d=aS(d,p),p=[]);let n=[],r=d.length;for(;f<r&&n.length<e;){let e=d[f].time;if(!t&&d[r-1].time===e)break;let i=new Map;for(;f<r&&d[f].time===e;){let e=d[f++];i.set(e.indexKey,e)}let a=[];for(let[e]of s){let t=i.get(e);a.push(t?.values.join(`,`)??u.get(e)??``)}n.push(a.join(`,`))}return n};return new ReadableStream({async pull(t){try{if(o||=(await e.seekFirst(),!0),!a){let e=c.map(e=>Wc.formatValue(e.header)).join(`,`);t.enqueue(i.encode(`${e}${r}`)),a=!0}d.length-f+p.length<oS&&await e.next()&&m(e.value);let n=h(oS);if(n.length>0&&t.enqueue(i.encode(`${n.join(r)}${r}`)),d.length-f===0||p.length===0){if(!await e.next()){let n=h(1/0,!0);n.length>0&&t.enqueue(i.encode(`${n.join(r)}${r}`)),await e.close(),t.close();return}m(e.value)}}catch(n){await e.close(),t.error(n)}},async cancel(){await e.close()}})},rS=e=>{let t=new Map;for(let n of e){if(n.index===0)continue;let e=t.get(n.index);e??(e=[n.index],t.set(n.index,e)),!n.isIndex&&!e.includes(n.key)&&e.push(n.key)}return t},iS=(e,t,n)=>{let r=new Map(e.map(e=>[e.key,e])),i=[],a=new Map,o=new Map;for(let[e,s]of t){let t=[];for(let e of s){let a=r.get(e);if(a==null)throw new wu(`Channel ${e} not found`);let o={key:e,header:n?.[e]??n?.[a.name]??a.name};i.push(o),t.push(o)}a.set(e,t),o.set(e,`,`.repeat(t.length-1))}return{columns:i,columnsByIndexKey:a,emptyGroupStrings:o}},aS=(e,t)=>{let n=[],r=0,i=0;for(;r<e.length&&i<t.length;)e[r].time<=t[i].time?n.push(e[r++]):n.push(t[i++]);return n.push(...e.slice(r),...t.slice(i)),n},oS=1e3,sS=l.z.object({keys:l.z.number().array(),downsampleFactor:l.z.int(),throttleRate:Do.z.optional(),excludeGroups:l.z.uint32().array().optional()}),cS=l.z.object({frame:bx}),lS=l.z.object({channels:Bb,downsampleFactor:l.z.int().default(1),throttleRate:Do.z.default(new Do(0)),useHighPerformanceCodec:l.z.boolean().default(!0),excludeGroups:l.z.uint32().array().default([])}),uS=lS.or(Bb.transform(e=>lS.parse({channels:e}))),dS=(e,t)=>async n=>{let r=uS.parse(n),i=await Gx.open(e,r.channels);r.useHighPerformanceCodec&&(t=t.withCodec(new Wx(i.codec)));let a=await t.stream(`/frame/stream`,sS,cS),o=new pS(a,i,r.downsampleFactor,r.throttleRate,r.excludeGroups);a.send({keys:Array.from(i.keys),downsampleFactor:r.downsampleFactor,throttleRate:r.throttleRate,excludeGroups:r.excludeGroups});let[,s]=await a.receive();if(s!=null)throw s;return o},fS=async(e,t,n)=>await dS(e,t)(n),pS=class{stream;adapter;downsampleFactor;throttleRate;excludeGroups;constructor(e,t,n=1,r=new Do(0),i=[]){this.stream=new qx(`Streamer`,e),this.adapter=t,this.downsampleFactor=n,this.throttleRate=r,this.excludeGroups=i}get keys(){return Array.from(this.adapter.keys)}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(br.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new $((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,excludeGroups:this.excludeGroups})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}},mS=class e{wrapped_=null;breaker;opener;config;constructor(e,t,n={}){this.opener=e,this.config=uS.parse(t);let{maxRetries:r=5e3,baseInterval:i=O.seconds(1),scale:a=1}=n??{};this.breaker=new fs.Breaker({maxRetries:r,baseInterval:i,scale:a})}static async open(t,n,r){let i=new e(t,n,r);return await i.runStreamer(),i}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 Error(`stream closed`);return this.wrapped_}async update(e){this.config.channels=Bb.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(br.matches(e))return{done:!0,value:void 0};throw e}}async read(){try{let e=await this.wrapped.read();return this.breaker.reset(),e}catch(e){if(br.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}},hS=class extends Tl.Observer{streamer;closePromise;constructor(e,t){super(t),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(let e of this.streamer)this.notify(e)}},gS=function(e){return e[e.PersistStream=1]=`PersistStream`,e[e.Persist=2]=`Persist`,e[e.Stream=3]=`Stream`,e}({}),_S=new O(-1),vS=class extends yu.sub(`writer_closed`){constructor(){super(`WriterClosed`)}},yS=l.z.enum(gS).or(l.z.enum([`persist`,`stream`,`persistStream`]).transform(e=>{switch(e){case`persist`:return gS.Persist;case`stream`:return gS.Stream;case`persistStream`:return gS.PersistStream}})),bS=l.z.object({start:D.z.optional(),controlSubject:F.subjectZ.optional(),authorities:l.z.union([F.authorityZ.transform(e=>[e]),F.authorityZ.array()]).default([F.ABSOLUTE_AUTHORITY]),mode:yS.default(gS.PersistStream),errOnUnauthorized:l.z.boolean().default(!1),enableAutoCommit:l.z.boolean().default(!0),autoIndexPersistInterval:O.z.default(O.SECOND),useHighPerformanceCodec:l.z.boolean().default(!0)}),xS=bS.extend({keys:Z.array().optional()}),SS=bS.extend({channels:Bb}),CS=SS.or(Bb.transform(e=>SS.parse({channels:e,start:D.now()}))),wS=l.z.object({command:l.z.enum(Cx),config:xS.optional(),frame:bx.optional(),buffer:l.z.instanceof(Uint8Array).optional()}),TS=l.z.object({command:l.z.enum(Cx),end:D.z,err:Zc.payloadZ.optional()}),ES=l.z.tuple([l.z.union([l.z.record(Z.or(nb),F.authorityZ),Z.or(nb),F.authorityZ]),F.authorityZ.optional()]).transform(([e,t])=>{if(F.authorityZ.safeParse(e).success)return{keys:[],authorities:[e]};if(Z.or(nb).safeParse(e).success){if(t==null)throw Error(`authority is required when setting authority for a single channel`);return{keys:[e],authorities:[t]}}let n=e;return{keys:Object.keys(n),authorities:Object.values(n)}}),DS=class e{stream;adapter;closeErr=null;constructor(e,t){this.stream=e,this.adapter=t}static async _open(t,n,r){let i=CS.parse(r),a=await Kx.open(t,i.channels);i.useHighPerformanceCodec&&(n=n.withCodec(new Ux(a.codec)));let o=new e(await n.stream(`/frame/write`,wS,TS),a);return await o.execute({command:Cx.Open,config:{...i,keys:a.keys}}),o}async write(e,t){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();let n=await this.adapter.adapt(e,t);this.stream.send({command:Cx.Write,frame:n.toPayload()})}async setAuthority(e,t){if(this.closeErr!=null)throw this.closeErr;let n=ES.parse([e,t]),r={keys:await this.adapter.adaptParams(n.keys),authorities:n.authorities};await this.execute({command:Cx.SetAuthority,config:r})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),D.ZERO):(await this.execute({command:Cx.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(vS.matches(this.closeErr))return null;throw this.closeErr}let[e,t]=await this.stream.receive();t==null?this.closeErr=Zc.decode(e?.err):this.closeErr=br.matches(t)?new vS:t}}async execute(e){let t=this.stream.send(e);for(t!=null&&await this.closeInternal(t);;){let[t,n]=await this.stream.receive();n!=null&&await this.closeInternal(n);let r=Zc.decode(t?.err);if(r!=null&&await this.closeInternal(r),t?.command==e.command)return t}}},OS=z(`framer`),kS=OS(``),AS=class{streamClient;retriever;deleter;reader;constructor(e,t,n){this.streamClient=e,this.retriever=n,this.deleter=new _x(t),this.reader=new tS(n,e)}async openIterator(e,t,n){return await $x._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return await DS._open(this.retriever,this.streamClient,e)}async openStreamer(e){return await fS(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){let n=t,r=await this.openWriter({start:e,channels:Object.keys(n),mode:gS.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:O.MAX});return await r.write(n),await r.close()}let r=await this.openWriter({start:e,channels:t,mode:gS.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:O.MAX});await r.write(t,n),await r.close()}async read(e,t){if(!(`start`in e))return this.reader.read(e);let{single:n}=gb(t),r=await this.readFrame(e,t);return n?r.get(t):r}async readFrame(e,t){let n=await this.openIterator(e,t),r=new $;try{for await(let e of n)r.push(e)}finally{await n.close()}return r}async readLatest(e,t=1){let{single:n}=gb(e),r=await this.readLatestNFrame(e,t);return n?r.get(e):r}async readLatestNFrame(e,t){let n=await this.openIterator(A.MAX,e,{chunkSize:t}),r=new $;if(t>0)try{await n.seekLast(),await n.prev(Jx),r.push(n.value)}finally{await n.close()}return r}async delete(e,t){let{normalized:n,variant:r}=gb(e),i=new A(t);return r===`keys`?await this.deleter.delete({keys:n,bounds:i}):await this.deleter.delete({names:n,bounds:i})}},jS=o({ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:()=>_S,AUTO_SPAN:()=>Jx,Client:()=>AS,Frame:()=>$,HardenedStreamer:()=>mS,Iterator:()=>$x,ObservableStreamer:()=>hS,Reader:()=>tS,TYPE_ONTOLOGY_ID:()=>kS,Writer:()=>DS,WriterClosedError:()=>vS,WriterCommand:()=>Cx,WriterMode:()=>gS,createStreamOpener:()=>dS,frameZ:()=>bx,ontologyID:()=>OS,openStreamer:()=>fS,seriesFromPayload:()=>xx,seriesToPayload:()=>Sx,streamerConfigZ:()=>uS,writerCommandZ:()=>wx,writerConfigZ:()=>CS}),MS=F.ABSOLUTE_AUTHORITY,NS=F.ZERO_AUTHORITY,PS=F.stateZ(l.z.number()),FS=e=>{let t=e.from?.resource,n=e.to?.resource;return e.to==null?`${t} - ${e.from?.subject.name} -> released`:e.from==null?`${n} - released -> ${e.to.subject.name} (${e.to.authority.toString()})`:`${n} - ${e.from.subject.name} -> ${e.to.subject.name} (${e.to.authority.toString()})`},IS=l.z.object({transfers:l.z.array(F.transferZ(Z))}),LS=class extends hS{states;codec;constructor(e){super(e,e=>{let t=this.codec.decode(e.series[0].buffer,IS);return this.merge(t),[t.transfers,!0]}),this.states=new Map,this.codec=new ai.JSONCodec}subjects(){let e=new Map;return this.states.forEach(t=>e.set(t.subject.key,t.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(e=>{e.from==null&&e.to==null&&console.warn(`Invalid transfer: `,e),e.to==null?this.states.delete(e.from.resource):this.states.set(e.to.resource,e.to)})}},RS=`sy_node_1_control`,zS=class{framer;constructor(e){this.framer=e}async openStateTracker(){return new LS(await mS.open(async e=>await this.framer.openStreamer(e),RS))}},BS=o({ABSOLUTE_AUTHORITY:()=>MS,CONTROL_STATE_CHANNEL_NAME:()=>RS,Client:()=>zS,StateTracker:()=>LS,ZERO_AUTHORITY:()=>NS,stateZ:()=>PS,transferString:()=>FS}),VS=l.z.uint32(),HS=l.z.object({rack:VS}),US=cu.statusZ({details:HS}),WS=l.z.object({key:VS,name:l.z.string().min(1,`Name is required`),taskCounter:l.z.uint32().optional(),embedded:l.z.boolean().optional(),status:US.optional(),integrations:N.nullToUndefined(l.z.string().array())}),GS=WS.omit({taskCounter:!0,embedded:!0,key:!0}).extend({key:l.z.uint32().default(0)}),KS=z(`rack`),qS=KS(0),JS=`sy_rack_set`,YS=`sy_rack_delete`,XS=l.z.object({keys:VS.array().optional(),names:l.z.string().array().optional(),integration:l.z.string().optional(),searchTerm:l.z.string().optional(),embedded:l.z.boolean().optional(),hostIsNode:l.z.boolean().optional(),limit:l.z.int().optional(),offset:l.z.int().optional(),includeStatus:l.z.boolean().optional()}),ZS=l.z.object({racks:w.nullishToEmpty(WS)}),QS=WS,$S=l.z.union([l.z.object({key:VS,includeStatus:l.z.boolean().optional()}).transform(({key:e,includeStatus:t})=>({keys:[e],includeStatus:t})),l.z.object({name:l.z.string(),includeStatus:l.z.boolean().optional()}).transform(({name:e,includeStatus:t})=>({names:[e],includeStatus:t}))]),eC=XS,tC=l.z.union([$S,eC]),nC=l.z.object({racks:GS.array()}),rC=l.z.object({racks:WS.array()}),iC=l.z.object({keys:VS.array()}),aC=l.z.object({}),oC=class{client;tasks;constructor(e,t){this.client=e,this.tasks=t}async delete(e){await S(this.client,`/rack/delete`,{keys:w.toArray(e)},iC,aC)}async create(e){let t=!Array.isArray(e),n=await S(this.client,`/rack/create`,{racks:w.toArray(e)},nC,rC),r=this.sugar(n.racks);return t?r[0]:r}async retrieve(e){let t=`key`in e||`name`in e,n=await S(this.client,`/rack/retrieve`,e,tC,ZS),r=this.sugar(n.racks);return X(`Rack`,e,r,t),t?r[0]:r}sugar(e){let t=!Array.isArray(e),n=w.toArray(e).map(({key:e,name:t,status:n,integrations:r})=>new sC(e,t,this.tasks,n,r));return t?n[0]:n}},sC=class{key;name;status;integrations;tasks;constructor(e,t,n,r,i){this.key=e,this.name=t,this.tasks=n,this.status=r,this.integrations=i}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,t){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&4294967295n)).toString(),await this.tasks.create(e,t)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status,integrations:this.integrations}}},cC=e=>Ru(KS(e)),lC=o({Client:()=>oC,DELETE_CHANNEL_NAME:()=>YS,Rack:()=>sC,SET_CHANNEL_NAME:()=>JS,TYPE_ONTOLOGY_ID:()=>qS,keyZ:()=>VS,newZ:()=>GS,ontologyID:()=>KS,payloadZ:()=>WS,rackZ:()=>QS,statusDetailsZ:()=>HS,statusKey:()=>cC,statusZ:()=>US}),uC=l.z.object({rack:VS,device:l.z.string()}),dC=l.z.string(),fC=cu.statusZ({details:uC}),pC=({properties:e,make:t,model:n}={})=>l.z.object({key:dC,rack:VS,location:l.z.string().min(1,`Location is required`),make:t??l.z.string().min(1,`Make is required`),model:n??l.z.string().min(1,`Model is required`),name:l.z.string().min(1,`Name is required`),configured:l.z.boolean().default(!1),properties:e??I.nullishToEmpty(),status:fC.optional(),parent:R.optional()}),mC=({properties:e,make:t,model:n}={})=>pC({properties:e,make:t,model:n}).partial({key:!0,configured:!0}),hC=z(`device`),gC=hC(``),_C=`sy_device_set`,vC=`sy_device_delete`,yC=e=>l.z.object({devices:N.toArray(mC(e))}),bC=e=>l.z.object({devices:pC(e).array()}),xC=l.z.object({keys:dC.array()}),SC=l.z.object({}),CC=l.z.object({keys:dC.array().optional(),names:l.z.string().array().optional(),makes:l.z.string().array().optional(),models:l.z.string().array().optional(),locations:l.z.string().array().optional(),racks:VS.array().optional(),searchTerm:l.z.string().optional(),limit:l.z.int().optional(),offset:l.z.int().optional(),includeStatus:l.z.boolean().optional(),includeParent:l.z.boolean().optional()}),wC=e=>l.z.object({devices:w.nullishToEmpty(pC(e))}),TC=l.z.object({key:dC,includeStatus:l.z.boolean().optional()}).transform(({key:e,includeStatus:t})=>({keys:[e],includeStatus:t})),EC=l.z.union([TC,CC]),DC=class{client;constructor(e){this.client=e}async retrieve(e){let{schemas:t,...n}=e,r=typeof n==`object`&&`key`in n,i=await S(this.client,`/device/retrieve`,n,EC,wC(t));return X(`Device`,n,i.devices,r),r?i.devices[0]:i.devices}async create(e,t){let n=!Array.isArray(e),r=await S(this.client,`/device/create`,{devices:w.toArray(e)},yC(t),bC(t));return n?r.devices[0]:r.devices}async delete(e){await S(this.client,`/device/delete`,{keys:w.toArray(e)},xC,SC)}},OC=e=>Ru(hC(e)),kC=o({Client:()=>DC,DELETE_CHANNEL_NAME:()=>vC,SET_CHANNEL_NAME:()=>_C,TYPE_ONTOLOGY_ID:()=>gC,deviceZ:()=>pC,keyZ:()=>dC,newZ:()=>mC,ontologyID:()=>hC,statusDetailsZ:()=>uC,statusKey:()=>OC,statusZ:()=>fC}),AC=fl.keyZ,jC=fl.labelZ,MC=fl.newZ,NC=`labeled_by`,PC=`sy_label_set`,FC=`sy_label_delete`,IC=l.default.object({labels:MC.array()}),LC=l.default.object({labels:jC.array()}),RC=l.default.object({keys:AC.array()}),zC=l.default.object({id:R,labels:AC.array(),replace:l.default.boolean().optional()}),BC=zC.omit({replace:!0}),VC=l.default.object({}),HC=l.default.object({keys:AC.array().optional(),names:l.default.string().array().optional(),for:R.optional(),searchTerm:l.default.string().optional(),offset:l.default.int().optional(),limit:l.default.int().optional()}),UC=l.default.object({key:AC}).transform(({key:e})=>({keys:[e]})),WC=l.default.union([UC,HC]),GC=l.default.object({labels:w.nullishToEmpty(jC)}),KC=class{type=`label`;client;constructor(e){this.client=e}async retrieve(e){let t=`key`in e,n=await S(this.client,`/label/retrieve`,e,WC,GC);return X(`Label`,e,n.labels,t),t?n.labels[0]:n.labels}async label(e,t,n={}){await S(this.client,`/label/set`,{id:e,labels:t,replace:n.replace},zC,VC)}async remove(e,t){await S(this.client,`/label/remove`,{id:e,labels:t},BC,VC)}async create(e){let t=Array.isArray(e),n=await S(this.client,`/label/create`,{labels:w.toArray(e)},IC,LC);return t?n.labels:n.labels[0]}async delete(e){await S(this.client,`/label/delete`,{keys:w.toArray(e)},RC,VC)}},qC=z(`label`),JC=qC(``),YC=o({Client:()=>KC,DELETE_CHANNEL_NAME:()=>FC,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:()=>NC,SET_CHANNEL_NAME:()=>PC,TYPE_ONTOLOGY_ID:()=>JC,keyZ:()=>AC,labelZ:()=>jC,newZ:()=>MC,ontologyID:()=>qC}),XC=l.z.uuid(),ZC=l.z.object({key:XC,name:l.z.string(),data:Hr.preserveCase(I.nullishToEmpty())}),QC=ZC.partial({key:!0}),$C=z(`lineplot`),ew=$C(``),tw=l.z.uuid(),nw=l.z.object({key:tw,name:l.z.string().min(1,`Name is required`),author:l.z.uuid().optional(),layout:Hr.preserveCase(I.nullishToEmpty())}),rw=nw.omit({author:!0}).partial({key:!0}),iw=z(`workspace`),aw=iw(``),ow=l.z.object({keys:tw.array().optional(),searchTerm:l.z.string().optional(),author:Ad.optional(),offset:l.z.int().optional(),limit:l.z.int().optional()}),sw=l.z.object({workspaces:rw.array()}),cw=l.z.object({key:tw,name:l.z.string()}),lw=l.z.object({key:tw,layout:Hr.preserveCase(I.unknownZ())}),uw=l.z.object({keys:tw.array()}),dw=l.z.object({workspaces:w.nullishToEmpty(nw)}),fw=l.z.object({workspaces:nw.array()}),pw=l.z.object({}),mw=`sy_workspace_set`,hw=`sy_workspace_delete`,gw=class{client;constructor(e){this.client=e}async create(e){let t=Array.isArray(e),n=await S(this.client,`/workspace/create`,{workspaces:w.toArray(e)},sw,fw);return t?n.workspaces:n.workspaces[0]}async rename(e,t){await S(this.client,`/workspace/rename`,{key:e,name:t},cw,pw)}async setLayout(e,t){await S(this.client,`/workspace/set-layout`,{key:e,layout:t},lw,pw)}async retrieve(e){let t,n=typeof e!=`string`;t=typeof e==`string`||Array.isArray(e)?{keys:w.toArray(e)}:e;let r=await S(this.client,`/workspace/retrieve`,t,ow,dw);return n?r.workspaces:r.workspaces[0]}async delete(e){await S(this.client,`/workspace/delete`,{keys:w.toArray(e)},uw,pw)}},_w=o({Client:()=>gw,DELETE_CHANNEL_NAME:()=>hw,SET_CHANNEL_NAME:()=>mw,TYPE_ONTOLOGY_ID:()=>aw,keyZ:()=>tw,newZ:()=>rw,ontologyID:()=>iw,workspaceZ:()=>nw}),vw=l.z.object({key:XC,name:l.z.string()}),yw=l.z.object({key:XC,data:Hr.preserveCase(I.unknownZ())}),bw=l.z.object({keys:XC.array()}),xw=l.z.object({keys:XC.array()}),Sw=l.z.object({key:XC}).transform(({key:e})=>({keys:[e]})),Cw=l.z.union([Sw,xw]),ww=l.z.object({linePlots:w.nullishToEmpty(ZC)}),Tw=l.z.object({workspace:tw,linePlots:QC.array()}),Ew=l.z.object({linePlots:ZC.array()}),Dw=l.z.object({}),Ow=class{client;constructor(e){this.client=e}async create(e,t){let n=Array.isArray(t),r=await S(this.client,`/lineplot/create`,{workspace:e,linePlots:w.toArray(t)},Tw,Ew);return n?r.linePlots:r.linePlots[0]}async rename(e,t){await S(this.client,`/lineplot/rename`,{key:e,name:t},vw,Dw)}async setData(e,t){await S(this.client,`/lineplot/set-data`,{key:e,data:t},yw,Dw)}async retrieve(e){let t=Sw.safeParse(e).success,n=await S(this.client,`/lineplot/retrieve`,e,Cw,ww);return X(`LinePlot`,e,n.linePlots,t),t?n.linePlots[0]:n.linePlots}async delete(e){await S(this.client,`/lineplot/delete`,{keys:w.toArray(e)},bw,Dw)}},kw=o({Client:()=>Ow,TYPE_ONTOLOGY_ID:()=>ew,keyZ:()=>XC,linePlotZ:()=>ZC,newZ:()=>QC,ontologyID:()=>$C,retrieveArgsZ:()=>Cw}),Aw=l.z.uuid(),jw=l.z.object({key:Aw,name:l.z.string(),data:Hr.preserveCase(I.nullishToEmpty())}),Mw=jw.partial({key:!0}),Nw=z(`log`),Pw=Nw(``),Fw=l.z.object({key:Aw,name:l.z.string()}),Iw=l.z.object({key:Aw,data:Hr.preserveCase(I.unknownZ())}),Lw=l.z.object({keys:Aw.array()}),Rw=l.z.object({keys:Aw.array()}),zw=l.z.object({key:Aw}).transform(({key:e})=>({keys:[e]})),Bw=l.z.union([zw,Rw]),Vw=l.z.object({logs:w.nullishToEmpty(jw)}),Hw=l.z.object({workspace:tw,logs:Mw.array()}),Uw=l.z.object({logs:jw.array()}),Ww=l.z.object({}),Gw=class{client;constructor(e){this.client=e}async create(e,t){let n=Array.isArray(t),r=await S(this.client,`/log/create`,{workspace:e,logs:w.toArray(t)},Hw,Uw);return n?r.logs:r.logs[0]}async rename(e,t){await S(this.client,`/log/rename`,{key:e,name:t},Fw,Ww)}async setData(e,t){await S(this.client,`/log/set-data`,{key:e,data:t},Iw,Ww)}async retrieve(e){let t=zw.safeParse(e).success,n=await S(this.client,`/log/retrieve`,e,Bw,Vw);return X(`Log`,e,n.logs,t),t?n.logs[0]:n.logs}async delete(e){await S(this.client,`/log/delete`,{keys:w.toArray(e)},Lw,Ww)}},Kw=o({Client:()=>Gw,TYPE_ONTOLOGY_ID:()=>Pw,keyZ:()=>Aw,logZ:()=>jw,newZ:()=>Mw,ontologyID:()=>Nw,retrieveArgsZ:()=>Bw}),qw=l.z.object({range:Q,aliases:l.z.string().array()}),Jw=l.z.object({aliases:l.z.record(l.z.string(),Z)}),Yw=l.z.object({range:Q,aliases:l.z.record(Z,l.z.string())}),Xw=l.z.unknown(),Zw=l.z.object({range:Q,channels:Z.array()}),Qw=l.z.unknown(),$w=l.z.object({range:Q}),eT=l.z.object({aliases:l.z.record(l.z.string(),l.z.string())}),tT=l.z.object({range:Q,channels:Z.array()}),nT=l.z.object({aliases:l.z.record(l.z.string(),l.z.string())}),rT=class{cache=new Map;client;rangeKey;constructor(e,t){this.rangeKey=e,this.cache=new Map,this.client=t}async resolve(e){let t=[],n=typeof e==`string`,r={};if(n){let n=this.cache.get(e);if(n!=null)return n;t.push(e)}else e.forEach(e=>{let n=this.cache.get(e);n==null?t.push(e):r[e]=n});if(t.length===0)return r;let i=await S(this.client,`/range/alias/resolve`,{range:this.rangeKey,aliases:t},qw,Jw);return Object.entries(i.aliases).forEach(([e,t])=>this.cache.set(e,t)),n?i.aliases[t[0]]:{...r,...i.aliases}}async set(e){await S(this.client,`/range/alias/set`,{range:this.rangeKey,aliases:e},Yw,Xw)}async list(){return(await S(this.client,`/range/alias/list`,{range:this.rangeKey},$w,eT)).aliases}async retrieve(e){let t=typeof e==`number`,n=await S(this.client,`/range/alias/retrieve`,{range:this.rangeKey,channels:w.toArray(e)},tT,nT);return t?n.aliases[e]:n.aliases}async delete(e){await S(this.client,`/range/alias/delete`,{range:this.rangeKey,channels:w.toArray(e)},Zw,Qw)}},iT=`sy_range_alias_set`,aT=`sy_range_alias_delete`,oT=`---`,sT=e=>`${e.range}${oT}${e.channel}`,cT=(e,t)=>({type:`range-alias`,key:sT({range:e,channel:t})}),lT={type:`range-alias`,key:``},uT=e=>{let[t,n]=e.split(oT);return{range:t,channel:Number(n)}},dT=iT,fT=aT,pT=sT,mT=uT,hT=l.z.object({range:Q,channel:Z,alias:l.z.string()}),gT=o({Client:()=>rT,DELETE_ALIAS_CHANNEL_NAME:()=>fT,DELETE_CHANNEL_NAME:()=>aT,SET_ALIAS_CHANNEL_NAME:()=>dT,SET_CHANNEL_NAME:()=>iT,TYPE_ONTOLOGY_ID:()=>lT,aliasKey:()=>pT,aliasZ:()=>hT,createKey:()=>sT,decodeDeleteAliasChange:()=>mT,decodeDeleteChange:()=>uT,ontologyID:()=>cT}),_T=`sy_range_set`,vT=`sy_range_delete`,yT=class{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:t=A.ZERO,key:n,color:r,parent:i,labels:a},{frameClient:o,kv:s,aliaser:c,channels:l,labelClient:u,ontologyClient:d,rangeClient:f}){this.key=n,this.name=e,this.timeRange=t,this.parent=i,this.labels=a,this.frameClient=o,this.color=r,this.kv=s,this.aliaser=c,this.channels=l,this.labelClient=u,this.ontologyClient=d,this.rangeClient=f}get ontologyID(){return fb(this.key)}get payload(){let e={key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels};return this.parent!=null&&(`payload`in this.parent?e.parent=this.parent.payload:e.parent=this.parent),e}async setAlias(e,t){let n=await this.channels.retrieve(e);if(n.length===0)throw new Tu(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){let e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:[`range`]})).map(e=>e.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:fb(this.key)})}async addLabel(...e){await this.labelClient.label(fb(this.key),e)}async removeLabel(...e){await this.labelClient.remove(fb(this.key),e)}static sort(e,t){return A.sort(e.timeRange,t.timeRange)}},bT=l.z.object({keys:Q.array().optional(),names:l.z.string().array().optional(),searchTerm:l.z.string().optional(),overlapsWith:A.z.optional(),hasLabels:AC.array().optional(),limit:l.z.int().optional(),offset:l.z.int().optional(),includeLabels:l.z.boolean().optional(),includeParent:l.z.boolean().optional()}).or(Q.array().transform(e=>({keys:e}))).or(Q.transform(e=>({keys:[e]}))).or(l.z.string().transform(e=>({names:[e]}))).or(l.z.string().array().transform(e=>({names:e}))).or(A.z.transform(e=>({overlapsWith:e}))),xT=l.z.object({ranges:w.nullishToEmpty(ub)}),ST=class{type=`range`;frameClient;writer;unaryClient;channels;labelClient;ontologyClient;createAliasClient;createKVClient;constructor(e,t,n,r,i,a,o,s){this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=r,this.labelClient=i,this.ontologyClient=a,this.createAliasClient=o,this.createKVClient=s}async create(e,t){let n=!Array.isArray(e),r=this.sugarMany(await this.writer.create(w.toArray(e),t));return n?r[0]:r}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(w.toArray(e))}async retrieve(e){let t=typeof e==`string`,{ranges:n}=await S(this.unaryClient,`/range/retrieve`,e,bT,xT);return X(`Range`,e,n,t),t?this.sugarMany(n)[0]:this.sugarMany(n)}getKV(e){return this.createKVClient(e)}async retrieveParent(e){let t=await this.ontologyClient.retrieveParents(fb(e));if(t.length===0)return null;let n=t[0];return n.id.type===`range`?await this.retrieve(n.id.key):null}sugarOntologyResource(e){return this.sugarOne(wT(e))}async retrieveAlias(e,t){return await this.createAliasClient(e).retrieve(t)}async retrieveAliases(e,t){return await this.createAliasClient(e).retrieve(t)}async listAliases(e){return await this.createAliasClient(e).list()}async setAlias(e,t,n){await this.createAliasClient(e).set({[t]:n})}async deleteAlias(e,t){await this.createAliasClient(e).delete(t)}sugarOne(e){return new yT(e,{frameClient:this.frameClient,kv:this.createKVClient(e.key),aliaser:this.createAliasClient(e.key),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(e){return e.map(e=>this.sugarOne(e))}resourceToRange(e){return this.sugarOne(wT(e))}},CT=e=>({type:`range-alias`,key:e}),wT=({data:e,id:{key:t},name:n})=>{let r=A.z.parse(e?.timeRange),i=Nc.colorZ.safeParse(e?.color);return{key:t,name:n,timeRange:r,color:i.success?i.data:void 0,labels:[],parent:void 0}},TT=l.z.object({range:Q,key:l.z.string(),value:l.z.string()}),ET=l.z.object({range:Q,keys:l.z.string().array()}),DT=l.z.object({pairs:w.nullishToEmpty(TT)}),OT=l.z.object({range:Q,pairs:TT.array()}),kT=l.z.object({range:Q,keys:l.z.string().array()}),AT=class{rangeKey;client;constructor(e,t){this.rangeKey=e,this.client=t}async get(e){let t=await S(this.client,`/range/kv/get`,{range:this.rangeKey,keys:w.toArray(e)},ET,DT);return typeof e==`string`?t.pairs[0].value:Object.fromEntries(t.pairs.map(e=>[e.key,e.value]))}async list(){return this.get([])}async set(e,t=``){let n;n=typeof e==`string`?[{range:this.rangeKey,key:e,value:t}]:Object.entries(e).map(([e,t])=>({range:this.rangeKey,key:e,value:t})),await S(this.client,`/range/kv/set`,{range:this.rangeKey,pairs:n},OT,l.z.unknown())}async delete(e){await S(this.client,`/range/kv/delete`,{range:this.rangeKey,keys:w.toArray(e)},kT,l.z.unknown())}},jT=`sy_range_kv_set`,MT=`sy_range_kv_delete`,NT=({range:e,key:t})=>`${e}<--->${t}`,PT=jT,FT=MT,IT=TT,LT=NT,RT=o({Client:()=>AT,DELETE_CHANNEL_NAME:()=>MT,KV_DELETE_CHANNEL:()=>FT,KV_SET_CHANNEL:()=>PT,SET_CHANNEL_NAME:()=>jT,createPairKey:()=>NT,kvPairKey:()=>LT,kvPairZ:()=>IT,pairZ:()=>TT}),zT=l.z.string().min(1),BT=l.z.object({ranges:ub.array()}),VT=l.z.object({parent:R.optional(),ranges:db.array()}),HT=l.z.object({keys:Q.array()}),UT=l.z.object({}),WT=l.z.object({key:Q,name:zT}),GT=l.z.object({}),KT=class{client;constructor(e){this.client=e}async rename(e,t){await S(this.client,`/range/rename`,{key:e,name:t},WT,GT)}async create(e,t){return(await S(this.client,`/range/create`,{ranges:e,...t},VT,BT)).ranges}async delete(e){await S(this.client,`/range/delete`,{keys:e},HT,UT)}},qT=o({Client:()=>ST,DELETE_ALIAS_CHANNEL_NAME:()=>aT,DELETE_CHANNEL_NAME:()=>vT,KV_DELETE_CHANNEL:()=>MT,KV_SET_CHANNEL:()=>jT,Range:()=>yT,SET_ALIAS_CHANNEL_NAME:()=>iT,SET_CHANNEL_NAME:()=>_T,TYPE_ONTOLOGY_ID:()=>pb,Writer:()=>KT,alias:()=>gT,aliasKey:()=>sT,aliasOntologyID:()=>CT,apiRangeZ:()=>lb,baseZ:()=>cb,convertOntologyResourceToPayload:()=>wT,decodeDeleteAliasChange:()=>uT,keyZ:()=>Q,kv:()=>RT,kvPairKey:()=>NT,nameZ:()=>zT,newZ:()=>db,ontologyID:()=>fb,payloadZ:()=>ub}),JT=l.z.object({key:l.z.string(),name:l.z.string(),selectors:w.nullishToEmpty(l.z.string()),strokeColor:l.z.string().optional(),fillColor:l.z.string().optional()}),YT=l.z.object({key:l.z.string(),position:xo.xyZ,orientation:xo.outerLocationZ}),XT=l.z.object({zoom:l.z.number().default(1),position:xo.xyZ}),ZT=l.z.uuid(),QT=l.z.object({key:l.z.string(),name:l.z.string(),regions:w.nullishToEmpty(JT)}),$T=l.z.object({svg:l.z.string().min(1),states:w.nullishToEmpty(QT),variant:l.z.string().min(1),handles:w.nullishToEmpty(YT),scale:l.z.number().default(1),scaleStroke:l.z.boolean().default(!1),previewViewport:XT.optional()}),eE=l.z.object({key:ZT,version:l.z.uint32().default(1),name:l.z.string().min(1),data:$T}),tE=l.z.object({key:ZT.optional(),version:l.z.uint32().default(1),name:l.z.string().min(1),data:$T}),nE=z(`schematic_symbol`),rE=nE(``),iE=l.z.object({symbols:tE.array(),parent:R}),aE=l.z.object({key:ZT,name:l.z.string()}),oE=l.z.object({keys:ZT.array()}),sE=l.z.object({keys:ZT.array().optional(),searchTerm:l.z.string().optional()}),cE=l.z.object({key:ZT}).transform(({key:e})=>({keys:[e]})),lE=l.z.union([cE,sE]),uE=l.z.object({symbols:w.nullishToEmpty(eE)}),dE=l.z.object({symbols:eE.array()}),fE=l.z.object({}),pE=l.z.object({}),mE=l.z.object({group:Sb}),hE=`sy_schematic_symbol_set`,gE=`sy_schematic_symbol_delete`,_E=class{client;constructor(e){this.client=e}async create(e){let t=`symbols`in e,n=t?e.symbols:[e],r=await S(this.client,`/schematic/symbol/create`,{symbols:n,parent:e.parent},iE,dE);return t?r.symbols:r.symbols[0]}async rename(e,t){await S(this.client,`/schematic/symbol/rename`,{key:e,name:t},aE,fE)}async retrieve(e){let t=`key`in e,n=await S(this.client,`/schematic/symbol/retrieve`,e,lE,uE);return X(`Schematic Symbol`,e,n.symbols,t),t?n.symbols[0]:n.symbols}async delete(e){await S(this.client,`/schematic/symbol/delete`,{keys:w.toArray(e)},oE,fE)}async retrieveGroup(){return(await S(this.client,`/schematic/symbol/retrieve-group`,{},pE,mE)).group}},vE=o({Client:()=>_E,DELETE_CHANNEL_NAME:()=>gE,SET_CHANNEL_NAME:()=>hE,TYPE_ONTOLOGY_ID:()=>rE,handleZ:()=>YT,keyZ:()=>ZT,newZ:()=>tE,ontologyID:()=>nE,regionZ:()=>JT,specZ:()=>$T,stateZ:()=>QT,symbolZ:()=>eE,viewportZ:()=>XT}),yE=l.z.uuid(),bE=l.z.object({key:yE,name:l.z.string(),data:Hr.preserveCase(I.nullishToEmpty()),snapshot:l.z.boolean()}),xE=bE.partial({key:!0,snapshot:!0}),SE=z(`schematic`),CE=SE(``),wE=l.z.object({key:yE,name:l.z.string()}),TE=l.z.object({key:yE,data:Hr.preserveCase(I.unknownZ())}),EE=l.z.object({keys:yE.array()}),DE=l.z.object({key:yE,name:l.z.string(),snapshot:l.z.boolean()}),OE=l.z.object({keys:yE.array()}),kE=l.z.object({key:yE}).transform(({key:e})=>({keys:[e]})),AE=l.z.union([kE,OE]),jE=l.z.object({schematics:bE.array()}),ME=l.z.object({workspace:tw,schematics:xE.array()}),NE=l.z.object({schematics:bE.array()}),PE=l.z.object({schematic:bE}),FE=l.z.object({}),IE=class{symbols;client;constructor(e){this.client=e,this.symbols=new _E(e)}async create(e,t){let n=Array.isArray(t),r=await S(this.client,`/schematic/create`,{workspace:e,schematics:w.toArray(t)},ME,NE);return n?r.schematics:r.schematics[0]}async rename(e,t){await S(this.client,`/schematic/rename`,{key:e,name:t},wE,FE)}async setData(e,t){await S(this.client,`/schematic/set-data`,{key:e,data:t},TE,FE)}async retrieve(e){let t=kE.safeParse(e).success,n=await S(this.client,`/schematic/retrieve`,e,AE,jE);return X(`Schematic`,e,n.schematics,t),t?n.schematics[0]:n.schematics}async delete(e){await S(this.client,`/schematic/delete`,{keys:w.toArray(e)},EE,FE)}async copy(e){return(await S(this.client,`/schematic/copy`,e,DE,PE)).schematic}},LE=o({Client:()=>IE,TYPE_ONTOLOGY_ID:()=>CE,keyZ:()=>yE,newZ:()=>xE,ontologyID:()=>SE,retrieveArgsZ:()=>AE,schematicZ:()=>bE,symbol:()=>vE}),RE=l.z.string(),zE=e=>cu.statusZ({details:e}),BE=e=>cu.newZ({details:e}).omit({labels:!0}),VE=`sy_status_set`,HE=`sy_status_delete`,UE=z(`status`),WE=UE(``),GE=e=>l.default.object({parent:R.optional(),statuses:BE(e).array()}),KE=e=>l.default.object({statuses:zE(e).array()}),qE=l.default.object({keys:RE.array()}),JE=l.default.object({}),YE=l.default.object({keys:RE.array().optional(),searchTerm:l.default.string().optional(),offset:l.default.int().optional(),limit:l.default.int().optional(),includeLabels:l.default.boolean().optional(),hasLabels:AC.array().optional(),variants:l.default.string().array().optional()}),XE=l.default.object({key:RE,includeLabels:l.default.boolean().optional()}).transform(({key:e,includeLabels:t})=>({keys:[e],includeLabels:t})),ZE=l.default.union([XE,YE]),QE=e=>l.default.object({statuses:w.nullishToEmpty(zE(e))}),$E=class{type=`status`;client;constructor(e){this.client=e}async retrieve(e){let t=`key`in e,n=await S(this.client,`/status/retrieve`,e,ZE,QE(e.detailsSchema));X(`Status`,e,n.statuses,t);let r=n.statuses;return t?r[0]:r}async set(e,t={}){let n=Array.isArray(e),r=(await S(this.client,`/status/set`,{statuses:w.toArray(e),parent:t.parent},GE(t.detailsSchema),KE(t.detailsSchema))).statuses;return n?r:r[0]}async delete(e){await S(this.client,`/status/delete`,{keys:w.toArray(e)},qE,JE)}},eD=o({Client:()=>$E,DELETE_CHANNEL_NAME:()=>HE,SET_CHANNEL_NAME:()=>VE,TYPE_ONTOLOGY_ID:()=>WE,keyZ:()=>RE,newZ:()=>BE,ontologyID:()=>UE,statusZ:()=>zE}),tD=l.z.uuid(),nD=l.z.object({key:tD,name:l.z.string(),data:Hr.preserveCase(I.nullishToEmpty())}),rD=nD.partial({key:!0}),iD=z(`table`),aD=iD(``),oD=l.z.object({key:tD,name:l.z.string()}),sD=l.z.object({key:tD,data:Hr.preserveCase(I.unknownZ())}),cD=l.z.object({keys:tD.array()}),lD=l.z.object({keys:tD.array()}),uD=l.z.object({key:tD}).transform(({key:e})=>({keys:[e]})),dD=l.z.union([uD,lD]),fD=l.z.object({tables:w.nullishToEmpty(nD)}),pD=l.z.object({workspace:tw,tables:rD.array()}),mD=l.z.object({tables:nD.array()}),hD=l.z.object({}),gD=class{client;constructor(e){this.client=e}async create(e,t){let n=Array.isArray(t),r=await S(this.client,`/table/create`,{workspace:e,tables:w.toArray(t)},pD,mD);return n?r.tables:r.tables[0]}async rename(e,t){await S(this.client,`/table/rename`,{key:e,name:t},oD,hD)}async setData(e,t){await S(this.client,`/table/set-data`,{key:e,data:t},sD,hD)}async retrieve(e){let t=uD.safeParse(e).success,n=await S(this.client,`/table/retrieve`,e,dD,fD);return X(`Table`,e,n.tables,t),t?n.tables[0]:n.tables}async delete(e){await S(this.client,`/table/delete`,{keys:w.toArray(e)},cD,hD)}},_D=o({Client:()=>gD,TYPE_ONTOLOGY_ID:()=>aD,keyZ:()=>tD,newZ:()=>rD,ontologyID:()=>iD,retrieveArgsZ:()=>dD,tableZ:()=>nD}),vD=l.z.string().or(l.z.number().transform(String).or(l.z.bigint().transform(String))),yD=e=>l.z.object({task:vD,running:l.z.boolean(),cmd:l.z.string().optional(),data:e??l.z.unknown().optional()}),bD=e=>l.z.object({task:vD.optional(),running:l.z.boolean(),cmd:l.z.string().optional(),data:e??l.z.unknown().optional()}),xD=l.z.object({task:vD,type:l.z.string(),key:l.z.string(),args:Hr.preserveCase(N.nullToUndefined(I.unknownZ()))}),SD=e=>cu.statusZ({details:yD(e)}),CD=e=>cu.newZ({details:bD(e)}),wD=({type:e,config:t,statusData:n}={})=>l.z.object({key:vD,name:l.z.string(),type:e??l.z.string(),config:t??I.nullishToEmpty(),internal:l.z.boolean().optional(),snapshot:l.z.boolean().optional(),status:cu.statusZ({details:yD(n)}).optional()}),TD=({type:e,config:t,statusData:n}={})=>wD({type:e,config:t,statusData:n}).omit({internal:!0,snapshot:!0,status:!0}).partial({key:!0}).extend({status:cu.newZ({details:bD(n)}).optional()}),ED=z(`task`),DD=ED(``),OD=`sy_task_cmd`,kD=`sy_task_set`,AD=`sy_task_delete`,jD=Error(`Task not created`),MD=e=>Number(BigInt(e)>>32n),ND=(e,t=0)=>((BigInt(e)<<32n)+BigInt(t)).toString(),PD=async(e,t)=>{let n=await t.retrieveParents(ED(e));return n.length===0?null:n[0]},FD=class{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw jD;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw jD;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw jD;return this.rangeClient_}constructor({key:e,type:t,name:n,config:r,internal:i=!1,snapshot:a=!1,status:o},s,c,u,d){this.key=e,this.name=n,this.type=t,this.config=r,this.schemas=s??{type:l.z.string(),config:l.z.unknown(),statusData:l.z.unknown()},this.internal=i,this.snapshot=a,this.status=o,this.frameClient_=c,this.ontologyClient_=u,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 ED(this.key)}async executeCommand(e){return await YD({...e,frameClient:this.frameClient,task:this.key})}async executeCommandSync(e){return await ZD({...e,frameClient:this.frameClient,task:this.key,name:this.name,statusDataZ:this.schemas.statusData})}async start(){await this.executeCommand({type:`start`})}async stop(){await this.executeCommand({type:`stop`})}async run(e){await this.start();try{return await e()}finally{await this.stop()}}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw jD;return this.snapshot?await PD(this.key,this.ontologyClient):null}},ID=l.z.object({rack:VS.optional(),keys:vD.array().optional(),names:l.z.string().array().optional(),types:l.z.string().array().optional(),includeStatus:l.z.boolean().optional(),internal:l.z.boolean().optional(),snapshot:l.z.boolean().optional(),searchTerm:l.z.string().optional(),offset:l.z.int().optional(),limit:l.z.int().optional()}),LD=l.z.union([l.z.object({key:vD,includeStatus:l.z.boolean().optional()}).transform(({key:e,includeStatus:t})=>({keys:[e],includeStatus:t})),l.z.object({name:l.z.string(),includeStatus:l.z.boolean().optional()}).transform(({name:e,includeStatus:t})=>({names:[e],includeStatus:t})),l.z.object({type:l.z.string(),rack:VS.optional()}).transform(({type:e,rack:t})=>({types:[e],rack:t}))]),RD=ID,zD=l.z.union([LD,RD]),BD=e=>l.z.object({tasks:w.nullishToEmpty(wD(e))}),VD=e=>l.z.object({tasks:TD(e).array()}),HD=e=>l.z.object({tasks:wD(e).array()}),UD=l.z.object({keys:vD.array()}),WD=l.z.object({}),GD=l.z.object({key:vD,name:l.z.string(),snapshot:l.z.boolean()}),KD=e=>l.z.object({task:wD(e)}),qD=class{client;frameClient;ontologyClient;rangeClient;constructor(e,t,n,r){this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=r}async create(e,t){let n=!Array.isArray(e),r=VD(t),i=HD(t),a=await S(this.client,`/task/create`,{tasks:w.toArray(e)},r,i),o=this.sugar(a.tasks,t);return n?o[0]:o}async delete(e){await S(this.client,`/task/delete`,{keys:w.toArray(e)},UD,WD)}async retrieve({schemas:e,...t}){let n=LD.safeParse(t).success,r=(await S(this.client,`/task/retrieve`,t,zD,BD(e))).tasks,i=this.sugar(r,e);return X(`Task`,t,i,n),n?i[0]:i}async copy(e,t,n){let r=KD(),i=await S(this.client,`/task/copy`,{key:e,name:t,snapshot:n},GD,r);return this.sugar(i.task)}async list(e){let t={internal:!1};return e!==void 0&&(t.rack=e),await this.retrieve(t)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw jD;return await PD(e,this.ontologyClient)}sugar(e,t){let n=!Array.isArray(e),r=w.toArray(e).map(({key:e,name:n,type:r,config:i,status:a,internal:o,snapshot:s})=>new FD({key:e,name:n,type:r,config:i,internal:o,snapshot:s,status:a},t,this.frameClient,this.ontologyClient,this.rangeClient));return n?r[0]:r}async executeCommand(e){return`commands`in e?await XD({...e,frameClient:this.frameClient}):await YD({...e,frameClient:this.frameClient})}async executeCommandSync(e){if(`commands`in e){let t=async()=>{let{commands:t}=e;return(await this.retrieve({keys:t.map(e=>e.task)})).map(e=>e.name)};return await QD({...e,frameClient:this.frameClient,name:t})}return await ZD({frameClient:this.frameClient,name:async()=>{let{task:t}=e;return(await this.retrieve({key:t})).name},...e})}},JD=e=>Ru(ED(e)),YD=async({frameClient:e,task:t,type:n,args:r})=>(await XD({frameClient:e,commands:[{args:r,task:t,type:n}]}))[0],XD=async({frameClient:e,commands:t})=>{if(e==null)throw jD;let n=await e.openWriter(OD),r=t.map(e=>({...e,key:Li.create()}));return await n.write(OD,r),await n.close(),r.map(e=>e.key)},ZD=async({frameClient:e,task:t,type:n,timeout:r,name:i,statusDataZ:a,args:o})=>(await QD({frameClient:e,commands:[{args:o,task:t,type:n}],timeout:r,statusDataZ:a,name:i}))[0],QD=async({frameClient:e,commands:t,timeout:n=O.seconds(10),statusDataZ:r,name:i})=>{if(e==null)throw jD;let a=await e.openStreamer(VE),o=await XD({frameClient:e,commands:t}),s=new O(n),c=[],l,u=new Promise((e,n)=>{l=setTimeout(()=>{(async()=>{n(await $D(`command`,i,s,t.map(e=>e.task)))})()},s.milliseconds)});try{for(;;){let e=await Promise.race([a.read(),u]),t=SD(r).safeParse(e.at(-1)[VE]);if(!t.success)continue;let n=t.data;if(!(n.details.cmd==null||!o.includes(n.details.cmd))&&(c=[...c.filter(e=>e.key!==n.key),n],c.length===o.length))return c}}finally{clearTimeout(l),a.close()}},$D=async(e,t,n,r)=>{let i=Hr.capitalize(e),a=n.toString();try{let e;e=typeof t==`string`?[t]:Array.isArray(t)?t:w.toArray(await t());let n=mu.naturalLanguageJoin(e);return Error(`${i} command to ${n} timed out after ${a}`)}catch(e){return console.error(`Failed to retrieve task name for timeout error:`,e),Error(`${i} command to task with key ${mu.naturalLanguageJoin(w.toArray(r).map(e=>e.toString()))} timed out after ${a}`)}},eO=o({COMMAND_CHANNEL_NAME:()=>OD,Client:()=>qD,DELETE_CHANNEL_NAME:()=>AD,SET_CHANNEL_NAME:()=>kD,TYPE_ONTOLOGY_ID:()=>DD,Task:()=>FD,commandZ:()=>xD,keyZ:()=>vD,newKey:()=>ND,newStatusDetailsZ:()=>bD,newStatusZ:()=>CD,newZ:()=>TD,ontologyID:()=>ED,payloadZ:()=>wD,rackKey:()=>MD,statusDetailsZ:()=>yD,statusKey:()=>JD,statusZ:()=>SD}),tO=class{url;unary;stream;secure;constructor(e,t={},n=!1){this.secure=n,this.url=e.child(`/api/v1/`);let r=new ai.JSONCodec;this.unary=kr(new Or(this.url,r,this.secure),t),this.stream=new Pr(this.url,r,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}},nO=l.z.uuid(),rO=l.z.object({key:nO,name:l.z.string(),type:l.z.string(),query:I.nullishToEmpty()}),iO=rO.partial({key:!0}),aO=z(`view`),oO=aO(``),sO=`sy_view_set`,cO=`sy_view_delete`,lO=l.z.object({views:iO.array()}),uO=l.z.object({views:rO.array()}),dO=l.z.object({keys:nO.array()}),fO=l.z.object({}),pO=l.z.object({keys:nO.array().optional(),types:l.z.string().array().optional(),searchTerm:l.z.string().optional(),offset:l.z.number().optional(),limit:l.z.number().optional()}),mO=l.z.object({key:nO}).transform(({key:e})=>({keys:[e]})),hO=l.z.union([mO,pO]),gO=l.z.object({views:w.nullishToEmpty(rO)}),_O=class{client;constructor(e){this.client=e}async retrieve(e){let t=`key`in e,n=await S(this.client,`/view/retrieve`,e,hO,gO);return X(`View`,e,n.views,t),t?n.views[0]:n.views}async create(e){let t=Array.isArray(e),n=await S(this.client,`/view/create`,{views:w.toArray(e)},lO,uO);return t?n.views:n.views[0]}async delete(e){await S(this.client,`/view/delete`,{keys:w.toArray(e)},dO,fO)}},vO=o({Client:()=>_O,DELETE_CHANNEL_NAME:()=>cO,SET_CHANNEL_NAME:()=>sO,TYPE_ONTOLOGY_ID:()=>oO,keyZ:()=>nO,newZ:()=>iO,ontologyID:()=>aO,viewZ:()=>rO}),yO=l.z.object({host:l.z.string({error:`Host is required`}).min(1,`Host is required`),port:l.z.number({error:`Port is required`}).or(l.z.string({error:`Port is required`})),username:l.z.string().min(1,`Username is required`),password:l.z.string().min(1,`Password is required`),connectivityPollFrequency:O.z.default(O.seconds(30)),secure:l.z.boolean().default(!1),name:l.z.string().optional(),retry:fs.breakerConfigZ.optional()}),bO=class extends AS{createdAt;params;ranges;channels;auth;users;access;connectivity;ontology;workspaces;labels;statuses;tasks;racks;devices;control;arcs;views;schematics;lineplots;logs;tables;groups;static connectivity=mx;transport;clientVersion=`0.54.0`;constructor(e){let t=yO.parse(e),{host:n,port:r,username:i,password:a,connectivityPollFrequency:o,secure:s,retry:c}=t,l=new tO(new vu({host:n,port:Number(r)}),c,s);l.use(Nu);let u=new vb(new _b(l.unary));super(l.stream,l.unary,u),this.auth=new ox(l.unary,{username:i,password:a}),l.use(this.auth.middleware());let d=new Zb(l.unary,u);this.createdAt=D.now(),this.params=t,this.transport=l,this.channels=new Rb(this,u,l.unary,d),this.connectivity=new mx(l.unary,o,this.clientVersion,t.name),this.control=new zS(this),this.ontology=new $u(this.transport.unary);let f=new KT(this.transport.unary);this.labels=new KC(this.transport.unary),this.statuses=new $E(this.transport.unary),this.ranges=new ST(this,f,this.transport.unary,u,this.labels,this.ontology,e=>new rT(e,this.transport.unary),e=>new AT(e,this.transport.unary)),this.access=new vf(this.transport.unary),this.users=new Yd(this.transport.unary),this.workspaces=new gw(this.transport.unary),this.tasks=new qD(this.transport.unary,this,this.ontology,this.ranges),this.racks=new oC(this.transport.unary,this.tasks),this.devices=new DC(this.transport.unary),this.arcs=new By(this.transport.unary,this.transport.stream),this.views=new _O(this.transport.unary),this.schematics=new IE(this.transport.unary),this.lineplots=new Ow(this.transport.unary),this.logs=new Gw(this.transport.unary),this.tables=new gD(this.transport.unary),this.groups=new jb(this.transport.unary)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stop()}},xO=async e=>await SO(e).check(),SO=e=>{let{host:t,port:n,secure:r,name:i,retry:a}=e,o=fs.breakerConfigZ.optional().parse(a);return new mx(new tO(new vu({host:t,port:Number(n)}),o,r).unary,void 0,`0.54.0`,i)},CO={host:`localhost`,port:9090,username:`synnax`,password:`seldon`,retry:{maxRetries:4,baseInterval:O.seconds(1),scale:1.5}},wO=e=>new bO({...CO,...e}),TO=async(e,t)=>{let n=Li.create(),r=await e.users.create({username:n,password:`test`,firstName:`test`,lastName:`test`}),i=await e.access.policies.create(t),a=await e.access.roles.create({name:`test`,description:`test`});return await e.ontology.addChildren(Od(a.key),cd(i.key)),await e.access.roles.assign({user:r.key,role:a.key}),wO({username:n,password:`test`})};exports.AuthError=xu,exports.Channel=Fb,exports.ContiguityError=Mu,exports.DataType=j,exports.Density=k,exports.DisconnectedError=ju,exports.Frame=$,exports.MultiSeries=os,exports.MultipleFoundError=Du,exports.NotFoundError=Eu,exports.QueryError=Tu,exports.Rate=Do,exports.RouteError=Ou,exports.Series=Qo,exports.Synnax=bO,exports.TEST_CLIENT_PARAMS=CO,exports.TimeRange=A,exports.TimeSpan=O,exports.TimeStamp=D,exports.UnexpectedError=wu,exports.ValidationError=L,Object.defineProperty(exports,`access`,{enumerable:!0,get:function(){return bf}}),Object.defineProperty(exports,`arc`,{enumerable:!0,get:function(){return Uy}}),Object.defineProperty(exports,`channel`,{enumerable:!0,get:function(){return Qb}}),exports.checkConnection=xO,Object.defineProperty(exports,`connection`,{enumerable:!0,get:function(){return sx}}),Object.defineProperty(exports,`control`,{enumerable:!0,get:function(){return BS}}),exports.createTestClient=wO,exports.createTestClientWithPolicy=TO,Object.defineProperty(exports,`device`,{enumerable:!0,get:function(){return kC}}),Object.defineProperty(exports,`framer`,{enumerable:!0,get:function(){return jS}}),Object.defineProperty(exports,`group`,{enumerable:!0,get:function(){return Mb}}),exports.isCalculated=zb,Object.defineProperty(exports,`label`,{enumerable:!0,get:function(){return YC}}),Object.defineProperty(exports,`lineplot`,{enumerable:!0,get:function(){return kw}}),Object.defineProperty(exports,`log`,{enumerable:!0,get:function(){return Kw}}),exports.newConnectionChecker=SO,Object.defineProperty(exports,`ontology`,{enumerable:!0,get:function(){return id}}),Object.defineProperty(exports,`rack`,{enumerable:!0,get:function(){return lC}}),Object.defineProperty(exports,`ranger`,{enumerable:!0,get:function(){return qT}}),Object.defineProperty(exports,`schematic`,{enumerable:!0,get:function(){return LE}}),Object.defineProperty(exports,`status`,{enumerable:!0,get:function(){return eD}}),exports.synnaxParamsZ=yO,Object.defineProperty(exports,`table`,{enumerable:!0,get:function(){return _D}}),Object.defineProperty(exports,`task`,{enumerable:!0,get:function(){return eO}}),Object.defineProperty(exports,`user`,{enumerable:!0,get:function(){return Qd}}),Object.defineProperty(exports,`view`,{enumerable:!0,get:function(){return vO}}),Object.defineProperty(exports,`workspace`,{enumerable:!0,get:function(){return _w}});
100
+ `,i=new TextEncoder,a=!1,o=!1,s=lC(t),{columns:c,columnsByIndexKey:l,emptyGroupStrings:u}=uC(t,s,n),d=[],f=0,p=[],m=e=>{for(let[t]of s){let n=e.get(t);if(n.length===0)continue;let r=(l.get(t)??[]).map(t=>e.get(t.key));for(let e=0;e<n.length;e++){let i=n.at(e,!0),a=r.map(t=>lu.formatValue(t.at(e,!0)));p.push({time:i,values:a,indexKey:t})}}},h=(e,t=!1)=>{p.length>0&&(p.sort((e,t)=>Number(e.time-t.time)),f>0&&(d=d.slice(f),f=0),d=dC(d,p),p=[]);let n=[],r=d.length;for(;f<r&&n.length<e;){let e=d[f].time;if(!t&&d[r-1].time===e)break;let i=new Map;for(;f<r&&d[f].time===e;){let e=d[f++];i.set(e.indexKey,e)}let a=[];for(let[e]of s){let t=i.get(e);a.push(t?.values.join(`,`)??u.get(e)??``)}n.push(a.join(`,`))}return n};return new ReadableStream({async pull(t){try{if(o||=(await e.seekFirst(),!0),!a){let e=c.map(e=>lu.formatValue(e.header)).join(`,`);t.enqueue(i.encode(`${e}${r}`)),a=!0}d.length-f+p.length<fC&&await e.next()&&m(e.value);let n=h(fC);if(n.length>0&&t.enqueue(i.encode(`${n.join(r)}${r}`)),d.length-f===0||p.length===0){if(!await e.next()){let n=h(1/0,!0);n.length>0&&t.enqueue(i.encode(`${n.join(r)}${r}`)),await e.close(),t.close();return}m(e.value)}}catch(n){await e.close(),t.error(n)}},async cancel(){await e.close()}})},lC=e=>{let t=new Map;for(let n of e){if(n.index===0)continue;let e=t.get(n.index);e??(e=[n.index],t.set(n.index,e)),!n.isIndex&&!e.includes(n.key)&&e.push(n.key)}return t},uC=(e,t,n)=>{let r=new Map(e.map(e=>[e.key,e])),i=[],a=new Map,o=new Map;for(let[e,s]of t){let t=[];for(let e of s){let a=r.get(e);if(a==null)throw new Ad(`Channel ${e} not found`);let o={key:e,header:n?.[e]??n?.[a.name]??a.name};i.push(o),t.push(o)}a.set(e,t),o.set(e,`,`.repeat(t.length-1))}return{columns:i,columnsByIndexKey:a,emptyGroupStrings:o}},dC=(e,t)=>{let n=[],r=0,i=0;for(;r<e.length&&i<t.length;)e[r].time<=t[i].time?n.push(e[r++]):n.push(t[i++]);return n.push(...e.slice(r),...t.slice(i)),n},fC=1e3,pC=l.z.object({keys:l.z.number().array(),downsampleFactor:l.z.int(),throttleRate:dc.z.optional(),excludeGroups:l.z.uint32().array().optional()}),mC=l.z.object({frame:ES}),hC=l.z.object({channels:Kx,downsampleFactor:l.z.int().default(1),throttleRate:dc.z.default(new dc(0)),useHighPerformanceCodec:l.z.boolean().default(!0),excludeGroups:l.z.uint32().array().default([])}),gC=hC.or(Kx.transform(e=>hC.parse({channels:e}))),_C=(e,t)=>async n=>{let r=gC.parse(n),i=await ZS.open(e,r.channels);r.useHighPerformanceCodec&&(t=t.withCodec(new XS(i.codec)));let a=await t.stream(`/frame/stream`,pC,mC),o=new yC(a,i,r.downsampleFactor,r.throttleRate,r.excludeGroups);a.send({keys:Array.from(i.keys),downsampleFactor:r.downsampleFactor,throttleRate:r.throttleRate,excludeGroups:r.excludeGroups});let[,s]=await a.receive();if(s!=null)throw s;return o},vC=async(e,t,n)=>await _C(e,t)(n),yC=class{stream;adapter;downsampleFactor;throttleRate;excludeGroups;constructor(e,t,n=1,r=new dc(0),i=[]){this.stream=new $S(`Streamer`,e),this.adapter=t,this.downsampleFactor=n,this.throttleRate=r,this.excludeGroups=i}get keys(){return Array.from(this.adapter.keys)}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Yr.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new $((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,excludeGroups:this.excludeGroups})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}},bC=class e{wrapped_=null;breaker;opener;config;constructor(e,t,n={}){this.opener=e,this.config=gC.parse(t);let{maxRetries:r=5e3,baseInterval:i=k.seconds(1),scale:a=1}=n??{};this.breaker=new Xc.Breaker({maxRetries:r,baseInterval:i,scale:a})}static async open(t,n,r){let i=new e(t,n,r);return await i.runStreamer(),i}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 Error(`stream closed`);return this.wrapped_}async update(e){this.config.channels=Kx.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(Yr.matches(e))return{done:!0,value:void 0};throw e}}async read(){try{let e=await this.wrapped.read();return this.breaker.reset(),e}catch(e){if(Yr.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}},xC=class extends Du.Observer{streamer;closePromise;constructor(e,t){super(t),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(let e of this.streamer)this.notify(e)}},SC=function(e){return e[e.PersistStream=1]=`PersistStream`,e[e.Persist=2]=`Persist`,e[e.Stream=3]=`Stream`,e}({}),CC=new k(-1),wC=class extends Td.sub(`writer_closed`){constructor(){super(`WriterClosed`)}},TC=l.z.enum(SC).or(l.z.enum([`persist`,`stream`,`persistStream`]).transform(e=>{switch(e){case`persist`:return SC.Persist;case`stream`:return SC.Stream;case`persistStream`:return SC.PersistStream}})),EC=l.z.object({start:O.z.optional(),controlSubject:F.subjectZ.optional(),authorities:l.z.union([F.authorityZ.transform(e=>[e]),F.authorityZ.array()]).default([F.ABSOLUTE_AUTHORITY]),mode:TC.default(SC.PersistStream),errOnUnauthorized:l.z.boolean().default(!1),enableAutoCommit:l.z.boolean().default(!0),autoIndexPersistInterval:k.z.default(k.SECOND),useHighPerformanceCodec:l.z.boolean().default(!0)}),DC=EC.extend({keys:Z.array().optional()}),OC=EC.extend({channels:Kx}),kC=OC.or(Kx.transform(e=>OC.parse({channels:e,start:O.now()}))),AC=l.z.object({command:l.z.enum(kS),config:DC.optional(),frame:ES.optional(),buffer:l.z.instanceof(Uint8Array).optional()}),jC=l.z.object({command:l.z.enum(kS),end:O.z,err:Gi.payloadZ.optional()}),MC=l.z.tuple([l.z.union([l.z.record(Z.or(cx),F.authorityZ),Z.or(cx),F.authorityZ]),F.authorityZ.optional()]).transform(([e,t])=>{if(F.authorityZ.safeParse(e).success)return{keys:[],authorities:[e]};if(Z.or(cx).safeParse(e).success){if(t==null)throw Error(`authority is required when setting authority for a single channel`);return{keys:[e],authorities:[t]}}let n=e;return{keys:Object.keys(n),authorities:Object.values(n)}}),NC=class e{stream;adapter;closeErr=null;constructor(e,t){this.stream=e,this.adapter=t}static async _open(t,n,r){let i=D.parse(kC,r),a=await QS.open(t,i.channels);i.useHighPerformanceCodec&&(n=n.withCodec(new YS(a.codec)));let o=new e(await n.stream(`/frame/write`,AC,jC),a);return await o.execute({command:kS.Open,config:{...i,keys:a.keys}}),o}async write(e,t){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();let n=await this.adapter.adapt(e,t);this.stream.send({command:kS.Write,frame:n.toPayload()})}async setAuthority(e,t){if(this.closeErr!=null)throw this.closeErr;let n=MC.parse([e,t]),r={keys:await this.adapter.adaptParams(n.keys),authorities:n.authorities};await this.execute({command:kS.SetAuthority,config:r})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),O.ZERO):(await this.execute({command:kS.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(wC.matches(this.closeErr))return null;throw this.closeErr}let[e,t]=await this.stream.receive();t==null?this.closeErr=Gi.decode(e?.err):this.closeErr=Yr.matches(t)?new wC:t}}async execute(e){let t=this.stream.send(e);for(t!=null&&await this.closeInternal(t);;){let[t,n]=await this.stream.receive();n!=null&&await this.closeInternal(n);let r=Gi.decode(t?.err);if(r!=null&&await this.closeInternal(r),t?.command==e.command)return t}}},PC=z(`framer`),FC=PC(``),IC=class{streamClient;retriever;deleter;reader;constructor(e,t,n){this.streamClient=e,this.retriever=n,this.deleter=new CS(t),this.reader=new sC(n,e)}async openIterator(e,t,n){return await aC._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return await NC._open(this.retriever,this.streamClient,e)}async openStreamer(e){return await vC(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){let n=t,r=await this.openWriter({start:e,channels:Object.keys(n),mode:SC.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:k.MAX});return await r.write(n),await r.close()}let r=await this.openWriter({start:e,channels:t,mode:SC.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:k.MAX});await r.write(t,n),await r.close()}async read(e,t){if(!(`start`in e))return this.reader.read(e);let{single:n}=Sx(t),r=await this.readFrame(e,t);return n?r.get(t):r}async readFrame(e,t){let n=await this.openIterator(e,t),r=new $;try{for await(let e of n)r.push(e)}finally{await n.close()}return r}async readLatest(e,t=1){let{single:n}=Sx(e),r=await this.readLatestNFrame(e,t);return n?r.get(e):r}async readLatestNFrame(e,t){let n=await this.openIterator(j.MAX,e,{chunkSize:t}),r=new $;if(t>0)try{await n.seekLast(),await n.prev(eC),r.push(n.value)}finally{await n.close()}return r}async delete(e,t){let{normalized:n,variant:r}=Sx(e),i=new j(t);return r===`keys`?await this.deleter.delete({keys:n,bounds:i}):await this.deleter.delete({names:n,bounds:i})}},LC=o({ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:()=>CC,AUTO_SPAN:()=>eC,Client:()=>IC,Frame:()=>$,HardenedStreamer:()=>bC,Iterator:()=>aC,ObservableStreamer:()=>xC,Reader:()=>sC,TYPE_ONTOLOGY_ID:()=>FC,Writer:()=>NC,WriterClosedError:()=>wC,WriterCommand:()=>kS,WriterMode:()=>SC,createStreamOpener:()=>_C,frameZ:()=>ES,ontologyID:()=>PC,openStreamer:()=>vC,seriesFromPayload:()=>DS,seriesToPayload:()=>OS,streamerConfigZ:()=>gC,writerCommandZ:()=>AS,writerConfigZ:()=>kC}),RC=F.ABSOLUTE_AUTHORITY,zC=F.ZERO_AUTHORITY,BC=F.stateZ(l.z.number()),VC=e=>{let t=e.from?.resource,n=e.to?.resource;return e.to==null?`${t} - ${e.from?.subject.name} -> released`:e.from==null?`${n} - released -> ${e.to.subject.name} (${e.to.authority.toString()})`:`${n} - ${e.from.subject.name} -> ${e.to.subject.name} (${e.to.authority.toString()})`},HC=l.z.object({transfers:l.z.array(F.transferZ(Z))}),UC=class extends xC{states;codec;constructor(e){super(e,e=>{let t=this.codec.decode(e.series[0].buffer,HC);return this.merge(t),[t.transfers,!0]}),this.states=new Map,this.codec=new Vo.JSONCodec}subjects(){let e=new Map;return this.states.forEach(t=>e.set(t.subject.key,t.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(e=>{e.from==null&&e.to==null&&console.warn(`Invalid transfer: `,e),e.to==null?this.states.delete(e.from.resource):this.states.set(e.to.resource,e.to)})}},WC=`sy_node_1_control`,GC=class{framer;constructor(e){this.framer=e}async openStateTracker(){return new UC(await bC.open(async e=>await this.framer.openStreamer(e),WC))}},KC=o({ABSOLUTE_AUTHORITY:()=>RC,CONTROL_STATE_CHANNEL_NAME:()=>WC,Client:()=>GC,StateTracker:()=>UC,ZERO_AUTHORITY:()=>zC,stateZ:()=>BC,transferString:()=>VC}),qC=l.z.uint32(),JC=l.z.object({rack:qC}),YC=md.statusZ({details:JC}),XC=l.z.object({key:qC,name:l.z.string().min(1,`Name is required`),taskCounter:l.z.uint32().optional(),embedded:l.z.boolean().optional(),status:YC.optional(),integrations:D.nullToUndefined(l.z.string().array())}),ZC=XC.omit({taskCounter:!0,embedded:!0,key:!0}).extend({key:l.z.uint32().default(0)}),QC=z(`rack`),$C=QC(0),ew=`sy_rack_set`,tw=`sy_rack_delete`,nw=l.z.object({keys:qC.array().optional(),names:l.z.string().array().optional(),integration:l.z.string().optional(),searchTerm:l.z.string().optional(),embedded:l.z.boolean().optional(),hostIsNode:l.z.boolean().optional(),limit:l.z.int().optional(),offset:l.z.int().optional(),includeStatus:l.z.boolean().optional()}),rw=l.z.object({racks:w.nullishToEmpty(XC)}),iw=XC,aw=l.z.union([l.z.object({key:qC,includeStatus:l.z.boolean().optional()}).transform(({key:e,includeStatus:t})=>({keys:[e],includeStatus:t})),l.z.object({name:l.z.string(),includeStatus:l.z.boolean().optional()}).transform(({name:e,includeStatus:t})=>({names:[e],includeStatus:t}))]),ow=nw,sw=l.z.union([aw,ow]),cw=l.z.object({racks:ZC.array()}),lw=l.z.object({racks:XC.array()}),uw=l.z.object({keys:qC.array()}),dw=l.z.object({}),fw=class{client;tasks;constructor(e,t){this.client=e,this.tasks=t}async delete(e){await S(this.client,`/rack/delete`,{keys:w.toArray(e)},uw,dw)}async create(e){let t=!Array.isArray(e),n=await S(this.client,`/rack/create`,{racks:w.toArray(e)},cw,lw),r=this.sugar(n.racks);return t?r[0]:r}async retrieve(e){let t=`key`in e||`name`in e,n=await S(this.client,`/rack/retrieve`,e,sw,rw),r=this.sugar(n.racks);return X(`Rack`,e,r,t),t?r[0]:r}sugar(e){let t=!Array.isArray(e),n=w.toArray(e).map(({key:e,name:t,status:n,integrations:r})=>new pw(e,t,this.tasks,n,r));return t?n[0]:n}},pw=class{key;name;status;integrations;tasks;constructor(e,t,n,r,i){this.key=e,this.name=t,this.tasks=n,this.status=r,this.integrations=i}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,t){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&4294967295n)).toString(),await this.tasks.create(e,t)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status,integrations:this.integrations}}},mw=e=>Wd(QC(e)),hw=o({Client:()=>fw,DELETE_CHANNEL_NAME:()=>tw,Rack:()=>pw,SET_CHANNEL_NAME:()=>ew,TYPE_ONTOLOGY_ID:()=>$C,keyZ:()=>qC,newZ:()=>ZC,ontologyID:()=>QC,payloadZ:()=>XC,rackZ:()=>iw,statusDetailsZ:()=>JC,statusKey:()=>mw,statusZ:()=>YC}),gw=l.z.object({rack:qC,device:l.z.string()}),_w=l.z.string(),vw=md.statusZ({details:gw}),yw=({properties:e,make:t,model:n}={})=>l.z.object({key:_w,rack:qC,location:l.z.string().min(1,`Location is required`),make:t??l.z.string().min(1,`Make is required`),model:n??l.z.string().min(1,`Model is required`),name:l.z.string().min(1,`Name is required`),configured:l.z.boolean().default(!1),properties:e??I.nullishToEmpty(),status:vw.optional(),parent:R.optional()}),bw=({properties:e,make:t,model:n}={})=>yw({properties:e,make:t,model:n}).partial({key:!0,configured:!0}),xw=z(`device`),Sw=xw(``),Cw=`sy_device_set`,ww=`sy_device_delete`,Tw=e=>l.z.object({devices:D.toArray(bw(e))}),Ew=e=>l.z.object({devices:yw(e).array()}),Dw=l.z.object({keys:_w.array()}),Ow=l.z.object({}),kw=l.z.object({keys:_w.array().optional(),names:l.z.string().array().optional(),makes:l.z.string().array().optional(),models:l.z.string().array().optional(),locations:l.z.string().array().optional(),racks:qC.array().optional(),searchTerm:l.z.string().optional(),limit:l.z.int().optional(),offset:l.z.int().optional(),includeStatus:l.z.boolean().optional(),includeParent:l.z.boolean().optional()}),Aw=e=>l.z.object({devices:w.nullishToEmpty(yw(e))}),jw=l.z.object({key:_w,includeStatus:l.z.boolean().optional()}).transform(({key:e,includeStatus:t})=>({keys:[e],includeStatus:t})),Mw=l.z.union([jw,kw]),Nw=class{client;constructor(e){this.client=e}async retrieve(e){let{schemas:t,...n}=e,r=typeof n==`object`&&`key`in n,i=await S(this.client,`/device/retrieve`,n,Mw,Aw(t));return X(`Device`,n,i.devices,r),r?i.devices[0]:i.devices}async create(e,t){let n=!Array.isArray(e),r=await S(this.client,`/device/create`,{devices:w.toArray(e)},Tw(t),Ew(t));return n?r.devices[0]:r.devices}async delete(e){await S(this.client,`/device/delete`,{keys:w.toArray(e)},Dw,Ow)}},Pw=e=>Wd(xw(e)),Fw=o({Client:()=>Nw,DELETE_CHANNEL_NAME:()=>ww,SET_CHANNEL_NAME:()=>Cw,TYPE_ONTOLOGY_ID:()=>Sw,deviceZ:()=>yw,keyZ:()=>_w,newZ:()=>bw,ontologyID:()=>xw,statusDetailsZ:()=>gw,statusKey:()=>Pw,statusZ:()=>vw}),Iw=mu.keyZ,Lw=mu.labelZ,Rw=mu.newZ,zw=`labeled_by`,Bw=`sy_label_set`,Vw=`sy_label_delete`,Hw=l.default.object({labels:Rw.array()}),Uw=l.default.object({labels:Lw.array()}),Ww=l.default.object({keys:Iw.array()}),Gw=l.default.object({id:R,labels:Iw.array(),replace:l.default.boolean().optional()}),Kw=Gw.omit({replace:!0}),qw=l.default.object({}),Jw=l.default.object({keys:Iw.array().optional(),names:l.default.string().array().optional(),for:R.optional(),searchTerm:l.default.string().optional(),offset:l.default.int().optional(),limit:l.default.int().optional()}),Yw=l.default.object({key:Iw}).transform(({key:e})=>({keys:[e]})),Xw=l.default.union([Yw,Jw]),Zw=l.default.object({labels:w.nullishToEmpty(Lw)}),Qw=class{type=`label`;client;constructor(e){this.client=e}async retrieve(e){let t=`key`in e,n=await S(this.client,`/label/retrieve`,e,Xw,Zw);return X(`Label`,e,n.labels,t),t?n.labels[0]:n.labels}async label(e,t,n={}){await S(this.client,`/label/set`,{id:e,labels:t,replace:n.replace},Gw,qw)}async remove(e,t){await S(this.client,`/label/remove`,{id:e,labels:t},Kw,qw)}async create(e){let t=Array.isArray(e),n=await S(this.client,`/label/create`,{labels:w.toArray(e)},Hw,Uw);return t?n.labels:n.labels[0]}async delete(e){await S(this.client,`/label/delete`,{keys:w.toArray(e)},Ww,qw)}},$w=z(`label`),eT=$w(``),tT=o({Client:()=>Qw,DELETE_CHANNEL_NAME:()=>Vw,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:()=>zw,SET_CHANNEL_NAME:()=>Bw,TYPE_ONTOLOGY_ID:()=>eT,keyZ:()=>Iw,labelZ:()=>Lw,newZ:()=>Rw,ontologyID:()=>$w}),nT=l.z.uuid(),rT=l.z.object({key:nT,name:l.z.string(),data:_i.preserveCase(I.nullishToEmpty())}),iT=rT.partial({key:!0}),aT=z(`lineplot`),oT=aT(``),sT=l.z.uuid(),cT=l.z.object({key:sT,name:l.z.string().min(1,`Name is required`),author:l.z.uuid().optional(),layout:_i.preserveCase(I.nullishToEmpty())}),lT=cT.omit({author:!0}).partial({key:!0}),uT=z(`workspace`),dT=uT(``),fT=l.z.object({keys:sT.array().optional(),searchTerm:l.z.string().optional(),author:Lf.optional(),offset:l.z.int().optional(),limit:l.z.int().optional()}),pT=l.z.object({workspaces:lT.array()}),mT=l.z.object({key:sT,name:l.z.string()}),hT=l.z.object({key:sT,layout:_i.preserveCase(I.unknownZ())}),gT=l.z.object({keys:sT.array()}),_T=l.z.object({workspaces:w.nullishToEmpty(cT)}),vT=l.z.object({workspaces:cT.array()}),yT=l.z.object({}),bT=`sy_workspace_set`,xT=`sy_workspace_delete`,ST=class{client;constructor(e){this.client=e}async create(e){let t=Array.isArray(e),n=await S(this.client,`/workspace/create`,{workspaces:w.toArray(e)},pT,vT);return t?n.workspaces:n.workspaces[0]}async rename(e,t){await S(this.client,`/workspace/rename`,{key:e,name:t},mT,yT)}async setLayout(e,t){await S(this.client,`/workspace/set-layout`,{key:e,layout:t},hT,yT)}async retrieve(e){let t,n=typeof e!=`string`;t=typeof e==`string`||Array.isArray(e)?{keys:w.toArray(e)}:e;let r=await S(this.client,`/workspace/retrieve`,t,fT,_T);return n?r.workspaces:r.workspaces[0]}async delete(e){await S(this.client,`/workspace/delete`,{keys:w.toArray(e)},gT,yT)}},CT=o({Client:()=>ST,DELETE_CHANNEL_NAME:()=>xT,SET_CHANNEL_NAME:()=>bT,TYPE_ONTOLOGY_ID:()=>dT,keyZ:()=>sT,newZ:()=>lT,ontologyID:()=>uT,workspaceZ:()=>cT}),wT=l.z.object({key:nT,name:l.z.string()}),TT=l.z.object({key:nT,data:_i.preserveCase(I.unknownZ())}),ET=l.z.object({keys:nT.array()}),DT=l.z.object({keys:nT.array()}),OT=l.z.object({key:nT}).transform(({key:e})=>({keys:[e]})),kT=l.z.union([OT,DT]),AT=l.z.object({linePlots:w.nullishToEmpty(rT)}),jT=l.z.object({workspace:sT,linePlots:iT.array()}),MT=l.z.object({linePlots:rT.array()}),NT=l.z.object({}),PT=class{client;constructor(e){this.client=e}async create(e,t){let n=Array.isArray(t),r=await S(this.client,`/lineplot/create`,{workspace:e,linePlots:w.toArray(t)},jT,MT);return n?r.linePlots:r.linePlots[0]}async rename(e,t){await S(this.client,`/lineplot/rename`,{key:e,name:t},wT,NT)}async setData(e,t){await S(this.client,`/lineplot/set-data`,{key:e,data:t},TT,NT)}async retrieve(e){let t=OT.safeParse(e).success,n=await S(this.client,`/lineplot/retrieve`,e,kT,AT);return X(`LinePlot`,e,n.linePlots,t),t?n.linePlots[0]:n.linePlots}async delete(e){await S(this.client,`/lineplot/delete`,{keys:w.toArray(e)},ET,NT)}},FT=o({Client:()=>PT,TYPE_ONTOLOGY_ID:()=>oT,keyZ:()=>nT,linePlotZ:()=>rT,newZ:()=>iT,ontologyID:()=>aT,retrieveArgsZ:()=>kT}),IT=l.z.uuid(),LT=l.z.object({key:IT,name:l.z.string(),data:_i.preserveCase(I.nullishToEmpty())}),RT=LT.partial({key:!0}),zT=z(`log`),BT=zT(``),VT=l.z.object({key:IT,name:l.z.string()}),HT=l.z.object({key:IT,data:_i.preserveCase(I.unknownZ())}),UT=l.z.object({keys:IT.array()}),WT=l.z.object({keys:IT.array()}),GT=l.z.object({key:IT}).transform(({key:e})=>({keys:[e]})),KT=l.z.union([GT,WT]),qT=l.z.object({logs:w.nullishToEmpty(LT)}),JT=l.z.object({workspace:sT,logs:RT.array()}),YT=l.z.object({logs:LT.array()}),XT=l.z.object({}),ZT=class{client;constructor(e){this.client=e}async create(e,t){let n=Array.isArray(t),r=await S(this.client,`/log/create`,{workspace:e,logs:w.toArray(t)},JT,YT);return n?r.logs:r.logs[0]}async rename(e,t){await S(this.client,`/log/rename`,{key:e,name:t},VT,XT)}async setData(e,t){await S(this.client,`/log/set-data`,{key:e,data:t},HT,XT)}async retrieve(e){let t=GT.safeParse(e).success,n=await S(this.client,`/log/retrieve`,e,KT,qT);return X(`Log`,e,n.logs,t),t?n.logs[0]:n.logs}async delete(e){await S(this.client,`/log/delete`,{keys:w.toArray(e)},UT,XT)}},QT=o({Client:()=>ZT,TYPE_ONTOLOGY_ID:()=>BT,keyZ:()=>IT,logZ:()=>LT,newZ:()=>RT,ontologyID:()=>zT,retrieveArgsZ:()=>KT}),$T=l.z.object({range:Q,aliases:l.z.string().array()}),eE=l.z.object({aliases:l.z.record(l.z.string(),Z)}),tE=l.z.object({range:Q,aliases:l.z.record(Z,l.z.string())}),nE=l.z.unknown(),rE=l.z.object({range:Q,channels:Z.array()}),iE=l.z.unknown(),aE=l.z.object({range:Q}),oE=l.z.object({aliases:l.z.record(l.z.string(),l.z.string())}),sE=l.z.object({range:Q,channels:Z.array()}),cE=l.z.object({aliases:l.z.record(l.z.string(),l.z.string())}),lE=class{cache=new Map;client;rangeKey;constructor(e,t){this.rangeKey=e,this.cache=new Map,this.client=t}async resolve(e){let t=[],n=typeof e==`string`,r={};if(n){let n=this.cache.get(e);if(n!=null)return n;t.push(e)}else e.forEach(e=>{let n=this.cache.get(e);n==null?t.push(e):r[e]=n});if(t.length===0)return r;let i=await S(this.client,`/range/alias/resolve`,{range:this.rangeKey,aliases:t},$T,eE);return Object.entries(i.aliases).forEach(([e,t])=>this.cache.set(e,t)),n?i.aliases[t[0]]:{...r,...i.aliases}}async set(e){await S(this.client,`/range/alias/set`,{range:this.rangeKey,aliases:e},tE,nE)}async list(){return(await S(this.client,`/range/alias/list`,{range:this.rangeKey},aE,oE)).aliases}async retrieve(e){let t=typeof e==`number`,n=await S(this.client,`/range/alias/retrieve`,{range:this.rangeKey,channels:w.toArray(e)},sE,cE);return t?n.aliases[e]:n.aliases}async delete(e){await S(this.client,`/range/alias/delete`,{range:this.rangeKey,channels:w.toArray(e)},rE,iE)}},uE=`sy_range_alias_set`,dE=`sy_range_alias_delete`,fE=`---`,pE=e=>`${e.range}${fE}${e.channel}`,mE=(e,t)=>({type:`range-alias`,key:pE({range:e,channel:t})}),hE={type:`range-alias`,key:``},gE=e=>{let[t,n]=e.split(fE);return{range:t,channel:Number(n)}},_E=uE,vE=dE,yE=pE,bE=gE,xE=l.z.object({range:Q,channel:Z,alias:l.z.string()}),SE=o({Client:()=>lE,DELETE_ALIAS_CHANNEL_NAME:()=>vE,DELETE_CHANNEL_NAME:()=>dE,SET_ALIAS_CHANNEL_NAME:()=>_E,SET_CHANNEL_NAME:()=>uE,TYPE_ONTOLOGY_ID:()=>hE,aliasKey:()=>yE,aliasZ:()=>xE,createKey:()=>pE,decodeDeleteAliasChange:()=>bE,decodeDeleteChange:()=>gE,ontologyID:()=>mE}),CE=`sy_range_set`,wE=`sy_range_delete`,TE=class{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:t=j.ZERO,key:n,color:r,parent:i,labels:a},{frameClient:o,kv:s,aliaser:c,channels:l,labelClient:u,ontologyClient:d,rangeClient:f}){this.key=n,this.name=e,this.timeRange=t,this.parent=i,this.labels=a,this.frameClient=o,this.color=r,this.kv=s,this.aliaser=c,this.channels=l,this.labelClient=u,this.ontologyClient=d,this.rangeClient=f}get ontologyID(){return vx(this.key)}get payload(){let e={key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels};return this.parent!=null&&(`payload`in this.parent?e.parent=this.parent.payload:e.parent=this.parent),e}async setAlias(e,t){let n=await this.channels.retrieve(e);if(n.length===0)throw new jd(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){let e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:[`range`]})).map(e=>e.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:vx(this.key)})}async addLabel(...e){await this.labelClient.label(vx(this.key),e)}async removeLabel(...e){await this.labelClient.remove(vx(this.key),e)}static sort(e,t){return j.sort(e.timeRange,t.timeRange)}},EE=l.z.object({keys:Q.array().optional(),names:l.z.string().array().optional(),searchTerm:l.z.string().optional(),overlapsWith:j.z.optional(),hasLabels:Iw.array().optional(),limit:l.z.int().optional(),offset:l.z.int().optional(),includeLabels:l.z.boolean().optional(),includeParent:l.z.boolean().optional()}).or(Q.array().transform(e=>({keys:e}))).or(Q.transform(e=>({keys:[e]}))).or(l.z.string().transform(e=>({names:[e]}))).or(l.z.string().array().transform(e=>({names:e}))).or(j.z.transform(e=>({overlapsWith:e}))),DE=l.z.object({ranges:w.nullishToEmpty(gx)}),OE=class{type=`range`;frameClient;writer;unaryClient;channels;labelClient;ontologyClient;createAliasClient;createKVClient;constructor(e,t,n,r,i,a,o,s){this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=r,this.labelClient=i,this.ontologyClient=a,this.createAliasClient=o,this.createKVClient=s}async create(e,t){let n=!Array.isArray(e),r=this.sugarMany(await this.writer.create(w.toArray(e),t));return n?r[0]:r}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(w.toArray(e))}async retrieve(e){let t=typeof e==`string`,{ranges:n}=await S(this.unaryClient,`/range/retrieve`,e,EE,DE);return X(`Range`,e,n,t),t?this.sugarMany(n)[0]:this.sugarMany(n)}getKV(e){return this.createKVClient(e)}async retrieveParent(e){let t=await this.ontologyClient.retrieveParents(vx(e));if(t.length===0)return null;let n=t[0];return n.id.type===`range`?await this.retrieve(n.id.key):null}sugarOntologyResource(e){return this.sugarOne(AE(e))}async retrieveAlias(e,t){return await this.createAliasClient(e).retrieve(t)}async retrieveAliases(e,t){return await this.createAliasClient(e).retrieve(t)}async listAliases(e){return await this.createAliasClient(e).list()}async setAlias(e,t,n){await this.createAliasClient(e).set({[t]:n})}async deleteAlias(e,t){await this.createAliasClient(e).delete(t)}sugarOne(e){return new TE(e,{frameClient:this.frameClient,kv:this.createKVClient(e.key),aliaser:this.createAliasClient(e.key),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(e){return e.map(e=>this.sugarOne(e))}resourceToRange(e){return this.sugarOne(AE(e))}},kE=e=>({type:`range-alias`,key:e}),AE=({data:e,id:{key:t},name:n})=>{let r=j.z.parse(e?.timeRange),i=Ql.colorZ.safeParse(e?.color);return{key:t,name:n,timeRange:r,color:i.success?i.data:void 0,labels:[],parent:void 0}},jE=l.z.object({range:Q,key:l.z.string(),value:l.z.string()}),ME=l.z.object({range:Q,keys:l.z.string().array()}),NE=l.z.object({pairs:w.nullishToEmpty(jE)}),PE=l.z.object({range:Q,pairs:jE.array()}),FE=l.z.object({range:Q,keys:l.z.string().array()}),IE=class{rangeKey;client;constructor(e,t){this.rangeKey=e,this.client=t}async get(e){let t=await S(this.client,`/range/kv/get`,{range:this.rangeKey,keys:w.toArray(e)},ME,NE);return typeof e==`string`?t.pairs[0].value:Object.fromEntries(t.pairs.map(e=>[e.key,e.value]))}async list(){return this.get([])}async set(e,t=``){let n;n=typeof e==`string`?[{range:this.rangeKey,key:e,value:t}]:Object.entries(e).map(([e,t])=>({range:this.rangeKey,key:e,value:t})),await S(this.client,`/range/kv/set`,{range:this.rangeKey,pairs:n},PE,l.z.unknown())}async delete(e){await S(this.client,`/range/kv/delete`,{range:this.rangeKey,keys:w.toArray(e)},FE,l.z.unknown())}},LE=`sy_range_kv_set`,RE=`sy_range_kv_delete`,zE=({range:e,key:t})=>`${e}<--->${t}`,BE=LE,VE=RE,HE=jE,UE=zE,WE=o({Client:()=>IE,DELETE_CHANNEL_NAME:()=>RE,KV_DELETE_CHANNEL:()=>VE,KV_SET_CHANNEL:()=>BE,SET_CHANNEL_NAME:()=>LE,createPairKey:()=>zE,kvPairKey:()=>UE,kvPairZ:()=>HE,pairZ:()=>jE}),GE=l.z.string().min(1),KE=l.z.object({ranges:gx.array()}),qE=l.z.object({parent:R.optional(),ranges:_x.array()}),JE=l.z.object({keys:Q.array()}),YE=l.z.object({}),XE=l.z.object({key:Q,name:GE}),ZE=l.z.object({}),QE=class{client;constructor(e){this.client=e}async rename(e,t){await S(this.client,`/range/rename`,{key:e,name:t},XE,ZE)}async create(e,t){return(await S(this.client,`/range/create`,{ranges:e,...t},qE,KE)).ranges}async delete(e){await S(this.client,`/range/delete`,{keys:e},JE,YE)}},$E=o({Client:()=>OE,DELETE_ALIAS_CHANNEL_NAME:()=>dE,DELETE_CHANNEL_NAME:()=>wE,KV_DELETE_CHANNEL:()=>RE,KV_SET_CHANNEL:()=>LE,Range:()=>TE,SET_ALIAS_CHANNEL_NAME:()=>uE,SET_CHANNEL_NAME:()=>CE,TYPE_ONTOLOGY_ID:()=>yx,Writer:()=>QE,alias:()=>SE,aliasKey:()=>pE,aliasOntologyID:()=>kE,apiRangeZ:()=>hx,baseZ:()=>mx,convertOntologyResourceToPayload:()=>AE,decodeDeleteAliasChange:()=>gE,keyZ:()=>Q,kv:()=>WE,kvPairKey:()=>zE,nameZ:()=>GE,newZ:()=>_x,ontologyID:()=>vx,payloadZ:()=>gx}),eD=l.z.object({key:l.z.string(),name:l.z.string(),selectors:w.nullishToEmpty(l.z.string()),strokeColor:l.z.string().optional(),fillColor:l.z.string().optional()}),tD=l.z.object({key:l.z.string(),position:ac.xyZ,orientation:ac.outerLocationZ}),nD=l.z.object({zoom:l.z.number().default(1),position:ac.xyZ}),rD=l.z.uuid(),iD=l.z.object({key:l.z.string(),name:l.z.string(),regions:w.nullishToEmpty(eD)}),aD=l.z.object({svg:l.z.string().min(1),states:w.nullishToEmpty(iD),variant:l.z.string().min(1),handles:w.nullishToEmpty(tD),scale:l.z.number().default(1),scaleStroke:l.z.boolean().default(!1),previewViewport:nD.optional()}),oD=l.z.object({key:rD,version:l.z.uint32().default(1),name:l.z.string().min(1),data:aD}),sD=l.z.object({key:rD.optional(),version:l.z.uint32().default(1),name:l.z.string().min(1),data:aD}),cD=z(`schematic_symbol`),lD=cD(``),uD=l.z.object({symbols:sD.array(),parent:R}),dD=l.z.object({key:rD,name:l.z.string()}),fD=l.z.object({keys:rD.array()}),pD=l.z.object({keys:rD.array().optional(),searchTerm:l.z.string().optional()}),mD=l.z.object({key:rD}).transform(({key:e})=>({keys:[e]})),hD=l.z.union([mD,pD]),gD=l.z.object({symbols:w.nullishToEmpty(oD)}),_D=l.z.object({symbols:oD.array()}),vD=l.z.object({}),yD=l.z.object({}),bD=l.z.object({group:Ox}),xD=`sy_schematic_symbol_set`,SD=`sy_schematic_symbol_delete`,CD=class{client;constructor(e){this.client=e}async create(e){let t=`symbols`in e,n=t?e.symbols:[e],r=await S(this.client,`/schematic/symbol/create`,{symbols:n,parent:e.parent},uD,_D);return t?r.symbols:r.symbols[0]}async rename(e,t){await S(this.client,`/schematic/symbol/rename`,{key:e,name:t},dD,vD)}async retrieve(e){let t=`key`in e,n=await S(this.client,`/schematic/symbol/retrieve`,e,hD,gD);return X(`Schematic Symbol`,e,n.symbols,t),t?n.symbols[0]:n.symbols}async delete(e){await S(this.client,`/schematic/symbol/delete`,{keys:w.toArray(e)},fD,vD)}async retrieveGroup(){return(await S(this.client,`/schematic/symbol/retrieve-group`,{},yD,bD)).group}},wD=o({Client:()=>CD,DELETE_CHANNEL_NAME:()=>SD,SET_CHANNEL_NAME:()=>xD,TYPE_ONTOLOGY_ID:()=>lD,handleZ:()=>tD,keyZ:()=>rD,newZ:()=>sD,ontologyID:()=>cD,regionZ:()=>eD,specZ:()=>aD,stateZ:()=>iD,symbolZ:()=>oD,viewportZ:()=>nD}),TD=l.z.uuid(),ED=l.z.object({key:TD,name:l.z.string(),data:_i.preserveCase(I.nullishToEmpty()),snapshot:l.z.boolean()}),DD=ED.partial({key:!0,snapshot:!0}),OD=z(`schematic`),kD=OD(``),AD=l.z.object({key:TD,name:l.z.string()}),jD=l.z.object({key:TD,data:_i.preserveCase(I.unknownZ())}),MD=l.z.object({keys:TD.array()}),ND=l.z.object({key:TD,name:l.z.string(),snapshot:l.z.boolean()}),PD=l.z.object({keys:TD.array()}),FD=l.z.object({key:TD}).transform(({key:e})=>({keys:[e]})),ID=l.z.union([FD,PD]),LD=l.z.object({schematics:ED.array()}),RD=l.z.object({workspace:sT,schematics:DD.array()}),zD=l.z.object({schematics:ED.array()}),BD=l.z.object({schematic:ED}),VD=l.z.object({}),HD=class{symbols;client;constructor(e){this.client=e,this.symbols=new CD(e)}async create(e,t){let n=Array.isArray(t),r=await S(this.client,`/schematic/create`,{workspace:e,schematics:w.toArray(t)},RD,zD);return n?r.schematics:r.schematics[0]}async rename(e,t){await S(this.client,`/schematic/rename`,{key:e,name:t},AD,VD)}async setData(e,t){await S(this.client,`/schematic/set-data`,{key:e,data:t},jD,VD)}async retrieve(e){let t=FD.safeParse(e).success,n=await S(this.client,`/schematic/retrieve`,e,ID,LD);return X(`Schematic`,e,n.schematics,t),t?n.schematics[0]:n.schematics}async delete(e){await S(this.client,`/schematic/delete`,{keys:w.toArray(e)},MD,VD)}async copy(e){return(await S(this.client,`/schematic/copy`,e,ND,BD)).schematic}},UD=o({Client:()=>HD,TYPE_ONTOLOGY_ID:()=>kD,keyZ:()=>TD,newZ:()=>DD,ontologyID:()=>OD,retrieveArgsZ:()=>ID,schematicZ:()=>ED,symbol:()=>wD}),WD=l.z.string(),GD=e=>md.statusZ({details:e}),KD=e=>md.newZ({details:e}).omit({labels:!0}),qD=`sy_status_set`,JD=`sy_status_delete`,YD=z(`status`),XD=YD(``),ZD=e=>l.default.object({parent:R.optional(),statuses:KD(e).array()}),QD=e=>l.default.object({statuses:GD(e).array()}),$D=l.default.object({keys:WD.array()}),eO=l.default.object({}),tO=l.default.object({keys:WD.array().optional(),searchTerm:l.default.string().optional(),offset:l.default.int().optional(),limit:l.default.int().optional(),includeLabels:l.default.boolean().optional(),hasLabels:Iw.array().optional(),variants:l.default.string().array().optional()}),nO=l.default.object({key:WD,includeLabels:l.default.boolean().optional()}).transform(({key:e,includeLabels:t})=>({keys:[e],includeLabels:t})),rO=l.default.union([nO,tO]),iO=e=>l.default.object({statuses:w.nullishToEmpty(GD(e))}),aO=class{type=`status`;client;constructor(e){this.client=e}async retrieve(e){let t=`key`in e,n=await S(this.client,`/status/retrieve`,e,rO,iO(e.detailsSchema));X(`Status`,e,n.statuses,t);let r=n.statuses;return t?r[0]:r}async set(e,t={}){let n=Array.isArray(e),r=(await S(this.client,`/status/set`,{statuses:w.toArray(e),parent:t.parent},ZD(t.detailsSchema),QD(t.detailsSchema))).statuses;return n?r:r[0]}async delete(e){await S(this.client,`/status/delete`,{keys:w.toArray(e)},$D,eO)}},oO=o({Client:()=>aO,DELETE_CHANNEL_NAME:()=>JD,SET_CHANNEL_NAME:()=>qD,TYPE_ONTOLOGY_ID:()=>XD,keyZ:()=>WD,newZ:()=>KD,ontologyID:()=>YD,statusZ:()=>GD}),sO=l.z.uuid(),cO=l.z.object({key:sO,name:l.z.string(),data:_i.preserveCase(I.nullishToEmpty())}),lO=cO.partial({key:!0}),uO=z(`table`),dO=uO(``),fO=l.z.object({key:sO,name:l.z.string()}),pO=l.z.object({key:sO,data:_i.preserveCase(I.unknownZ())}),mO=l.z.object({keys:sO.array()}),hO=l.z.object({keys:sO.array()}),gO=l.z.object({key:sO}).transform(({key:e})=>({keys:[e]})),_O=l.z.union([gO,hO]),vO=l.z.object({tables:w.nullishToEmpty(cO)}),yO=l.z.object({workspace:sT,tables:lO.array()}),bO=l.z.object({tables:cO.array()}),xO=l.z.object({}),SO=class{client;constructor(e){this.client=e}async create(e,t){let n=Array.isArray(t),r=await S(this.client,`/table/create`,{workspace:e,tables:w.toArray(t)},yO,bO);return n?r.tables:r.tables[0]}async rename(e,t){await S(this.client,`/table/rename`,{key:e,name:t},fO,xO)}async setData(e,t){await S(this.client,`/table/set-data`,{key:e,data:t},pO,xO)}async retrieve(e){let t=gO.safeParse(e).success,n=await S(this.client,`/table/retrieve`,e,_O,vO);return X(`Table`,e,n.tables,t),t?n.tables[0]:n.tables}async delete(e){await S(this.client,`/table/delete`,{keys:w.toArray(e)},mO,xO)}},CO=o({Client:()=>SO,TYPE_ONTOLOGY_ID:()=>dO,keyZ:()=>sO,newZ:()=>lO,ontologyID:()=>uO,retrieveArgsZ:()=>_O,tableZ:()=>cO}),wO=l.z.string().or(l.z.number().transform(String).or(l.z.bigint().transform(String))),TO=e=>l.z.object({task:wO,running:l.z.boolean(),cmd:l.z.string().optional(),data:e??l.z.unknown().optional()}),EO=e=>l.z.object({task:wO.optional(),running:l.z.boolean(),cmd:l.z.string().optional(),data:e??l.z.unknown().optional()}),DO=l.z.object({task:wO,type:l.z.string(),key:l.z.string(),args:_i.preserveCase(D.nullToUndefined(I.unknownZ()))}),OO=e=>md.statusZ({details:TO(e)}),kO=e=>md.newZ({details:EO(e)}),AO=({type:e,config:t,statusData:n}={})=>l.z.object({key:wO,name:l.z.string(),type:e??l.z.string(),config:t??I.nullishToEmpty(),internal:l.z.boolean().optional(),snapshot:l.z.boolean().optional(),status:md.statusZ({details:TO(n)}).optional()}),jO=({type:e,config:t,statusData:n}={})=>AO({type:e,config:t,statusData:n}).omit({internal:!0,snapshot:!0,status:!0}).partial({key:!0}).extend({status:md.newZ({details:EO(n)}).optional()}),MO=z(`task`),NO=MO(``),PO=`sy_task_cmd`,FO=`sy_task_set`,IO=`sy_task_delete`,LO=Error(`Task not created`),RO=e=>Number(BigInt(e)>>32n),zO=(e,t=0)=>((BigInt(e)<<32n)+BigInt(t)).toString(),BO=async(e,t)=>{let n=await t.retrieveParents(MO(e));return n.length===0?null:n[0]},VO=class{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw LO;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw LO;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw LO;return this.rangeClient_}constructor({key:e,type:t,name:n,config:r,internal:i=!1,snapshot:a=!1,status:o},s,c,u,d){this.key=e,this.name=n,this.type=t,this.config=r,this.schemas=s??{type:l.z.string(),config:l.z.unknown(),statusData:l.z.unknown()},this.internal=i,this.snapshot=a,this.status=o,this.frameClient_=c,this.ontologyClient_=u,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 MO(this.key)}async executeCommand(e){return await tk({...e,frameClient:this.frameClient,task:this.key})}async executeCommandSync(e){return await rk({...e,frameClient:this.frameClient,task:this.key,name:this.name,statusDataZ:this.schemas.statusData})}async start(){await this.executeCommand({type:`start`})}async stop(){await this.executeCommand({type:`stop`})}async run(e){await this.start();try{return await e()}finally{await this.stop()}}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw LO;return this.snapshot?await BO(this.key,this.ontologyClient):null}},HO=l.z.object({rack:qC.optional(),keys:wO.array().optional(),names:l.z.string().array().optional(),types:l.z.string().array().optional(),includeStatus:l.z.boolean().optional(),internal:l.z.boolean().optional(),snapshot:l.z.boolean().optional(),searchTerm:l.z.string().optional(),offset:l.z.int().optional(),limit:l.z.int().optional()}),UO=l.z.union([l.z.object({key:wO,includeStatus:l.z.boolean().optional()}).transform(({key:e,includeStatus:t})=>({keys:[e],includeStatus:t})),l.z.object({name:l.z.string(),includeStatus:l.z.boolean().optional()}).transform(({name:e,includeStatus:t})=>({names:[e],includeStatus:t})),l.z.object({type:l.z.string(),rack:qC.optional()}).transform(({type:e,rack:t})=>({types:[e],rack:t}))]),WO=HO,GO=l.z.union([UO,WO]),KO=e=>l.z.object({tasks:w.nullishToEmpty(AO(e))}),qO=e=>l.z.object({tasks:jO(e).array()}),JO=e=>l.z.object({tasks:AO(e).array()}),YO=l.z.object({keys:wO.array()}),XO=l.z.object({}),ZO=l.z.object({key:wO,name:l.z.string(),snapshot:l.z.boolean()}),QO=e=>l.z.object({task:AO(e)}),$O=class{client;frameClient;ontologyClient;rangeClient;constructor(e,t,n,r){this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=r}async create(e,t){let n=!Array.isArray(e),r=qO(t),i=JO(t),a=await S(this.client,`/task/create`,{tasks:w.toArray(e)},r,i),o=this.sugar(a.tasks,t);return n?o[0]:o}async delete(e){await S(this.client,`/task/delete`,{keys:w.toArray(e)},YO,XO)}async retrieve({schemas:e,...t}){let n=UO.safeParse(t).success,r=(await S(this.client,`/task/retrieve`,t,GO,KO(e))).tasks,i=this.sugar(r,e);return X(`Task`,t,i,n),n?i[0]:i}async copy(e,t,n){let r=QO(),i=await S(this.client,`/task/copy`,{key:e,name:t,snapshot:n},ZO,r);return this.sugar(i.task)}async list(e){let t={internal:!1};return e!==void 0&&(t.rack=e),await this.retrieve(t)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw LO;return await BO(e,this.ontologyClient)}sugar(e,t){let n=!Array.isArray(e),r=w.toArray(e).map(({key:e,name:n,type:r,config:i,status:a,internal:o,snapshot:s})=>new VO({key:e,name:n,type:r,config:i,internal:o,snapshot:s,status:a},t,this.frameClient,this.ontologyClient,this.rangeClient));return n?r[0]:r}async executeCommand(e){return`commands`in e?await nk({...e,frameClient:this.frameClient}):await tk({...e,frameClient:this.frameClient})}async executeCommandSync(e){if(`commands`in e){let t=async()=>{let{commands:t}=e;return(await this.retrieve({keys:t.map(e=>e.task)})).map(e=>e.name)};return await ik({...e,frameClient:this.frameClient,name:t})}return await rk({frameClient:this.frameClient,name:async()=>{let{task:t}=e;return(await this.retrieve({key:t})).name},...e})}},ek=e=>Wd(MO(e)),tk=async({frameClient:e,task:t,type:n,args:r})=>(await nk({frameClient:e,commands:[{args:r,task:t,type:n}]}))[0],nk=async({frameClient:e,commands:t})=>{if(e==null)throw LO;let n=await e.openWriter(PO),r=t.map(e=>({...e,key:ms.create()}));return await n.write(PO,r),await n.close(),r.map(e=>e.key)},rk=async({frameClient:e,task:t,type:n,timeout:r,name:i,statusDataZ:a,args:o})=>(await ik({frameClient:e,commands:[{args:o,task:t,type:n}],timeout:r,statusDataZ:a,name:i}))[0],ik=async({frameClient:e,commands:t,timeout:n=k.seconds(10),statusDataZ:r,name:i})=>{if(e==null)throw LO;let a=await e.openStreamer(qD),o=await nk({frameClient:e,commands:t}),s=new k(n),c=[],l,u=new Promise((e,n)=>{l=setTimeout(()=>{(async()=>{n(await ak(`command`,i,s,t.map(e=>e.task)))})()},s.milliseconds)});try{for(;;){let e=await Promise.race([a.read(),u]),t=OO(r).safeParse(e.at(-1)[qD]);if(!t.success)continue;let n=t.data;if(!(n.details.cmd==null||!o.includes(n.details.cmd))&&(c=[...c.filter(e=>e.key!==n.key),n],c.length===o.length))return c}}finally{clearTimeout(l),a.close()}},ak=async(e,t,n,r)=>{let i=_i.capitalize(e),a=n.toString();try{let e;e=typeof t==`string`?[t]:Array.isArray(t)?t:w.toArray(await t());let n=bd.naturalLanguageJoin(e);return Error(`${i} command to ${n} timed out after ${a}`)}catch(e){return console.error(`Failed to retrieve task name for timeout error:`,e),Error(`${i} command to task with key ${bd.naturalLanguageJoin(w.toArray(r).map(e=>e.toString()))} timed out after ${a}`)}},ok=o({COMMAND_CHANNEL_NAME:()=>PO,Client:()=>$O,DELETE_CHANNEL_NAME:()=>IO,SET_CHANNEL_NAME:()=>FO,TYPE_ONTOLOGY_ID:()=>NO,Task:()=>VO,commandZ:()=>DO,keyZ:()=>wO,newKey:()=>zO,newStatusDetailsZ:()=>EO,newStatusZ:()=>kO,newZ:()=>jO,ontologyID:()=>MO,payloadZ:()=>AO,rackKey:()=>RO,statusDetailsZ:()=>TO,statusKey:()=>ek,statusZ:()=>OO}),sk=class{url;unary;stream;secure;constructor(e,t={},n=!1){this.secure=n,this.url=e.child(`/api/v1/`);let r=new Vo.JSONCodec;this.unary=ii(new ri(this.url,r,this.secure),t),this.stream=new li(this.url,r,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}},ck=l.z.uuid(),lk=l.z.object({key:ck,name:l.z.string(),type:l.z.string(),query:I.nullishToEmpty()}),uk=lk.partial({key:!0}),dk=z(`view`),fk=dk(``),pk=`sy_view_set`,mk=`sy_view_delete`,hk=l.z.object({views:uk.array()}),gk=l.z.object({views:lk.array()}),_k=l.z.object({keys:ck.array()}),vk=l.z.object({}),yk=l.z.object({keys:ck.array().optional(),types:l.z.string().array().optional(),searchTerm:l.z.string().optional(),offset:l.z.number().optional(),limit:l.z.number().optional()}),bk=l.z.object({key:ck}).transform(({key:e})=>({keys:[e]})),xk=l.z.union([bk,yk]),Sk=l.z.object({views:w.nullishToEmpty(lk)}),Ck=class{client;constructor(e){this.client=e}async retrieve(e){let t=`key`in e,n=await S(this.client,`/view/retrieve`,e,xk,Sk);return X(`View`,e,n.views,t),t?n.views[0]:n.views}async create(e){let t=Array.isArray(e),n=await S(this.client,`/view/create`,{views:w.toArray(e)},hk,gk);return t?n.views:n.views[0]}async delete(e){await S(this.client,`/view/delete`,{keys:w.toArray(e)},_k,vk)}},wk=o({Client:()=>Ck,DELETE_CHANNEL_NAME:()=>mk,SET_CHANNEL_NAME:()=>pk,TYPE_ONTOLOGY_ID:()=>fk,keyZ:()=>ck,newZ:()=>uk,ontologyID:()=>dk,viewZ:()=>lk}),Tk=l.z.object({host:l.z.string({error:`Host is required`}).min(1,`Host is required`),port:l.z.number({error:`Port is required`}).or(l.z.string({error:`Port is required`})),username:l.z.string().min(1,`Username is required`),password:l.z.string().min(1,`Password is required`),connectivityPollFrequency:k.z.default(k.seconds(30)),secure:l.z.boolean().default(!1),name:l.z.string().optional(),retry:Xc.breakerConfigZ.optional()}),Ek=class extends IC{createdAt;params;ranges;channels;auth;users;access;connectivity;ontology;workspaces;labels;statuses;tasks;racks;devices;control;arcs;views;schematics;lineplots;logs;tables;groups;static connectivity=bS;transport;clientVersion=`0.54.2`;constructor(e){let t=D.parse(Tk,e),{host:n,port:r,username:i,password:a,connectivityPollFrequency:o,secure:s,retry:c}=t,l=new sk(new wd({host:n,port:Number(r)}),c,s);l.use(zd);let u=new wx(new Cx(l.unary));super(l.stream,l.unary,u),this.auth=new fS(l.unary,{username:i,password:a}),l.use(this.auth.middleware());let d=new rS(l.unary,u);this.createdAt=O.now(),this.params=t,this.transport=l,this.channels=new Wx(this,u,l.unary,d),this.connectivity=new bS(l.unary,o,this.clientVersion,t.name),this.control=new GC(this),this.ontology=new of(this.transport.unary);let f=new QE(this.transport.unary);this.labels=new Qw(this.transport.unary),this.statuses=new aO(this.transport.unary),this.ranges=new OE(this,f,this.transport.unary,u,this.labels,this.ontology,e=>new lE(e,this.transport.unary),e=>new IE(e,this.transport.unary)),this.access=new wp(this.transport.unary),this.users=new np(this.transport.unary),this.workspaces=new ST(this.transport.unary),this.tasks=new $O(this.transport.unary,this,this.ontology,this.ranges),this.racks=new fw(this.transport.unary,this.tasks),this.devices=new Nw(this.transport.unary),this.arcs=new Kb(this.transport.unary,this.transport.stream),this.views=new Ck(this.transport.unary),this.schematics=new HD(this.transport.unary),this.lineplots=new PT(this.transport.unary),this.logs=new ZT(this.transport.unary),this.tables=new SO(this.transport.unary),this.groups=new Lx(this.transport.unary)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stop()}},Dk=async e=>await Ok(e).check(),Ok=e=>{let{host:t,port:n,secure:r,name:i,retry:a}=e,o=D.parse(Xc.breakerConfigZ.optional(),a);return new bS(new sk(new wd({host:t,port:Number(n)}),o,r).unary,void 0,`0.54.2`,i)},kk={host:`localhost`,port:9090,username:`synnax`,password:`seldon`,retry:{maxRetries:4,baseInterval:k.seconds(1),scale:1.5}},Ak=e=>new Ek({...kk,...e}),jk=async(e,t)=>{let n=ms.create(),r=await e.users.create({username:n,password:`test`,firstName:`test`,lastName:`test`}),i=await e.access.policies.create(t),a=await e.access.roles.create({name:`test`,description:`test`});return await e.ontology.addChildren(Ff(a.key),hf(i.key)),await e.access.roles.assign({user:r.key,role:a.key}),Ak({username:n,password:`test`})};exports.AuthError=Dd,exports.Channel=Vx,exports.ContiguityError=Rd,exports.DataType=M,exports.Density=A,exports.DisconnectedError=Ld,exports.Frame=$,exports.MultiSeries=Wc,exports.MultipleFoundError=Nd,exports.NotFoundError=Md,exports.QueryError=jd,exports.Rate=dc,exports.RouteError=Pd,exports.Series=Ic,exports.Synnax=Ek,exports.TEST_CLIENT_PARAMS=kk,exports.TimeRange=j,exports.TimeSpan=k,exports.TimeStamp=O,exports.UnexpectedError=Ad,exports.ValidationError=L,Object.defineProperty(exports,`access`,{enumerable:!0,get:function(){return Ep}}),Object.defineProperty(exports,`arc`,{enumerable:!0,get:function(){return Yb}}),Object.defineProperty(exports,`channel`,{enumerable:!0,get:function(){return iS}}),exports.checkConnection=Dk,Object.defineProperty(exports,`connection`,{enumerable:!0,get:function(){return pS}}),Object.defineProperty(exports,`control`,{enumerable:!0,get:function(){return KC}}),exports.createTestClient=Ak,exports.createTestClientWithPolicy=jk,Object.defineProperty(exports,`device`,{enumerable:!0,get:function(){return Fw}}),Object.defineProperty(exports,`framer`,{enumerable:!0,get:function(){return LC}}),Object.defineProperty(exports,`group`,{enumerable:!0,get:function(){return Rx}}),exports.isCalculated=Gx,Object.defineProperty(exports,`label`,{enumerable:!0,get:function(){return tT}}),Object.defineProperty(exports,`lineplot`,{enumerable:!0,get:function(){return FT}}),Object.defineProperty(exports,`log`,{enumerable:!0,get:function(){return QT}}),exports.newConnectionChecker=Ok,Object.defineProperty(exports,`ontology`,{enumerable:!0,get:function(){return df}}),Object.defineProperty(exports,`rack`,{enumerable:!0,get:function(){return hw}}),Object.defineProperty(exports,`ranger`,{enumerable:!0,get:function(){return $E}}),Object.defineProperty(exports,`schematic`,{enumerable:!0,get:function(){return UD}}),Object.defineProperty(exports,`status`,{enumerable:!0,get:function(){return oO}}),exports.synnaxParamsZ=Tk,Object.defineProperty(exports,`table`,{enumerable:!0,get:function(){return CO}}),Object.defineProperty(exports,`task`,{enumerable:!0,get:function(){return ok}}),Object.defineProperty(exports,`user`,{enumerable:!0,get:function(){return ap}}),Object.defineProperty(exports,`view`,{enumerable:!0,get:function(){return wk}}),Object.defineProperty(exports,`workspace`,{enumerable:!0,get:function(){return CT}});