@rizom/ops 0.2.0-alpha.849 → 0.2.0-alpha.850
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/brains-ops.js +77 -71
- package/dist/index.js +106 -100
- package/dist/secrets-encrypt.d.ts +1 -0
- package/package.json +1 -1
- package/templates/rover-pilot/.env.schema +5 -0
- package/templates/rover-pilot/deploy/scripts/decrypt-user-secrets.ts +3 -0
- package/templates/rover-pilot/docs/onboarding-checklist.md +1 -0
- package/templates/rover-pilot/docs/operator-playbook.md +32 -0
package/dist/brains-ops.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var dK=Object.create;var{getPrototypeOf:pK,defineProperty:qb,getOwnPropertyNames:fK}=Object;var mK=Object.prototype.hasOwnProperty;function hK(e){return this[e]}var gK,yK,Vl=(e,t,r)=>{var o=e!=null&&typeof e==="object";if(o){var n=t?gK??=new WeakMap:yK??=new WeakMap,i=n.get(e);if(i)return i}r=e!=null?dK(pK(e)):{};let s=t||!e||!e.__esModule?qb(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of fK(e))if(!mK.call(s,a))qb(s,a,{get:hK.bind(e,a),enumerable:!0})}if(o)n.set(e,s);return s};var ye=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var bK=(e)=>e;function SK(e,t){this[e]=bK.bind(null,t)}var Lt=(e,t)=>{for(var r in t)qb(e,r,{get:t[r],enumerable:!0,configurable:!0,set:SK.bind(t,r)})};var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var Fr=import.meta.require;function Ve(e,t){if(e instanceof Error)return e.message;return t??String(e)}function Fb(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function St(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(`${r}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw RangeError(`${r}expected integer >= 0, got ${e}`)}}function Mt(e,t,r=""){let o=Fb(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+l;if(!o)throw TypeError(u);throw RangeError(u)}return e}function fo(e){if(typeof e!=="function"||typeof e.create!=="function")throw TypeError("Hash must wrapped by utils.createHasher");if(St(e.outputLen),St(e.blockLen),e.outputLen<1)throw Error('"outputLen" must be >= 1');if(e.blockLen<1)throw Error('"blockLen" must be >= 1')}function ka(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function ff(e,t){Mt(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw RangeError('"digestInto() output" expected to be of length >='+r)}function mf(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function cr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ra(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ln(e,t){return e<<32-t|e>>>t}function Fe(e,t){return e<<t|e>>>32-t>>>0}function $K(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function OK(e){for(let t=0;t<e.length;t++)e[t]=$K(e[t]);return e}function hf(e){if(Mt(e),SO)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=CK[e[r]];return t}function bO(e){if(e>=po._0&&e<=po._9)return e-po._0;if(e>=po.A&&e<=po.F)return e-(po.A-10);if(e>=po.a&&e<=po.f)return e-(po.a-10);return}function Wl(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(SO)try{return Uint8Array.fromHex(e)}catch(n){if(n instanceof SyntaxError)throw RangeError(n.message);throw n}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=bO(e.charCodeAt(i)),a=bO(e.charCodeAt(i+1));if(s===void 0||a===void 0){let l=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+l+'" at index '+i)}o[n]=s*16+a}return o}function zK(e){if(typeof e!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Kb(e,t=""){if(typeof e==="string")return zK(e);return Mt(e,void 0,t)}function Hb(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Mt(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function gf(e,t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw TypeError("options must be object or undefined");return Object.assign(e,t)}function Vb(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.canXOF=o.canXOF,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function mo(e=32){St(e,"bytesLength");let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var TK,Jb,SO,CK,po,Wb=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Jr=b(()=>{TK=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();Jb=TK?(e)=>e:OK,SO=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),CK=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));po={_0:48,_9:57,A:65,F:70,a:97,f:102}});class Gb{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(fo(e),Mt(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),cr(o)}update(e){return ka(this),this.iHash.update(e),this}digestInto(e){ka(this),ff(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var zn;var Gl=b(()=>{Jr();zn=(()=>{let e=(t,r,o)=>new Gb(t,r).update(o).digest();return e.create=(t,r)=>new Gb(t,r),e})()});function Ql(e,t,r){if(fo(e),r===void 0)r=new Uint8Array(e.outputLen);return zn(e,r,t)}function Yb(e,t,r,o=32){fo(e),St(o,"length"),Mt(t,void 0,"prk");let n=e.outputLen;if(t.length<n)throw Error('"prk" must be at least HashLen octets');if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=vO;else Mt(r,void 0,"info");let s=new Uint8Array(i*n),a=zn.create(e,t),l=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)Qb[0]=d+1,l.update(d===0?vO:u).update(r).update(Qb).digestInto(u),s.set(u,n*d),a._cloneInto(l);return a.destroy(),l.destroy(),cr(u,Qb),s.slice(0,o)}var Qb,vO,Yo=(e,t,r,o,n)=>Yb(e,Ql(e,t,r),o,n);var Xb=b(()=>{Gl();Jr();Qb=Uint8Array.of(0),vO=Uint8Array.of()});function wO(e,t,r){return e&t^~e&r}function xO(e,t,r){return e&t^e&r^t&r}class yf{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Ra(this.buffer)}update(e){ka(this),Mt(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=Ra(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){ka(this),ff(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,cr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=Ra(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let l=a/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var ho,qt;var _O=b(()=>{Jr();ho=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function PK(e,t=!1){if(t)return{h:Number(e&bf),l:Number(e>>EO&bf)};return{h:Number(e>>EO&bf)|0,l:Number(e&bf)|0}}function AO(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=PK(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}function Pn(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var bf,EO,eS=(e,t,r)=>e>>>r,tS=(e,t,r)=>e<<32-r|t>>>r,ms=(e,t,r)=>e>>>r|t<<32-r,hs=(e,t,r)=>e<<32-r|t>>>r,Yl=(e,t,r)=>e<<64-r|t>>>r-32,Xl=(e,t,r)=>e>>>r-32|t<<64-r,IO=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),kO=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,RO=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),TO=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,$O=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),OO=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var CO=b(()=>{bf=BigInt(4294967295),EO=BigInt(32)});var DK,Xo,zO,PO,NO,LK,ZK,ei,ti,DO,LO,vt,Sf;var Ta=b(()=>{_O();CO();Jr();DK=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Xo=new Uint32Array(64);zO=class zO extends yf{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)Xo[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=Xo[d-15],m=Xo[d-2],h=ln(p,7)^ln(p,18)^p>>>3,S=ln(m,17)^ln(m,19)^m>>>10;Xo[d]=S+Xo[d-7]+h+Xo[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:l,H:u}=this;for(let d=0;d<64;d++){let p=ln(s,6)^ln(s,11)^ln(s,25),m=u+p+wO(s,a,l)+DK[d]+Xo[d]|0,S=(ln(r,2)^ln(r,13)^ln(r,22))+xO(r,o,n)|0;u=l,l=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+S|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,l,u)}roundClean(){cr(Xo)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),cr(this.buffer)}};PO=class PO extends zO{A=ho[0]|0;B=ho[1]|0;C=ho[2]|0;D=ho[3]|0;E=ho[4]|0;F=ho[5]|0;G=ho[6]|0;H=ho[7]|0;constructor(){super(32)}};NO=(()=>AO(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e)=>BigInt(e))))(),LK=(()=>NO[0])(),ZK=(()=>NO[1])(),ei=new Uint32Array(80),ti=new Uint32Array(80);DO=class DO extends yf{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:l,El:u,Fh:d,Fl:p,Gh:m,Gl:h,Hh:S,Hl:y}=this;return[e,t,r,o,n,i,s,a,l,u,d,p,m,h,S,y]}set(e,t,r,o,n,i,s,a,l,u,d,p,m,h,S,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=h|0,this.Hh=S|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)ei[_]=e.getUint32(t),ti[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let k=ei[_-15]|0,O=ti[_-15]|0,L=ms(k,O,1)^ms(k,O,8)^eS(k,O,7),P=hs(k,O,1)^hs(k,O,8)^tS(k,O,7),K=ei[_-2]|0,z=ti[_-2]|0,W=ms(K,z,19)^Yl(K,z,61)^eS(K,z,6),ee=hs(K,z,19)^Xl(K,z,61)^tS(K,z,6),j=RO(P,ee,ti[_-7],ti[_-16]),T=TO(j,L,W,ei[_-7],ei[_-16]);ei[_]=T|0,ti[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:l,Dl:u,Eh:d,El:p,Fh:m,Fl:h,Gh:S,Gl:y,Hh:v,Hl:x}=this;for(let _=0;_<80;_++){let k=ms(d,p,14)^ms(d,p,18)^Yl(d,p,41),O=hs(d,p,14)^hs(d,p,18)^Xl(d,p,41),L=d&m^~d&S,P=p&h^~p&y,K=$O(x,O,P,ZK[_],ti[_]),z=OO(K,v,k,L,LK[_],ei[_]),W=K|0,ee=ms(r,o,28)^Yl(r,o,34)^Yl(r,o,39),j=hs(r,o,28)^Xl(r,o,34)^Xl(r,o,39),T=r&n^r&s^n&s,Z=o&i^o&a^i&a;v=S|0,x=y|0,S=m|0,y=h|0,m=d|0,h=p|0,{h:d,l:p}=Pn(l|0,u|0,z|0,W|0),l=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let A=IO(W,j,Z);r=kO(A,z,ee,T),o=A|0}({h:r,l:o}=Pn(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=Pn(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=Pn(this.Ch|0,this.Cl|0,s|0,a|0),{h:l,l:u}=Pn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=Pn(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:h}=Pn(this.Fh|0,this.Fl|0,m|0,h|0),{h:S,l:y}=Pn(this.Gh|0,this.Gl|0,S|0,y|0),{h:v,l:x}=Pn(this.Hh|0,this.Hl|0,v|0,x|0),this.set(r,o,n,i,s,a,l,u,d,p,m,h,S,y,v,x)}roundClean(){cr(ei,ti)}destroy(){this.destroyed=!0,cr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};LO=class LO extends DO{Ah=qt[0]|0;Al=qt[1]|0;Bh=qt[2]|0;Bl=qt[3]|0;Ch=qt[4]|0;Cl=qt[5]|0;Dh=qt[6]|0;Dl=qt[7]|0;Eh=qt[8]|0;El=qt[9]|0;Fh=qt[10]|0;Fl=qt[11]|0;Gh=qt[12]|0;Gl=qt[13]|0;Hh=qt[14]|0;Hl=qt[15]|0;constructor(){super(64)}};vt=Vb(()=>new PO,Wb(1)),Sf=Vb(()=>new LO,Wb(3))});function Ef(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function oS(e){if(!Ef(e))throw TypeError("Uint8Array expected")}function MO(e,t){if(!Array.isArray(t))return!1;if(t.length===0)return!0;if(e)return t.every((r)=>typeof r==="string");else return t.every((r)=>Number.isSafeInteger(r))}function qO(e){if(typeof e!=="function")throw TypeError("function expected");return!0}function ri(e,t){if(typeof t!=="string")throw TypeError(`${e}: string expected`);return!0}function tu(e){if(typeof e!=="number")throw TypeError(`number expected, got ${typeof e}`);if(!Number.isSafeInteger(e))throw RangeError(`invalid integer: ${e}`)}function wf(e){if(!Array.isArray(e))throw TypeError("array expected")}function xf(e,t){if(!MO(!0,t))throw TypeError(`${e}: array of strings expected`)}function iS(e,t){if(!MO(!1,t))throw TypeError(`${e}: array of numbers expected`)}function Cr(...e){let t=(i)=>i,r=(i,s)=>(a)=>i(s(a)),o=e.map((i)=>i.encode).reduceRight(r,t),n=e.map((i)=>i.decode).reduce(r,t);return{encode:o,decode:n}}function zr(e){let t=typeof e==="string"?e.split(""):e,r=t.length;xf("alphabet",t);let o=new Map(t.map((n,i)=>[n,i]));return{encode:(n)=>(wf(n),n.map((i)=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return t[i]})),decode:(n)=>(wf(n),n.map((i)=>{ri("alphabet.decode",i);let s=o.get(i);if(s===void 0)throw Error(`Unknown letter: "${i}". Allowed: ${e}`);return s}))}}function Pr(e=""){return ri("join",e),{encode:(t)=>(xf("join.decode",t),t.join(e)),decode:(t)=>(ri("join.decode",t),t.split(e))}}function Af(e,t="="){return tu(e),ri("padding",t),{encode(r){xf("padding.encode",r);while(r.length*e%8)r.push(t);return r},decode(r){xf("padding.decode",r);let o=r.length;if(o*e%8)throw Error("padding: invalid, string should have whole number of bytes");for(;o>0&&r[o-1]===t;o--)if((o-1)*e%8===0)throw Error("padding: invalid, string has too much padding");return r.slice(0,o)}}}function FO(e){return qO(e),{encode:(t)=>t,decode:(t)=>e(t)}}function ZO(e,t,r){if(t<2)throw RangeError(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(r<2)throw RangeError(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(wf(e),!e.length)return[];let o=0,n=[],i=Array.from(e,(a)=>{if(tu(a),a<0||a>=t)throw Error(`invalid integer: ${a}`);return a}),s=i.length;while(!0){let a=0,l=!0;for(let u=o;u<s;u++){let d=i[u],p=t*a,m=p+d;if(!Number.isSafeInteger(m)||p/t!==a||m-d!==p)throw Error("convertRadix: carry overflow");let h=m/r;a=m%r;let S=Math.floor(h);if(i[u]=S,!Number.isSafeInteger(S)||S*r+a!==m)throw Error("convertRadix: carry overflow");if(!l)continue;else if(!S)o=u;else l=!1}if(n.push(a),l)break}for(let a=0;a<e.length-1&&e[a]===0;a++)n.push(0);return n.reverse()}function rS(e,t,r,o){if(wf(e),t<=0||t>32)throw RangeError(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw RangeError(`convertRadix2: wrong to=${r}`);if(_f(t,r)>32)throw Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${_f(t,r)}`);let n=0,i=0,s=vf[t],a=vf[r]-1,l=[];for(let u of e){if(tu(u),u>=s)throw Error(`convertRadix2: invalid data word=${u} from=${t}`);if(n=n<<t|u,i+t>32)throw Error(`convertRadix2: carry overflow pos=${i} from=${t}`);i+=t;for(;i>=r;i-=r)l.push((n>>i-r&a)>>>0);let d=vf[i];if(d===void 0)throw Error("invalid carry");n&=d-1}if(n=n<<r-i&a,!o&&i>=t)throw Error("Excess padding");if(!o&&n>0)throw Error(`Non-zero padding: ${n}`);if(o&&i>0)l.push(n>>>0);return l}function jK(e){tu(e);let t=256;return{encode:(r)=>{if(!Ef(r))throw TypeError("radix.encode input should be Uint8Array");return ZO(Array.from(r),t,e)},decode:(r)=>(iS("radix.decode",r),Uint8Array.from(ZO(r,e,t)))}}function Kr(e,t=!1){if(tu(e),e<=0||e>32)throw RangeError("radix2: bits should be in (0..32]");if(_f(8,e)>32||_f(e,8)>32)throw RangeError("radix2: carry overflow");return{encode:(r)=>{if(!Ef(r))throw TypeError("radix2.encode input should be Uint8Array");return rS(Array.from(r),8,e,!t)},decode:(r)=>(iS("radix2.decode",r),Uint8Array.from(rS(r,e,8,t)))}}function jO(e){return qO(e),function(...t){try{return e.apply(null,t)}catch(r){}}}function eu(e){let t=e>>25,r=(e&33554431)<<5;for(let o=0;o<BO.length;o++)if((t>>o&1)===1)r^=BO[o];return r}function UO(e,t,r=1){let o=e.length,n=1;for(let i=0;i<o;i++){let s=e.charCodeAt(i);if(s<33||s>126)throw Error(`Invalid prefix (${e})`);n=eu(n)^s>>5}n=eu(n);for(let i=0;i<o;i++)n=eu(n)^e.charCodeAt(i)&31;for(let i of t)n=eu(n)^i;for(let i=0;i<6;i++)n=eu(n);return n^=r,nS.encode(rS([n%vf[30]],30,5,!1))}function VO(e){let t=e==="bech32"?1:734539939,r=Kr(5),o=r.decode,n=r.encode,i=jO(o);function s(p,m,h=90){if(ri("bech32.encode prefix",p),Ef(m))m=Array.from(m);iS("bech32.encode",m);let S=p.length;if(S===0)throw TypeError(`Invalid prefix length ${S}`);let y=S+7+m.length;if(h!==!1&&y>h)throw TypeError(`Length ${y} exceeds limit ${h}`);let v=p.toLowerCase(),x=UO(v,m,t);return`${v}1${nS.encode(m)}${x}`}function a(p,m=90){ri("bech32.decode input",p);let h=p.length;if(h<8||m!==!1&&h>m)throw TypeError(`invalid string length: ${h} (${p}). Expected (8..${m})`);let S=p.toLowerCase();if(p!==S&&p!==p.toUpperCase())throw Error("String must be lowercase or uppercase");let y=S.lastIndexOf("1");if(y===0||y===-1)throw Error('Letter "1" must be present between prefix and data only');let v=S.slice(0,y),x=S.slice(y+1);if(x.length<6)throw Error("Data must be at least 6 characters long");let _=nS.decode(x).slice(0,-6),k=UO(v,_,t);if(!x.endsWith(k))throw Error(`Invalid checksum in ${p}: expected "${k}"`);return{prefix:v,words:_}}let l=jO(a);function u(p){let{prefix:m,words:h}=a(p,!1);return{prefix:m,words:h,bytes:o(h)}}function d(p,m){return s(p,n(m))}return{encode:s,decode:a,encodeFromBytes:d,decodeToBytes:u,decodeUnsafe:l,fromWords:o,fromWordsUnsafe:i,toWords:n}}var JO=(e,t)=>t===0?e:JO(t,e%t),_f=(e,t)=>e+(t-JO(e,t)),vf,sbe,abe,cbe,lbe,ube,dbe,KO,BK,HO=(e,t)=>{ri("base64",e);let r=t?"base64url":"base64";if(e.length>0&&BK.test(e))throw Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},sS,Yt,pbe,fbe,aS=(e)=>Cr(jK(58),zr(e),Pr("")),mbe,hbe,gbe,nS,BO,Nr,ybe,UK,MK,bbe;var ru=b(()=>{/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */vf=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();sbe=Object.freeze(Cr(Kr(4),zr("0123456789ABCDEF"),Pr(""))),abe=Object.freeze(Cr(Kr(5),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Af(5),Pr(""))),cbe=Object.freeze(Cr(Kr(5),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Pr(""))),lbe=Object.freeze(Cr(Kr(5),zr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Af(5),Pr(""))),ube=Object.freeze(Cr(Kr(5),zr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Pr(""))),dbe=Object.freeze(Cr(Kr(5),zr("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Pr(""),FO((e)=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),KO=(()=>typeof Uint8Array.from([]).toBase64==="function"&&typeof Uint8Array.fromBase64==="function")(),BK=/[\t\n\f\r ]/,sS=Object.freeze(KO?{encode(e){return oS(e),e.toBase64()},decode(e){return HO(e,!1)}}:Cr(Kr(6),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Af(6),Pr(""))),Yt=Object.freeze(Cr(Kr(6),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Pr(""))),pbe=Object.freeze(KO?{encode(e){return oS(e),e.toBase64({alphabet:"base64url"})},decode(e){return HO(e,!0)}}:Cr(Kr(6),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Af(6),Pr(""))),fbe=Object.freeze(Cr(Kr(6),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Pr(""))),mbe=Object.freeze(aS("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),hbe=Object.freeze(aS("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")),gbe=Object.freeze(aS("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz")),nS=Cr(zr("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Pr("")),BO=[996825010,642813549,513874426,1027748829,705979059];Nr=Object.freeze(VO("bech32")),ybe=Object.freeze(VO("bech32m")),UK=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),MK={encode(e){return oS(e),e.toHex()},decode(e){return ri("hex",e),Uint8Array.fromHex(e)}},bbe=Object.freeze(UK?MK:Cr(Kr(4),zr("0123456789abcdef"),Pr(""),FO((e)=>{if(typeof e!=="string"||e.length%2!==0)throw TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})))});function FK(e,t,r,o){fo(e);let n=gf({dkLen:32,asyncTick:10},o),{c:i,dkLen:s,asyncTick:a}=n;if(St(i,"c"),St(s,"dkLen"),St(a,"asyncTick"),i<1)throw Error("iterations (c) must be >= 1");if(s<1)throw Error('"dkLen" must be >= 1');if(s>4294967295*e.outputLen)throw Error("derived key too long");let l=Kb(t,"password"),u=Kb(r,"salt"),d=new Uint8Array(s),p=zn.create(e,l),m=p._cloneInto().update(u);return{c:i,dkLen:s,asyncTick:a,DK:d,PRF:p,PRFSalt:m}}function JK(e,t,r,o,n){if(e.destroy(),t.destroy(),o)o.destroy();return cr(n),r}function cS(e,t,r,o){let{c:n,dkLen:i,DK:s,PRF:a,PRFSalt:l}=FK(e,t,r,o),u,d=new Uint8Array(4),p=Ra(d),m=new Uint8Array(a.outputLen);for(let h=1,S=0;S<i;h++,S+=a.outputLen){let y=s.subarray(S,S+a.outputLen);p.setInt32(0,h,!1),(u=l._cloneInto(u)).update(d).digestInto(m),y.set(m.subarray(0,y.length));for(let v=1;v<n;v++){a._cloneInto(u).update(m).digestInto(m);for(let x=0;x<y.length;x++)y[x]^=m[x]}}return JK(a,l,s,u,m)}var WO=b(()=>{Gl();Jr()});function GO(e,t,r,o,n,i){let s=e[t++]^r[o++],a=e[t++]^r[o++],l=e[t++]^r[o++],u=e[t++]^r[o++],d=e[t++]^r[o++],p=e[t++]^r[o++],m=e[t++]^r[o++],h=e[t++]^r[o++],S=e[t++]^r[o++],y=e[t++]^r[o++],v=e[t++]^r[o++],x=e[t++]^r[o++],_=e[t++]^r[o++],k=e[t++]^r[o++],O=e[t++]^r[o++],L=e[t++]^r[o++],P=s,K=a,z=l,W=u,ee=d,j=p,T=m,Z=h,A=S,R=y,I=v,q=x,N=_,H=k,G=O,re=L;for(let ae=0;ae<8;ae+=2)ee^=Fe(P+N|0,7),A^=Fe(ee+P|0,9),N^=Fe(A+ee|0,13),P^=Fe(N+A|0,18),R^=Fe(j+K|0,7),H^=Fe(R+j|0,9),K^=Fe(H+R|0,13),j^=Fe(K+H|0,18),G^=Fe(I+T|0,7),z^=Fe(G+I|0,9),T^=Fe(z+G|0,13),I^=Fe(T+z|0,18),W^=Fe(re+q|0,7),Z^=Fe(W+re|0,9),q^=Fe(Z+W|0,13),re^=Fe(q+Z|0,18),K^=Fe(P+W|0,7),z^=Fe(K+P|0,9),W^=Fe(z+K|0,13),P^=Fe(W+z|0,18),T^=Fe(j+ee|0,7),Z^=Fe(T+j|0,9),ee^=Fe(Z+T|0,13),j^=Fe(ee+Z|0,18),q^=Fe(I+R|0,7),A^=Fe(q+I|0,9),R^=Fe(A+q|0,13),I^=Fe(R+A|0,18),N^=Fe(re+G|0,7),H^=Fe(N+re|0,9),G^=Fe(H+N|0,13),re^=Fe(G+H|0,18);n[i++]=s+P|0,n[i++]=a+K|0,n[i++]=l+z|0,n[i++]=u+W|0,n[i++]=d+ee|0,n[i++]=p+j|0,n[i++]=m+T|0,n[i++]=h+Z|0,n[i++]=S+A|0,n[i++]=y+R|0,n[i++]=v+I|0,n[i++]=x+q|0,n[i++]=_+N|0,n[i++]=k+H|0,n[i++]=O+G|0,n[i++]=L+re|0}function lS(e,t,r,o,n){let i=o+0,s=o+16*n;for(let a=0;a<16;a++)r[s+a]=e[t+(2*n-1)*16+a];for(let a=0;a<n;a++,i+=16,t+=16){if(GO(r,s,e,t,r,i),a>0)s+=16;GO(r,i,e,t+=16,r,s)}}function KK(e,t,r){let o=gf({dkLen:32,asyncTick:10,maxmem:1073742848},r),{N:n,r:i,p:s,dkLen:a,asyncTick:l,maxmem:u,onProgress:d}=o;if(St(n,"N"),St(i,"r"),St(s,"p"),St(a,"dkLen"),St(l,"asyncTick"),St(u,"maxmem"),d!==void 0&&typeof d!=="function")throw Error("progressCb must be a function");let p=128*i,m=p/4,h=Math.pow(2,32);if(n<=1||(n&n-1)!==0||n>h)throw Error('"N" expected a power of 2, and 2^1 <= N <= 2^32');if(s<1||s>(h-1)*32/p)throw Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)');if(a<1||a>(h-1)*32)throw Error('"dkLen" expected integer 1..(2^32 - 1) * 32');let S=p*(n+s+1);if(S>u)throw Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))='+S+", maxmem="+u);let y=cS(vt,e,t,{c:1,dkLen:p*s}),v=mf(y),x=mf(new Uint8Array(p*n)),_=mf(new Uint8Array(p)),k=()=>{};if(d){let O=2*n*s,L=Math.max(Math.floor(O/1e4),1),P=0;k=()=>{if(P++,d&&(!(P%L)||P===O))d(P/O)}}return{N:n,r:i,p:s,dkLen:a,blockSize32:m,V:x,B32:v,B:y,tmp:_,blockMixCb:k,asyncTick:l}}function HK(e,t,r,o,n){let i=cS(vt,e,r,{c:1,dkLen:t});return cr(r,o,n),i}function uS(e,t,r){let{N:o,r:n,p:i,dkLen:s,blockSize32:a,V:l,B32:u,B:d,tmp:p,blockMixCb:m}=KK(e,t,r);Jb(u);for(let h=0;h<i;h++){let S=a*h;for(let y=0;y<a;y++)l[y]=u[S+y];for(let y=0,v=0;y<o-1;y++)lS(l,v,l,v+=a,n),m();lS(l,(o-1)*a,u,S,n),m();for(let y=0;y<o;y++){let v=(u[S+a-16]&o-1)>>>0;for(let x=0;x<a;x++)p[x]=u[S+x]^l[v*a+x];lS(p,0,u,S,n),m()}}return Jb(u),HK(e,s,d,l,p)}var QO=b(()=>{WO();Ta();Jr()});function VK(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function If(e){if(typeof e!=="boolean")throw TypeError(`boolean expected, not ${e}`)}function $a(e){if(typeof e!=="number")throw TypeError("number expected, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError("positive integer expected, got "+e)}function $t(e,t,r=""){let o=VK(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+l;if(!o)throw TypeError(u);throw RangeError(u)}return e}function dS(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function YO(e,t,r=!1){$t(e,void 0,"output");let o=t.outputLen;if(e.length<o)throw RangeError("digestInto() expects output buffer of length at least "+o);if(r&&!Oa(e))throw Error("invalid output, must be aligned")}function Nn(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function un(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function WK(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function XO(e,t){if(t==null||typeof t!=="object")throw Error("options must be defined");return Object.assign(e,t)}function eC(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function tC(e,t,r){let o=t,n=r||(()=>[]),i=(a,l)=>o(l,...n(a)).update(a).digest(),s=o(new Uint8Array(e),...n(new Uint8Array(0)));return i.outputLen=s.outputLen,i.blockLen=s.blockLen,i.create=(a,...l)=>o(a,...l),i}function nu(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if($t(t,void 0,"output"),t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!Oa(t))throw Error("invalid output, must be aligned");return t}function nC(e,t,r){$a(e),$a(t),If(r);let o=new Uint8Array(16),n=WK(o);return n.setBigUint64(0,BigInt(t),r),n.setBigUint64(8,BigInt(e),r),o}function Oa(e){return e.byteOffset%4===0}function Ca(e){return Uint8Array.from($t(e))}var gs,GK=(e)=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255,QK=(e)=>{for(let t=0;t<e.length;t++)e[t]=GK(e[t]);return e},go,rC=(e,t)=>{function r(o,...n){if($t(o,void 0,"key"),e.nonceLength!==void 0){let d=n[0];$t(d,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let i=e.tagLength;if(i&&n[1]!==void 0)$t(n[1],void 0,"AAD");let s=t(o,...n),a=(d,p)=>{if(p!==void 0){if(d!==2)throw Error("cipher output not supported");$t(p,void 0,"output")}},l=!1;return{encrypt(d,p){if(l)throw Error("cannot encrypt() twice with same key + nonce");return l=!0,$t(d),a(s.encrypt.length,p),s.encrypt(d,p)},decrypt(d,p){if($t(d),i&&d.length<i)throw Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,p),s.decrypt(d,p)}}}return Object.assign(r,e),r};var kf=b(()=>{/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */gs=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)(),go=gs?(e)=>e:QK});function Je(e,t){return e<<t|e>>>32-t}function tH(e,t,r,o,n,i,s,a){let l=n.length,u=new Uint8Array(ou),d=Nn(u),p=gs&&Oa(n)&&Oa(i),m=p?Nn(n):oC,h=p?Nn(i):oC;if(!gs){for(let S=0;S<l;s++){if(e(t,r,o,d,s,a),go(d),s>=pS)throw Error("arx: counter overflow");let y=Math.min(ou,l-S);for(let v=0,x;v<y;v++)x=S+v,i[x]=n[x]^u[v];S+=y}return}for(let S=0;S<l;s++){if(e(t,r,o,d,s,a),s>=pS)throw Error("arx: counter overflow");let y=Math.min(ou,l-S);if(p&&y===ou){let v=S/4;if(S%4!==0)throw Error("arx: invalid block position");for(let x=0,_;x<eH;x++)_=v+x,h[_]=m[_]^d[x];S+=ou;continue}for(let v=0,x;v<y;v++)x=S+v,i[x]=n[x]^u[v];S+=y}}function sC(e,t){let{allowShortKeys:r,extendNonceFn:o,counterLength:n,counterRight:i,rounds:s}=XO({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=="function")throw Error("core must be a function");return $a(n),$a(s),If(i),If(r),(a,l,u,d,p=0)=>{$t(a,void 0,"key"),$t(l,void 0,"nonce"),$t(u,void 0,"data");let m=u.length;if(d=nu(m,d,!1),$a(p),p<0||p>=pS)throw Error("arx: counter overflow");let h=[],S=a.length,y,v;if(S===32)h.push(y=Ca(a)),v=XK;else if(S===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),v=YK,h.push(y);else throw $t(a,32,"arx key"),Error("invalid key size");if(!gs||!Oa(l))h.push(l=Ca(l));let x=Nn(y);if(o){if(l.length!==24)throw Error("arx: extended nonce must be 24 bytes");let O=l.subarray(0,16);if(gs)o(v,x,Nn(O),x);else{let L=go(Uint32Array.from(v));o(L,x,Nn(O),x),un(L),go(x)}l=l.subarray(16)}else if(!gs)go(x);let _=16-n;if(_!==l.length)throw Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){let O=new Uint8Array(12);O.set(l,i?0:12-l.length),l=O,h.push(l)}let k=go(Nn(l));try{return tH(e,v,x,k,u,d,p,s),d}finally{un(...h)}}}var iC=(e)=>Uint8Array.from(e.split(""),(t)=>t.charCodeAt(0)),YK,XK,ou=64,eH=16,pS,oC;var aC=b(()=>{kf();YK=(()=>go(Nn(iC("expand 16-byte k"))))(),XK=(()=>go(Nn(iC("expand 32-byte k"))))();pS=(()=>4294967295)(),oC=Uint32Array.of()});function Ft(e,t){return e[t++]&255|(e[t++]&255)<<8}class cC{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Ca($t(e,32,"key"));let t=Ft(e,0),r=Ft(e,2),o=Ft(e,4),n=Ft(e,6),i=Ft(e,8),s=Ft(e,10),a=Ft(e,12),l=Ft(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|n<<9)&8191,this.r[4]=(n>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|s<<2)&8191,this.r[7]=(s>>>11|a<<5)&8065,this.r[8]=(a>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ft(e,16+2*u)}process(e,t,r=!1){let o=r?0:2048,{h:n,r:i}=this,s=i[0],a=i[1],l=i[2],u=i[3],d=i[4],p=i[5],m=i[6],h=i[7],S=i[8],y=i[9],v=Ft(e,t+0),x=Ft(e,t+2),_=Ft(e,t+4),k=Ft(e,t+6),O=Ft(e,t+8),L=Ft(e,t+10),P=Ft(e,t+12),K=Ft(e,t+14),z=n[0]+(v&8191),W=n[1]+((v>>>13|x<<3)&8191),ee=n[2]+((x>>>10|_<<6)&8191),j=n[3]+((_>>>7|k<<9)&8191),T=n[4]+((k>>>4|O<<12)&8191),Z=n[5]+(O>>>1&8191),A=n[6]+((O>>>14|L<<2)&8191),R=n[7]+((L>>>11|P<<5)&8191),I=n[8]+((P>>>8|K<<8)&8191),q=n[9]+(K>>>5|o),N=0,H=N+z*s+W*(5*y)+ee*(5*S)+j*(5*h)+T*(5*m);N=H>>>13,H&=8191,H+=Z*(5*p)+A*(5*d)+R*(5*u)+I*(5*l)+q*(5*a),N+=H>>>13,H&=8191;let G=N+z*a+W*s+ee*(5*y)+j*(5*S)+T*(5*h);N=G>>>13,G&=8191,G+=Z*(5*m)+A*(5*p)+R*(5*d)+I*(5*u)+q*(5*l),N+=G>>>13,G&=8191;let re=N+z*l+W*a+ee*s+j*(5*y)+T*(5*S);N=re>>>13,re&=8191,re+=Z*(5*h)+A*(5*m)+R*(5*p)+I*(5*d)+q*(5*u),N+=re>>>13,re&=8191;let ae=N+z*u+W*l+ee*a+j*s+T*(5*y);N=ae>>>13,ae&=8191,ae+=Z*(5*S)+A*(5*h)+R*(5*m)+I*(5*p)+q*(5*d),N+=ae>>>13,ae&=8191;let me=N+z*d+W*u+ee*l+j*a+T*s;N=me>>>13,me&=8191,me+=Z*(5*y)+A*(5*S)+R*(5*h)+I*(5*m)+q*(5*p),N+=me>>>13,me&=8191;let Se=N+z*p+W*d+ee*u+j*l+T*a;N=Se>>>13,Se&=8191,Se+=Z*s+A*(5*y)+R*(5*S)+I*(5*h)+q*(5*m),N+=Se>>>13,Se&=8191;let xe=N+z*m+W*p+ee*d+j*u+T*l;N=xe>>>13,xe&=8191,xe+=Z*a+A*s+R*(5*y)+I*(5*S)+q*(5*h),N+=xe>>>13,xe&=8191;let ke=N+z*h+W*m+ee*p+j*d+T*u;N=ke>>>13,ke&=8191,ke+=Z*l+A*a+R*s+I*(5*y)+q*(5*S),N+=ke>>>13,ke&=8191;let Ie=N+z*S+W*h+ee*m+j*p+T*d;N=Ie>>>13,Ie&=8191,Ie+=Z*u+A*l+R*a+I*s+q*(5*y),N+=Ie>>>13,Ie&=8191;let _e=N+z*y+W*S+ee*h+j*m+T*p;N=_e>>>13,_e&=8191,_e+=Z*d+A*u+R*l+I*a+q*s,N+=_e>>>13,_e&=8191,N=(N<<2)+N|0,N=N+H|0,H=N&8191,N=N>>>13,G+=N,n[0]=H,n[1]=G,n[2]=re,n[3]=ae,n[4]=me,n[5]=Se,n[6]=xe,n[7]=ke,n[8]=Ie,n[9]=_e}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let s=2;s<10;s++)e[s]+=o,o=e[s]>>>13,e[s]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let s=1;s<10;s++)r[s]=e[s]+o,o=r[s]>>>13,r[s]&=8191;r[9]-=8192;let n=(o^1)-1;for(let s=0;s<10;s++)r[s]&=n;n=~n;for(let s=0;s<10;s++)e[s]=e[s]&n|r[s];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let s=1;s<8;s++)i=(e[s]+t[s]|0)+(i>>>16)|0,e[s]=i&65535;un(r)}update(e){dS(this),$t(e),e=Ca(e);let{buffer:t,blockLen:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(r-this.pos,o-n);if(i===r){for(;r<=o-n;n+=r)this.process(e,n);continue}if(t.set(e.subarray(n,n+i),this.pos),this.pos+=i,n+=i,this.pos===r)this.process(t,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,un(this.h,this.r,this.buffer,this.pad)}digestInto(e){dS(this),YO(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:o}=this;if(o){t[o++]=1;for(;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let i=0;i<8;i++)e[n++]=r[i]>>>0,e[n++]=r[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}var lC;var uC=b(()=>{kf();lC=tC(32,(e)=>new cC(e))});function rH(e,t,r,o,n,i=20){let s=e[0],a=e[1],l=e[2],u=e[3],d=t[0],p=t[1],m=t[2],h=t[3],S=t[4],y=t[5],v=t[6],x=t[7],_=n,k=r[0],O=r[1],L=r[2],P=s,K=a,z=l,W=u,ee=d,j=p,T=m,Z=h,A=S,R=y,I=v,q=x,N=_,H=k,G=O,re=L;for(let me=0;me<i;me+=2)P=P+ee|0,N=Je(N^P,16),A=A+N|0,ee=Je(ee^A,12),P=P+ee|0,N=Je(N^P,8),A=A+N|0,ee=Je(ee^A,7),K=K+j|0,H=Je(H^K,16),R=R+H|0,j=Je(j^R,12),K=K+j|0,H=Je(H^K,8),R=R+H|0,j=Je(j^R,7),z=z+T|0,G=Je(G^z,16),I=I+G|0,T=Je(T^I,12),z=z+T|0,G=Je(G^z,8),I=I+G|0,T=Je(T^I,7),W=W+Z|0,re=Je(re^W,16),q=q+re|0,Z=Je(Z^q,12),W=W+Z|0,re=Je(re^W,8),q=q+re|0,Z=Je(Z^q,7),P=P+j|0,re=Je(re^P,16),I=I+re|0,j=Je(j^I,12),P=P+j|0,re=Je(re^P,8),I=I+re|0,j=Je(j^I,7),K=K+T|0,N=Je(N^K,16),q=q+N|0,T=Je(T^q,12),K=K+T|0,N=Je(N^K,8),q=q+N|0,T=Je(T^q,7),z=z+Z|0,H=Je(H^z,16),A=A+H|0,Z=Je(Z^A,12),z=z+Z|0,H=Je(H^z,8),A=A+H|0,Z=Je(Z^A,7),W=W+ee|0,G=Je(G^W,16),R=R+G|0,ee=Je(ee^R,12),W=W+ee|0,G=Je(G^W,8),R=R+G|0,ee=Je(ee^R,7);let ae=0;o[ae++]=s+P|0,o[ae++]=a+K|0,o[ae++]=l+z|0,o[ae++]=u+W|0,o[ae++]=d+ee|0,o[ae++]=p+j|0,o[ae++]=m+T|0,o[ae++]=h+Z|0,o[ae++]=S+A|0,o[ae++]=y+R|0,o[ae++]=v+I|0,o[ae++]=x+q|0,o[ae++]=_+N|0,o[ae++]=k+H|0,o[ae++]=O+G|0,o[ae++]=L+re|0}function pC(e,t,r,o,n){if(n!==void 0)$t(n,void 0,"AAD");let i=e(t,r,iH),s=nC(o.length,n?n.length:0,!0),a=lC.create(i);if(n)dC(a,n);dC(a,o),a.update(s);let l=a.digest();return un(i,s),l}var nH,oH,dC=(e,t)=>{e.update(t);let r=t.length%16;if(r)e.update(oH.subarray(r))},iH,sH=(e)=>(t,r,o)=>({encrypt(i,s){let a=i.length;s=nu(a+16,s,!1),s.set(i);let l=s.subarray(0,-16);e(t,r,l,l,1);let u=pC(e,t,r,l,o);return s.set(u,a),un(u),s},decrypt(i,s){s=nu(i.length-16,s,!1);let a=i.subarray(0,-16),l=i.subarray(-16),u=pC(e,t,r,a,o);if(!eC(l,u))throw un(u),Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,r,s,s,1),un(u),s}}),Hr;var fS=b(()=>{aC();uC();kf();nH=sC(rH,{counterRight:!1,counterLength:4,allowShortKeys:!1}),oH=new Uint8Array(16),iH=new Uint8Array(32);Hr=rC({blockSize:64,nonceLength:12,tagLength:16},sH(nH))});function za(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Zt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw Error(`${r}expected integer >= 0, got ${e}`)}}function Re(e,t,r=""){let o=za(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`;throw Error(s+"expected Uint8Array"+a+", got "+l)}return e}function Vr(e){if(typeof e!=="function"||typeof e.create!=="function")throw Error("Hash must wrapped by utils.createHasher");Zt(e.outputLen),Zt(e.blockLen)}function bo(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Rf(e,t){Re(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw Error('"digestInto() output" expected to be of length >='+r)}function Tf(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function wr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function $f(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function dn(e,t){return e<<32-t|e>>>t}function cH(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function lH(e){for(let t=0;t<e.length;t++)e[t]=cH(e[t]);return e}function ys(e){if(Re(e),mC)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=uH[e[r]];return t}function fC(e){if(e>=yo._0&&e<=yo._9)return e-yo._0;if(e>=yo.A&&e<=yo.F)return e-(yo.A-10);if(e>=yo.a&&e<=yo.f)return e-(yo.a-10);return}function bs(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);if(mC)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=fC(e.charCodeAt(i)),a=fC(e.charCodeAt(i+1));if(s===void 0||a===void 0){let l=e[i]+e[i+1];throw Error('hex string expected, got non-hex character "'+l+'" at index '+i)}o[n]=s*16+a}return o}function At(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Re(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function Pa(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function ni(e=32){let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}var aH,mS,mC,uH,yo,oi=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Dr=b(()=>{/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */aH=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();mS=aH?(e)=>e:lH,mC=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),uH=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));yo={_0:48,_9:57,A:65,F:70,a:97,f:102}});function iu(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw Error(r+"expected boolean, got type="+typeof e)}return e}function hC(e){if(typeof e==="bigint"){if(!Of(e))throw Error("positive bigint expected, got "+e)}else Zt(e);return e}function su(e){let t=hC(e).toString(16);return t.length&1?"0"+t:t}function gC(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);return e===""?gS:BigInt("0x"+e)}function ii(e){return gC(ys(e))}function si(e){return gC(ys(Cf(Re(e)).reverse()))}function Na(e,t){Zt(t),e=hC(e);let r=bs(e.toString(16).padStart(t*2,"0"));if(r.length!==t)throw Error("number too large");return r}function au(e,t){return Na(e,t).reverse()}function Cf(e){return Uint8Array.from(e)}function ai(e){return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw Error(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}function dH(e,t,r){return Of(e)&&Of(t)&&Of(r)&&t<=e&&e<r}function cu(e,t,r,o){if(!dH(t,r,o))throw Error("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function yS(e){let t;for(t=0;e>gS;e>>=hS,t+=1);return t}function yC(e,t,r){if(Zt(e,"hashLen"),Zt(t,"qByteLen"),typeof r!=="function")throw Error("hmacFn must be a function");let o=(v)=>new Uint8Array(v),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,l=o(e),u=o(e),d=0,p=()=>{l.fill(1),u.fill(0),d=0},m=(...v)=>r(u,At(l,...v)),h=(v=n)=>{if(u=m(i,v),l=m(),v.length===0)return;u=m(s,v),l=m()},S=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let v=0,x=[];while(v<t){l=m();let _=l.slice();x.push(_),v+=l.length}return At(...x)};return(v,x)=>{p(),h(v);let _=void 0;while(!(_=x(S())))h();return p(),_}}function Ss(e,t={},r={}){if(!e||typeof e!=="object")throw Error("expected valid options object");function o(i,s,a){let l=e[i];if(a&&l===void 0)return;let u=typeof l;if(u!==s||l===null)throw Error(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,l])=>o(a,l,s));n(t,!1),n(r,!0)}function bS(e){let t=new WeakMap;return(r,...o)=>{let n=t.get(r);if(n!==void 0)return n;let i=e(r,...o);return t.set(r,i),i}}var gS,hS,Of=(e)=>typeof e==="bigint"&&gS<=e,lu=(e)=>(hS<<BigInt(e))-hS;var Da=b(()=>{Dr();Dr();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */gS=BigInt(0),hS=BigInt(1)});function lr(e,t){let r=e%t;return r>=ur?r:t+r}function Wr(e,t,r){let o=e;while(t-- >ur)o*=o,o%=r;return o}function bC(e,t){if(e===ur)throw Error("invert: expected non-zero number");if(t<=ur)throw Error("invert: expected positive modulus, got "+t);let r=lr(e,t),o=t,n=ur,i=Xt,s=Xt,a=ur;while(r!==ur){let u=o/r,d=o%r,p=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=p,a=m}if(o!==Xt)throw Error("invert: does not exist");return lr(n,t)}function SS(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function AC(e,t){let r=(e.ORDER+Xt)/wC,o=e.pow(t,r);return SS(e,o,t),o}function mH(e,t){let r=(e.ORDER-xC)/_C,o=e.mul(t,vs),n=e.pow(o,r),i=e.mul(t,n),s=e.mul(e.mul(i,vs),n),a=e.mul(i,e.sub(s,e.ONE));return SS(e,a,t),a}function hH(e){let t=zf(e),r=IC(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+pH)/EC;return(a,l)=>{let u=a.pow(l,s),d=a.mul(u,o),p=a.mul(u,n),m=a.mul(u,i),h=a.eql(a.sqr(d),l),S=a.eql(a.sqr(p),l);u=a.cmov(u,d,h),d=a.cmov(m,p,S);let y=a.eql(a.sqr(d),l),v=a.cmov(u,d,y);return SS(a,v,l),v}}function IC(e){if(e<vC)throw Error("sqrt is not defined for small field");let t=e-Xt,r=0;while(t%vs===ur)t/=vs,r++;let o=vs,n=zf(e);while(SC(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return AC;let i=n.pow(o,t),s=(t+Xt)/vs;return function(l,u){if(l.is0(u))return u;if(SC(l,u)!==1)throw Error("Cannot find square root");let d=r,p=l.mul(l.ONE,i),m=l.pow(u,t),h=l.pow(u,s);while(!l.eql(m,l.ONE)){if(l.is0(m))return l.ZERO;let S=1,y=l.sqr(m);while(!l.eql(y,l.ONE))if(S++,y=l.sqr(y),S===d)throw Error("Cannot find square root");let v=Xt<<BigInt(d-S-1),x=l.pow(p,v);d=S,p=l.sqr(x),m=l.mul(m,p),h=l.mul(h,x)}return h}}function gH(e){if(e%wC===vC)return AC;if(e%_C===xC)return mH;if(e%EC===fH)return hH(e);return IC(e)}function vS(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=yH.reduce((o,n)=>(o[n]="function",o),t);return Ss(e,r),e}function bH(e,t,r){if(r<ur)throw Error("invalid exponent, negatives unsupported");if(r===ur)return e.ONE;if(r===Xt)return t;let o=e.ONE,n=t;while(r>ur){if(r&Xt)o=e.mul(o,n);n=e.sqr(n),r>>=Xt}return o}function uu(e,t,r=!1){let o=Array(t.length).fill(r?e.ZERO:void 0),n=t.reduce((s,a,l)=>{if(e.is0(a))return s;return o[l]=s,e.mul(s,a)},e.ONE),i=e.inv(n);return t.reduceRight((s,a,l)=>{if(e.is0(a))return s;return o[l]=e.mul(s,o[l]),e.mul(s,a)},i),o}function SC(e,t){let r=(e.ORDER-Xt)/vs,o=e.pow(t,r),n=e.eql(o,e.ONE),i=e.eql(o,e.ZERO),s=e.eql(o,e.neg(e.ONE));if(!n&&!i&&!s)throw Error("invalid Legendre symbol result");return n?1:i?0:-1}function SH(e,t){if(t!==void 0)Zt(t);let r=t!==void 0?t:e.toString(2).length,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}class kC{ORDER;BITS;BYTES;isLE;ZERO=ur;ONE=Xt;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=ur)throw Error("invalid field: expected ORDER > 0, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")this.sqrt=t.sqrt;if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=t.allowedLengths?.slice();if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=SH(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return lr(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof e);return ur<=e&&e<this.ORDER}is0(e){return e===ur}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Xt)===Xt}neg(e){return lr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return lr(e*e,this.ORDER)}add(e,t){return lr(e+t,this.ORDER)}sub(e,t){return lr(e-t,this.ORDER)}mul(e,t){return lr(e*t,this.ORDER)}pow(e,t){return bH(this,e,t)}div(e,t){return lr(e*bC(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return bC(e,this.ORDER)}sqrt(e){if(!this._sqrt)this._sqrt=gH(this.ORDER);return this._sqrt(this,e)}toBytes(e){return this.isLE?au(e,this.BYTES):Na(e,this.BYTES)}fromBytes(e,t=!1){Re(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,n?0:l.length-e.length),e=l}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?si(e):ii(e);if(s)a=lr(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return uu(this,e)}cmov(e,t,r){return r?t:e}}function zf(e,t={}){return new kC(e,t)}function RC(e){if(typeof e!=="bigint")throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function wS(e){let t=RC(e);return t+Math.ceil(t/2)}function TC(e,t,r=!1){Re(e);let o=e.length,n=RC(t),i=wS(t);if(o<16||o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?si(e):ii(e),a=lr(s,t-Xt)+Xt;return r?au(a,n):Na(a,n)}var ur,Xt,vs,vC,wC,xC,pH,_C,fH,EC,yH;var du=b(()=>{Da();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ur=BigInt(0),Xt=BigInt(1),vs=BigInt(2),vC=BigInt(3),wC=BigInt(4),xC=BigInt(5),pH=BigInt(7),_C=BigInt(8),fH=BigInt(9),EC=BigInt(16);yH=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function pu(e,t){let r=t.negate();return e?r:t}function AS(e,t){let r=uu(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function zC(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function xS(e,t){zC(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=lu(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function $C(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),l=e>>s;if(a>o)a-=i,l+=ws;let u=t*o,d=u+Math.abs(a)-1,p=a===0,m=a<0,h=t%2!==0;return{nextN:l,offset:d,isZero:p,isNeg:m,isNegF:h,offsetF:u}}function ES(e){return PC.get(e)||1}function OC(e){if(e!==La)throw Error("invalid wNAF")}class IS{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>La){if(t&ws)r=r.add(o);o=o.double(),t>>=ws}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=xS(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let l=1;l<o;l++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=xS(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:m}=$C(r,s,i);if(r=a,u)n=n.add(pu(p,t[m]));else o=o.add(pu(d,t[l]))}return OC(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=xS(e,this.bits);for(let i=0;i<n.windows;i++){if(r===La)break;let{nextN:s,offset:a,isZero:l,isNeg:u}=$C(r,i,n);if(r=s,l)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return OC(r),o}getPrecomputes(e,t,r){let o=_S.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);_S.set(t,o)}}return o}cached(e,t,r){let o=ES(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=ES(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){zC(t,this.bits),PC.set(e,t),_S.delete(e)}hasCache(e){return ES(e)!==1}}function NC(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>La||o>La){if(r&ws)i=i.add(n);if(o&ws)s=s.add(n);n=n.double(),r>>=ws,o>>=ws}return{p1:i,p2:s}}function CC(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return vS(t),t}else return zf(e,{isLE:r})}function DC(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let l of["p","n","h"]){let u=t[l];if(!(typeof u==="bigint"&&u>La))throw Error(`CURVE.${l} must be positive bigint`)}let n=CC(t.p,r.Fp,o),i=CC(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(t[l]))throw Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function Pf(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}var La,ws,_S,PC;var kS=b(()=>{Da();du();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */La=BigInt(0),ws=BigInt(1);_S=new WeakMap,PC=new WeakMap});function vH(e){return Ss(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function LC(e){let t=vH(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let l=s||ni,u=a?255:448,d=a?32:56,p=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?Nf**BigInt(254):Nf**BigInt(447),S=a?BigInt(8)*Nf**BigInt(251)-Za:BigInt(4)*Nf**BigInt(445)-Za,y=h+S+Za,v=(A)=>lr(A,r),x=_(p);function _(A){return au(v(A),d)}function k(A){let R=Cf(Re(A,d,"uCoordinate"));if(a)R[31]&=127;return v(si(R))}function O(A){return si(n(Cf(Re(A,d,"scalar"))))}function L(A,R){let I=ee(k(R),O(A));if(I===fu)throw Error("invalid private or public key received");return _(I)}function P(A){return L(A,x)}let K=P,z=L;function W(A,R,I){let q=v(A*(R-I));return R=v(R-q),I=v(I+q),{x_2:R,x_3:I}}function ee(A,R){cu("u",A,fu,r),cu("scalar",R,h,y);let I=R,q=A,N=Za,H=fu,G=A,re=Za,ae=fu;for(let Se=BigInt(u-1);Se>=fu;Se--){let xe=I>>Se&Za;ae^=xe,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=xe;let ke=N+H,Ie=v(ke*ke),_e=N-H,Ue=v(_e*_e),De=Ie-Ue,Qe=G+re,bt=G-re,Tt=v(bt*ke),Dt=v(Qe*_e),lt=Tt+Dt,Or=Tt-Dt;G=v(lt*lt),re=v(q*v(Or*Or)),N=v(Ie*Ue),H=v(De*(Ie+v(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let me=i(H);return v(N*me)}let j={secretKey:d,publicKey:d,seed:d},T=(A=l(d))=>(Re(A,j.seed,"seed"),A),Z={randomSecretKey:T};return Object.freeze({keygen:Pf(T,K),getSharedSecret:z,getPublicKey:K,scalarMult:L,scalarMultBase:P,utils:Z,GuBytes:x.slice(),lengths:j})}var fu,Za,Nf;var ZC=b(()=>{Da();kS();du();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */fu=BigInt(0),Za=BigInt(1),Nf=BigInt(2)});class RS{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Vr(e),Re(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),wr(o)}update(e){return bo(this),this.iHash.update(e),this}digestInto(e){bo(this),Re(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var ja=(e,t,r)=>new RS(e,t).update(r).digest();var TS=b(()=>{Dr();ja.create=(e,t)=>new RS(e,t)});function wH(e,t,r){let[[o,n],[i,s]]=t,a=jC(s*e,r),l=jC(-n*e,r),u=e-a*o-l*i,d=-a*n-l*s,p=u<So,m=d<So;if(p)u=-u;if(m)d=-d;let h=lu(Math.ceil(yS(r)/2))+Ba;if(u<So||u>=h||d<So||d>=h)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:p,k1:u,k2neg:m,k2:d}}function OS(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function $S(e,t){let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(iu(r.lowS,"lowS"),iu(r.prehash,"prehash"),r.format!==void 0)OS(r.format);return r}function CS(e,t={}){let r=DC("weierstrass",e,t),{Fp:o,Fn:n}=r,i=r.CURVE,{h:s,n:a}=i;Ss(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:l}=t;if(l){if(!o.is0(i.a)||typeof l.beta!=="bigint"||!Array.isArray(l.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let u=qC(o,n);function d(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function p(T,Z,A){let{x:R,y:I}=Z.toAffine(),q=o.toBytes(R);if(iu(A,"isCompressed"),A){d();let N=!o.isOdd(I);return At(MC(N),q)}else return At(Uint8Array.of(4),q,o.toBytes(I))}function m(T){Re(T,void 0,"Point");let{publicKey:Z,publicKeyUncompressed:A}=u,R=T.length,I=T[0],q=T.subarray(1);if(R===Z&&(I===2||I===3)){let N=o.fromBytes(q);if(!o.isValid(N))throw Error("bad point: is not on curve, wrong x");let H=y(N),G;try{G=o.sqrt(H)}catch(me){let Se=me instanceof Error?": "+me.message:"";throw Error("bad point: is not on curve, sqrt error"+Se)}d();let re=o.isOdd(G);if((I&1)===1!==re)G=o.neg(G);return{x:N,y:G}}else if(R===A&&I===4){let N=o.BYTES,H=o.fromBytes(q.subarray(0,N)),G=o.fromBytes(q.subarray(N,N*2));if(!v(H,G))throw Error("bad point: is not on curve");return{x:H,y:G}}else throw Error(`bad point: got length ${R}, expected compressed=${Z} or uncompressed=${A}`)}let h=t.toBytes||p,S=t.fromBytes||m;function y(T){let Z=o.sqr(T),A=o.mul(Z,T);return o.add(o.add(A,o.mul(T,i.a)),i.b)}function v(T,Z){let A=o.sqr(Z),R=y(T);return o.eql(A,R)}if(!v(i.Gx,i.Gy))throw Error("bad curve params: generator point");let x=o.mul(o.pow(i.a,Df),xH),_=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(x,_)))throw Error("bad curve params: a or b");function k(T,Z,A=!1){if(!o.isValid(Z)||A&&o.is0(Z))throw Error(`bad point coordinate ${T}`);return Z}function O(T){if(!(T instanceof W))throw Error("Weierstrass Point expected")}function L(T){if(!l||!l.basises)throw Error("no endo");return wH(T,l.basises,n.ORDER)}let P=bS((T,Z)=>{let{X:A,Y:R,Z:I}=T;if(o.eql(I,o.ONE))return{x:A,y:R};let q=T.is0();if(Z==null)Z=q?o.ONE:o.inv(I);let N=o.mul(A,Z),H=o.mul(R,Z),G=o.mul(I,Z);if(q)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}),K=bS((T)=>{if(T.is0()){if(t.allowInfinityPoint&&!o.is0(T.Y))return;throw Error("bad point: ZERO")}let{x:Z,y:A}=T.toAffine();if(!o.isValid(Z)||!o.isValid(A))throw Error("bad point: x or y not field elements");if(!v(Z,A))throw Error("bad point: equation left != right");if(!T.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});function z(T,Z,A,R,I){return A=new W(o.mul(A.X,T),A.Y,A.Z),Z=pu(R,Z),A=pu(I,A),Z.add(A)}class W{static BASE=new W(i.Gx,i.Gy,o.ONE);static ZERO=new W(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(T,Z,A){this.X=k("x",T),this.Y=k("y",Z,!0),this.Z=k("z",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(T){let{x:Z,y:A}=T||{};if(!T||!o.isValid(Z)||!o.isValid(A))throw Error("invalid affine point");if(T instanceof W)throw Error("projective point not allowed");if(o.is0(Z)&&o.is0(A))return W.ZERO;return new W(Z,A,o.ONE)}static fromBytes(T){let Z=W.fromAffine(S(Re(T,void 0,"point")));return Z.assertValidity(),Z}static fromHex(T){return W.fromBytes(bs(T))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(T=8,Z=!0){if(j.createCache(this,T),!Z)this.multiply(Df);return this}assertValidity(){K(this)}hasEvenY(){let{y:T}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(T)}equals(T){O(T);let{X:Z,Y:A,Z:R}=this,{X:I,Y:q,Z:N}=T,H=o.eql(o.mul(Z,N),o.mul(I,R)),G=o.eql(o.mul(A,N),o.mul(q,R));return H&&G}negate(){return new W(this.X,o.neg(this.Y),this.Z)}double(){let{a:T,b:Z}=i,A=o.mul(Z,Df),{X:R,Y:I,Z:q}=this,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=o.mul(R,R),ae=o.mul(I,I),me=o.mul(q,q),Se=o.mul(R,I);return Se=o.add(Se,Se),G=o.mul(R,q),G=o.add(G,G),N=o.mul(T,G),H=o.mul(A,me),H=o.add(N,H),N=o.sub(ae,H),H=o.add(ae,H),H=o.mul(N,H),N=o.mul(Se,N),G=o.mul(A,G),me=o.mul(T,me),Se=o.sub(re,me),Se=o.mul(T,Se),Se=o.add(Se,G),G=o.add(re,re),re=o.add(G,re),re=o.add(re,me),re=o.mul(re,Se),H=o.add(H,re),me=o.mul(I,q),me=o.add(me,me),re=o.mul(me,Se),N=o.sub(N,re),G=o.mul(me,ae),G=o.add(G,G),G=o.add(G,G),new W(N,H,G)}add(T){O(T);let{X:Z,Y:A,Z:R}=this,{X:I,Y:q,Z:N}=T,H=o.ZERO,G=o.ZERO,re=o.ZERO,ae=i.a,me=o.mul(i.b,Df),Se=o.mul(Z,I),xe=o.mul(A,q),ke=o.mul(R,N),Ie=o.add(Z,A),_e=o.add(I,q);Ie=o.mul(Ie,_e),_e=o.add(Se,xe),Ie=o.sub(Ie,_e),_e=o.add(Z,R);let Ue=o.add(I,N);return _e=o.mul(_e,Ue),Ue=o.add(Se,ke),_e=o.sub(_e,Ue),Ue=o.add(A,R),H=o.add(q,N),Ue=o.mul(Ue,H),H=o.add(xe,ke),Ue=o.sub(Ue,H),re=o.mul(ae,_e),H=o.mul(me,ke),re=o.add(H,re),H=o.sub(xe,re),re=o.add(xe,re),G=o.mul(H,re),xe=o.add(Se,Se),xe=o.add(xe,Se),ke=o.mul(ae,ke),_e=o.mul(me,_e),xe=o.add(xe,ke),ke=o.sub(Se,ke),ke=o.mul(ae,ke),_e=o.add(_e,ke),Se=o.mul(xe,_e),G=o.add(G,Se),Se=o.mul(Ue,_e),H=o.mul(Ie,H),H=o.sub(H,Se),Se=o.mul(Ie,xe),re=o.mul(Ue,re),re=o.add(re,Se),new W(H,G,re)}subtract(T){return this.add(T.negate())}is0(){return this.equals(W.ZERO)}multiply(T){let{endo:Z}=t;if(!n.isValidNot0(T))throw Error("invalid scalar: out of range");let A,R,I=(q)=>j.cached(this,q,(N)=>AS(W,N));if(Z){let{k1neg:q,k1:N,k2neg:H,k2:G}=L(T),{p:re,f:ae}=I(N),{p:me,f:Se}=I(G);R=ae.add(Se),A=z(Z.beta,re,me,q,H)}else{let{p:q,f:N}=I(T);A=q,R=N}return AS(W,[A,R])[0]}multiplyUnsafe(T){let{endo:Z}=t,A=this;if(!n.isValid(T))throw Error("invalid scalar: out of range");if(T===So||A.is0())return W.ZERO;if(T===Ba)return A;if(j.hasCache(this))return this.multiply(T);if(Z){let{k1neg:R,k1:I,k2neg:q,k2:N}=L(T),{p1:H,p2:G}=NC(W,A,I,N);return z(Z.beta,H,G,R,q)}else return j.unsafe(A,T)}toAffine(T){return P(this,T)}isTorsionFree(){let{isTorsionFree:T}=t;if(s===Ba)return!0;if(T)return T(W,this);return j.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:T}=t;if(s===Ba)return this;if(T)return T(W,this);return this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(T=!0){return iu(T,"isCompressed"),this.assertValidity(),h(W,this,T)}toHex(T=!0){return ys(this.toBytes(T))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let ee=n.BITS,j=new IS(W,t.endo?Math.ceil(ee/2):ee);return W.BASE.precompute(8),W}function MC(e){return Uint8Array.of(e?2:3)}function qC(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function _H(e,t={}){let{Fn:r}=e,o=t.randomBytes||ni,n=Object.assign(qC(e.Fp,r),{seed:wS(r.ORDER)});function i(h){try{let S=r.fromBytes(h);return r.isValidNot0(S)}catch(S){return!1}}function s(h,S){let{publicKey:y,publicKeyUncompressed:v}=n;try{let x=h.length;if(S===!0&&x!==y)return!1;if(S===!1&&x!==v)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h=o(n.seed)){return TC(Re(h,n.seed,"seed"),r.ORDER)}function l(h,S=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(S)}function u(h){let{secretKey:S,publicKey:y,publicKeyUncompressed:v}=n;if(!za(h))return;if("_lengths"in r&&r._lengths||S===y)return;let x=Re(h,void 0,"key").length;return x===y||x===v}function d(h,S,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(S)===!1)throw Error("second arg must be public key");let v=r.fromBytes(h);return e.fromBytes(S).multiply(v).toBytes(y)}let p={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=Pf(a,l);return Object.freeze({getPublicKey:l,getSharedSecret:d,keygen:m,Point:e,utils:p,lengths:n})}function zS(e,t,r={}){Vr(t),Ss(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes||ni,n=r.hmac||((A,R)=>ja(t,A,R)),{Fp:i,Fn:s}=e,{ORDER:a,BITS:l}=s,{keygen:u,getPublicKey:d,getSharedSecret:p,utils:m,lengths:h}=_H(e,r),S={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=a*UC<i.ORDER;function v(A){let R=a>>Ba;return A>R}function x(A,R){if(!s.isValidNot0(R))throw Error(`invalid signature ${A}: out of range 1..Point.Fn.ORDER`);return R}function _(){if(y)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function k(A,R){OS(R);let I=h.signature,q=R==="compact"?I:R==="recovered"?I+1:void 0;return Re(A,q)}class O{r;s;recovery;constructor(A,R,I){if(this.r=x("r",A),this.s=x("s",R),I!=null){if(_(),![0,1,2,3].includes(I))throw Error("invalid recovery id");this.recovery=I}Object.freeze(this)}static fromBytes(A,R=S.format){k(A,R);let I;if(R==="der"){let{r:G,s:re}=ci.toSig(Re(A));return new O(G,re)}if(R==="recovered")I=A[0],R="compact",A=A.subarray(1);let q=h.signature/2,N=A.subarray(0,q),H=A.subarray(q,q*2);return new O(s.fromBytes(N),s.fromBytes(H),I)}static fromHex(A,R){return this.fromBytes(bs(A),R)}assertRecovery(){let{recovery:A}=this;if(A==null)throw Error("invalid recovery id: must be present");return A}addRecoveryBit(A){return new O(this.r,this.s,A)}recoverPublicKey(A){let{r:R,s:I}=this,q=this.assertRecovery(),N=q===2||q===3?R+a:R;if(!i.isValid(N))throw Error("invalid recovery id: sig.r+curve.n != R.x");let H=i.toBytes(N),G=e.fromBytes(At(MC((q&1)===0),H)),re=s.inv(N),ae=P(Re(A,void 0,"msgHash")),me=s.create(-ae*re),Se=s.create(I*re),xe=e.BASE.multiplyUnsafe(me).add(G.multiplyUnsafe(Se));if(xe.is0())throw Error("invalid recovery: point at infinify");return xe.assertValidity(),xe}hasHighS(){return v(this.s)}toBytes(A=S.format){if(OS(A),A==="der")return bs(ci.hexFromSig(this));let{r:R,s:I}=this,q=s.toBytes(R),N=s.toBytes(I);if(A==="recovered")return _(),At(Uint8Array.of(this.assertRecovery()),q,N);return At(q,N)}toHex(A){return ys(this.toBytes(A))}}let L=r.bits2int||function(R){if(R.length>8192)throw Error("input is too large");let I=ii(R),q=R.length*8-l;return q>0?I>>BigInt(q):I},P=r.bits2int_modN||function(R){return s.create(L(R))},K=lu(l);function z(A){return cu("num < 2^"+l,A,So,K),s.toBytes(A)}function W(A,R){return Re(A,void 0,"message"),R?Re(t(A),void 0,"prehashed message"):A}function ee(A,R,I){let{lowS:q,prehash:N,extraEntropy:H}=$S(I,S);A=W(A,N);let G=P(A),re=s.fromBytes(R);if(!s.isValidNot0(re))throw Error("invalid private key");let ae=[z(re),z(G)];if(H!=null&&H!==!1){let ke=H===!0?o(h.secretKey):H;ae.push(Re(ke,void 0,"extraEntropy"))}let me=At(...ae),Se=G;function xe(ke){let Ie=L(ke);if(!s.isValidNot0(Ie))return;let _e=s.inv(Ie),Ue=e.BASE.multiply(Ie).toAffine(),De=s.create(Ue.x);if(De===So)return;let Qe=s.create(_e*s.create(Se+De*re));if(Qe===So)return;let bt=(Ue.x===De?0:2)|Number(Ue.y&Ba),Tt=Qe;if(q&&v(Qe))Tt=s.neg(Qe),bt^=1;return new O(De,Tt,y?void 0:bt)}return{seed:me,k2sig:xe}}function j(A,R,I={}){let{seed:q,k2sig:N}=ee(A,R,I);return yC(t.outputLen,s.BYTES,n)(q,N).toBytes(I.format)}function T(A,R,I,q={}){let{lowS:N,prehash:H,format:G}=$S(q,S);if(I=Re(I,void 0,"publicKey"),R=W(R,H),!za(A)){let re=A instanceof O?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+re)}k(A,G);try{let re=O.fromBytes(A,G),ae=e.fromBytes(I);if(N&&re.hasHighS())return!1;let{r:me,s:Se}=re,xe=P(R),ke=s.inv(Se),Ie=s.create(xe*ke),_e=s.create(me*ke),Ue=e.BASE.multiplyUnsafe(Ie).add(ae.multiplyUnsafe(_e));if(Ue.is0())return!1;return s.create(Ue.x)===me}catch(re){return!1}}function Z(A,R,I={}){let{prehash:q}=$S(I,S);return R=W(R,q),O.fromBytes(A,"recovered").recoverPublicKey(R).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:p,utils:m,lengths:h,Point:e,sign:j,verify:T,recoverPublicKey:Z,Signature:O,hash:t})}var jC=(e,t)=>(e+(e>=0?t:-t)/UC)/t,BC,ci,So,Ba,UC,Df,xH;var FC=b(()=>{TS();Dr();Da();kS();du();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BC=class BC extends Error{constructor(e=""){super(e)}};ci={Err:BC,_tlv:{encode:(e,t)=>{let{Err:r}=ci;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=su(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?su(n.length/2|128):"";return su(e)+i+n+t},decode(e,t){let{Err:r}=ci,o=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let l=n&127;if(!l)throw new r("tlv.decode(long): indefinite length not supported");if(l>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+l);if(u.length!==l)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=l,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=ci;if(e<So)throw new t("integer: negative integers are not allowed");let r=su(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=ci;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return ii(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=ci,n=Re(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=o.decode(2,i),{v:u,l:d}=o.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=ci,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}},So=BigInt(0),Ba=BigInt(1),UC=BigInt(2),Df=BigInt(3),xH=BigInt(4)});function JC(e,t,r){return e&t^~e&r}function KC(e,t,r){return e&t^e&r^t&r}class Lf{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=$f(this.buffer)}update(e){bo(this),Re(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=$f(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){bo(this),Rf(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,wr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=$f(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let l=a/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var vo,Jt;var HC=b(()=>{Dr();vo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Jt=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428])});function EH(e,t=!1){if(t)return{h:Number(e&Zf),l:Number(e>>VC&Zf)};return{h:Number(e>>VC&Zf)|0,l:Number(e&Zf)|0}}function jf(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=EH(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}function Dn(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var Zf,VC,PS=(e,t,r)=>e>>>r,NS=(e,t,r)=>e<<32-r|t>>>r,xs=(e,t,r)=>e>>>r|t<<32-r,_s=(e,t,r)=>e<<32-r|t>>>r,mu=(e,t,r)=>e<<64-r|t>>>r-32,hu=(e,t,r)=>e>>>r-32|t<<64-r,WC=(e,t,r)=>e<<r|t>>>32-r,GC=(e,t,r)=>t<<r|e>>>32-r,QC=(e,t,r)=>t<<r-32|e>>>64-r,YC=(e,t,r)=>e<<r-32|t>>>64-r,XC=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),e1=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,t1=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),r1=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,n1=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),o1=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var DS=b(()=>{Zf=BigInt(4294967295),VC=BigInt(32)});var IH,li,i1,s1,a1,kH,RH,ui,di,c1,l1,Bf,u1;var LS=b(()=>{HC();DS();Dr();IH=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),li=new Uint32Array(64);i1=class i1 extends Lf{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)li[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=li[d-15],m=li[d-2],h=dn(p,7)^dn(p,18)^p>>>3,S=dn(m,17)^dn(m,19)^m>>>10;li[d]=S+li[d-7]+h+li[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:l,H:u}=this;for(let d=0;d<64;d++){let p=dn(s,6)^dn(s,11)^dn(s,25),m=u+p+JC(s,a,l)+IH[d]+li[d]|0,S=(dn(r,2)^dn(r,13)^dn(r,22))+KC(r,o,n)|0;u=l,l=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+S|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,l,u)}roundClean(){wr(li)}destroy(){this.set(0,0,0,0,0,0,0,0),wr(this.buffer)}};s1=class s1 extends i1{A=vo[0]|0;B=vo[1]|0;C=vo[2]|0;D=vo[3]|0;E=vo[4]|0;F=vo[5]|0;G=vo[6]|0;H=vo[7]|0;constructor(){super(32)}};a1=(()=>jf(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e)=>BigInt(e))))(),kH=(()=>a1[0])(),RH=(()=>a1[1])(),ui=new Uint32Array(80),di=new Uint32Array(80);c1=class c1 extends Lf{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:l,El:u,Fh:d,Fl:p,Gh:m,Gl:h,Hh:S,Hl:y}=this;return[e,t,r,o,n,i,s,a,l,u,d,p,m,h,S,y]}set(e,t,r,o,n,i,s,a,l,u,d,p,m,h,S,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=h|0,this.Hh=S|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)ui[_]=e.getUint32(t),di[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let k=ui[_-15]|0,O=di[_-15]|0,L=xs(k,O,1)^xs(k,O,8)^PS(k,O,7),P=_s(k,O,1)^_s(k,O,8)^NS(k,O,7),K=ui[_-2]|0,z=di[_-2]|0,W=xs(K,z,19)^mu(K,z,61)^PS(K,z,6),ee=_s(K,z,19)^hu(K,z,61)^NS(K,z,6),j=t1(P,ee,di[_-7],di[_-16]),T=r1(j,L,W,ui[_-7],ui[_-16]);ui[_]=T|0,di[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:l,Dl:u,Eh:d,El:p,Fh:m,Fl:h,Gh:S,Gl:y,Hh:v,Hl:x}=this;for(let _=0;_<80;_++){let k=xs(d,p,14)^xs(d,p,18)^mu(d,p,41),O=_s(d,p,14)^_s(d,p,18)^hu(d,p,41),L=d&m^~d&S,P=p&h^~p&y,K=n1(x,O,P,RH[_],di[_]),z=o1(K,v,k,L,kH[_],ui[_]),W=K|0,ee=xs(r,o,28)^mu(r,o,34)^mu(r,o,39),j=_s(r,o,28)^hu(r,o,34)^hu(r,o,39),T=r&n^r&s^n&s,Z=o&i^o&a^i&a;v=S|0,x=y|0,S=m|0,y=h|0,m=d|0,h=p|0,{h:d,l:p}=Dn(l|0,u|0,z|0,W|0),l=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let A=XC(W,j,Z);r=e1(A,z,ee,T),o=A|0}({h:r,l:o}=Dn(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=Dn(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=Dn(this.Ch|0,this.Cl|0,s|0,a|0),{h:l,l:u}=Dn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=Dn(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:h}=Dn(this.Fh|0,this.Fl|0,m|0,h|0),{h:S,l:y}=Dn(this.Gh|0,this.Gl|0,S|0,y|0),{h:v,l:x}=Dn(this.Hh|0,this.Hl|0,v|0,x|0),this.set(r,o,n,i,s,a,l,u,d,p,m,h,S,y,v,x)}roundClean(){wr(ui,di)}destroy(){wr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};l1=class l1 extends c1{Ah=Jt[0]|0;Al=Jt[1]|0;Bh=Jt[2]|0;Bl=Jt[3]|0;Ch=Jt[4]|0;Cl=Jt[5]|0;Dh=Jt[6]|0;Dl=Jt[7]|0;Eh=Jt[8]|0;El=Jt[9]|0;Fh=Jt[10]|0;Fl=Jt[11]|0;Gh=Jt[12]|0;Gl=Jt[13]|0;Hh=Jt[14]|0;Hl=Jt[15]|0;constructor(){super(48)}};Bf=Pa(()=>new s1,oi(1)),u1=Pa(()=>new l1,oi(2))});function CH(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=p1,a=e*e%i*e%i,l=Wr(a,d1,i)*a%i,u=Wr(l,TH,i)*e%i,d=Wr(u,OH,i)*u%i,p=Wr(d,t,i)*d%i,m=Wr(p,r,i)*p%i,h=Wr(m,o,i)*m%i,S=Wr(h,n,i)*h%i,y=Wr(S,n,i)*h%i,v=Wr(y,t,i)*d%i;return{pow_p_5_8:Wr(v,d1,i)*e%i,b2:a}}function zH(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var TH,d1,$H,OH,wSe,p1,f1;var m1=b(()=>{du();ZC();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */TH=BigInt(1),d1=BigInt(2),$H=BigInt(3),OH=BigInt(5),wSe=BigInt(8),p1=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");f1=(()=>{let e=p1;return LC({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=CH(t);return lr(Wr(r,$H,e)*o,e)},adjustScalarBytes:zH})})()});var PH,NH,DH,ZS,LH,h1;var g1=b(()=>{LS();FC();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */PH=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),NH=(()=>({p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")}))(),DH=CS(PH),ZS=zS(DH,Bf),LH=CS(NH),h1=zS(LH,u1)});function b1(e,t,r){if(Vr(e),r===void 0)r=new Uint8Array(e.outputLen);return ja(e,r,t)}function S1(e,t,r,o=32){Vr(e),Zt(o,"length");let n=e.outputLen;if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=y1;else Re(r,void 0,"info");let s=new Uint8Array(i*n),a=ja.create(e,t),l=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)jS[0]=d+1,l.update(d===0?y1:u).update(r).update(jS).digestInto(u),s.set(u,n*d),a._cloneInto(l);return a.destroy(),l.destroy(),wr(u,jS),s.slice(0,o)}var jS,y1;var v1=b(()=>{TS();Dr();jS=Uint8Array.of(0),y1=Uint8Array.of()});function JH(e,t=24){let r=new Uint32Array(10);for(let o=24-t;o<24;o++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,l=(s+2)%10,u=r[l],d=r[l+1],p=w1(u,d,1)^r[a],m=x1(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[s+h]^=p,e[s+h+1]^=m}let n=e[2],i=e[3];for(let s=0;s<24;s++){let a=E1[s],l=w1(n,i,a),u=x1(n,i,a),d=_1[s];n=e[d],i=e[d+1],e[d]=l,e[d+1]=u}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=qH[o],e[1]^=FH[o]}wr(r)}class Uf{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,t,r,o=!1,n=24){if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=o,this.rounds=n,Zt(r,"outputLen"),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Tf(this.state)}clone(){return this._cloneInto()}keccak(){mS(this.state32),JH(this.state32,this.rounds),mS(this.state32),this.posOut=0,this.pos=0}update(e){bo(this),Re(e);let{blockLen:t,state:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(t-this.pos,o-n);for(let s=0;s<i;s++)r[this.pos++]^=e[n++];if(this.pos===t)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:o}=this;if(e[r]^=t,(t&128)!==0&&r===o-1)this.keccak();e[o-1]^=128,this.keccak()}writeInto(e){bo(this,!1),Re(e),this.finish();let t=this.state,{blockLen:r}=this;for(let o=0,n=e.length;o<n;){if(this.posOut>=r)this.keccak();let i=Math.min(r-this.posOut,n-o);e.set(t.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Zt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Rf(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,wr(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:o,rounds:n,enableXOF:i}=this;return e||=new Uf(t,r,o,i,n),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}}var ZH,gu,jH,BH,UH,MH,_1,E1,A1,I1,qH,FH,w1=(e,t,r)=>r>32?QC(e,t,r):WC(e,t,r),x1=(e,t,r)=>r>32?YC(e,t,r):GC(e,t,r),k1=(e,t,r,o={})=>Pa(()=>new Uf(t,e,r),o),Es,R1,T1=(e,t,r,o={})=>Pa((n={})=>new Uf(t,e,n.dkLen===void 0?r:n.dkLen,!0),o),$1,Ln;var Mf=b(()=>{DS();Dr();ZH=BigInt(0),gu=BigInt(1),jH=BigInt(2),BH=BigInt(7),UH=BigInt(256),MH=BigInt(113),_1=[],E1=[],A1=[];for(let e=0,t=gu,r=1,o=0;e<24;e++){[r,o]=[o,(2*r+3*o)%5],_1.push(2*(5*o+r)),E1.push((e+1)*(e+2)/2%64);let n=ZH;for(let i=0;i<7;i++)if(t=(t<<gu^(t>>BH)*MH)%UH,t&jH)n^=gu<<(gu<<BigInt(i))-gu;A1.push(n)}I1=jf(A1,!0),qH=I1[0],FH=I1[1];Es=k1(6,136,32,oi(8)),R1=k1(6,72,64,oi(10)),$1=T1(31,168,16,oi(11)),Ln=T1(31,136,32,oi(12))});function BS(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error("wrong u32 integer:"+e);return e}function C1(e){return BS(e),(e&e-1)===0&&e!==0}function US(e,t){BS(e);let r=0;for(let o=0;o<t;o++,e>>>=1)r=r<<1|e&1;return r}function z1(e){return BS(e),31-Math.clz32(e)}function O1(e){let t=e.length;if(t<2||!C1(t))throw Error("n must be a power of 2 and greater than 1. Got "+t);let r=z1(t);for(let o=0;o<t;o++){let n=US(o,r);if(o<n){let i=e[o];e[o]=e[n],e[n]=i}}return e}var MS=(e,t)=>{let{N:r,roots:o,dit:n,invertButterflies:i=!1,skipStages:s=0,brp:a=!0}=t,l=z1(r);if(!C1(r))throw Error("FFT: Polynomial size should be power of two");let u=n!==i;return(d)=>{if(d.length!==r)throw Error("FFT: wrong Polynomial length");if(n&&a)O1(d);for(let p=0,m=1;p<l-s;p++){let h=n?p+1+s:l-p,S=1<<h,y=S>>1,v=r>>h;for(let x=0;x<r;x+=S)for(let _=0,k=m++;_<y;_++){let O=i?n?r-k:k:_*v,L=x+_,P=x+_+y,K=o[O],z=d[P],W=d[L];if(u){let ee=e.mul(z,K);d[L]=e.add(W,ee),d[P]=e.sub(W,ee)}else if(i)d[L]=e.add(z,W),d[P]=e.mul(e.sub(z,W),K);else d[L]=e.add(W,z),d[P]=e.mul(e.sub(W,z),K)}}if(!n&&a)O1(d);return d}};var P1=()=>{};function qf(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function N1(e){return Uint8Array.from(e)}function As(e,...t){let r=(n)=>typeof n==="number"?n:n.bytesLen,o=t.reduce((n,i)=>n+r(i),0);return{bytesLen:o,encode:(n)=>{let i=new Uint8Array(o);for(let s=0,a=0;s<t.length;s++){let l=t[s],u=r(l),d=typeof l==="number"?n[s]:l.encode(n[s]);if(Re(d,u,e),i.set(d,a),typeof l!=="number")d.fill(0);a+=u}return i},decode:(n)=>{Re(n,o,e);let i=[];for(let s of t){let a=r(s),l=n.subarray(0,a);i.push(typeof s==="number"?l:s.decode(l)),n=n.subarray(a)}return i}}}function Ff(e,t){let r=t*e.bytesLen;return{bytesLen:r,encode:(o)=>{if(o.length!==t)throw Error(`vecCoder.encode: wrong length=${o.length}. Expected: ${t}`);let n=new Uint8Array(r);for(let i=0,s=0;i<o.length;i++){let a=e.encode(o[i]);n.set(a,s),a.fill(0),s+=a.length}return n},decode:(o)=>{Re(o,r);let n=[];for(let i=0;i<o.length;i+=e.bytesLen)n.push(e.decode(o.subarray(i,i+e.bytesLen)));return n}}}function Ot(...e){for(let t of e)if(Array.isArray(t))for(let r of t)r.fill(0);else t.fill(0)}function qS(e){return(1<<e)-1}var Zn,DSe;var Jf=b(()=>{Dr();Dr();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */Zn=ni;DSe=Uint8Array.of()});var D1=(e)=>{let{newPoly:t,N:r,Q:o,F:n,ROOT_OF_UNITY:i,brvBits:s,isKyber:a}=e,l=(_,k=o)=>{let O=_%k|0;return(O>=0?O|0:k+O|0)|0},u=(_,k=o)=>{let O=l(_,k)|0;return(O>k>>1?O-k|0:O)|0};function d(){let _=t(r);for(let k=0;k<r;k++){let O=US(k,s),L=BigInt(i)**BigInt(O)%BigInt(o);_[k]=Number(L)|0}return _}let p=d(),m={add:(_,k)=>l((_|0)+(k|0))|0,sub:(_,k)=>l((_|0)-(k|0))|0,mul:(_,k)=>l((_|0)*(k|0))|0,inv:(_)=>{throw Error("not implemented")}},h={N:r,roots:p,invertButterflies:!0,skipStages:a?1:0,brp:!1},S=MS(m,{dit:!1,...h}),y=MS(m,{dit:!0,...h});return{mod:l,smod:u,nttZetas:p,NTT:{encode:(_)=>S(_),decode:(_)=>{y(_);for(let k=0;k<_.length;k++)_[k]=l(n*_[k]);return _}},bitsCoder:(_,k)=>{let O=qS(_),L=_*(r/8);return{bytesLen:L,encode:(P)=>{let K=new Uint8Array(L);for(let z=0,W=0,ee=0,j=0;z<P.length;z++){W|=(k.encode(P[z])&O)<<ee,ee+=_;for(;ee>=8;ee-=8,W>>=8)K[j++]=W&qS(ee)}return K},decode:(P)=>{let K=t(r);for(let z=0,W=0,ee=0,j=0;z<P.length;z++){W|=P[z]<<ee,ee+=8;for(;ee>=_;ee-=_,W>>=_)K[j++]=k.decode(W&O)}return K}}}}},KH=(e)=>(t,r)=>{if(!r)r=e.blockLen;let o=new Uint8Array(t.length+2);o.set(t);let n=t.length,i=new Uint8Array(r),s=e.create({}),a=0,l=0;return{stats:()=>({calls:a,xofs:l}),get:(u,d)=>(o[n+0]=u,o[n+1]=d,s.destroy(),s=e.create({}).update(o),a++,()=>(l++,s.xofInto(i))),clean:()=>{s.destroy(),Ot(i,o)}}},L1;var Z1=b(()=>{P1();Mf();Jf();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */L1=KH($1)});function ks(e,t){for(let r=0;r<er;r++)e[r]=Su(e[r]+t[r])}function YH(e,t){for(let r=0;r<er;r++)e[r]=Su(e[r]-t[r])}function XH(e,t,r,o,n){let i=Su(t*o*n+e*r),s=Su(e*o+t*r);return{c0:i,c1:s}}function Kf(e,t){for(let r=0;r<er/2;r++){let o=WH[64+(r>>1)];if(r&1)o=-o;let{c0:n,c1:i}=XH(e[2*r+0],e[2*r+1],t[2*r+0],t[2*r+1],o);e[2*r+0]=n,e[2*r+1]=i}return e}function j1(e){let t=new Uint16Array(er);for(let r=0;r<er;){let o=e();if(o.length%3)throw Error("SampleNTT: unaligned block");for(let n=0;r<er&&n+3<=o.length;n+=3){let i=(o[n+0]>>0|o[n+1]<<8)&4095,s=(o[n+1]>>4|o[n+2]<<4)&4095;if(i<wo)t[r++]=i;if(r<er&&s<wo)t[r++]=s}}return t}function bu(e,t,r,o){let n=e(o*er/4,t,r),i=new Uint16Array(er),s=Tf(n),a=0;for(let l=0,u=0,d=0,p=0;l<s.length;l++){let m=s[l];for(let h=0;h<32;h++)if(d+=m&1,m>>=1,a+=1,a===o)p=d,d=0;else if(a===2*o)i[u++]=Su(p-d),d=0,a=0}if(a)throw Error(`sampleCBD: leftover bits: ${a}`);return i}function JS(e){let t=eV(e),{HASH256:r,HASH512:o,KDF:n}=e,{secretCoder:i,lengths:s}=t,a=As("secretKey",s.secretKey,s.publicKey,32,32),l=32,u=64;return{info:{type:"ml-kem"},lengths:{...s,seed:64,msg:32,msgRand:32,secretKey:a.bytesLen},keygen:(d=Zn(64))=>{Re(d,64,"seed");let{publicKey:p,secretKey:m}=t.keygen(d.subarray(0,32)),h=r(p),S=a.encode([m,p,h,d.subarray(32)]);return Ot(m,h),{publicKey:p,secretKey:S}},getPublicKey:(d)=>{let[p,m,h,S]=a.decode(d);return Uint8Array.from(m)},encapsulate:(d,p=Zn(32))=>{Re(d,s.publicKey,"publicKey"),Re(p,32,"message");let m=d.subarray(0,384*e.K),h=i.encode(i.decode(N1(m)));if(!qf(h,m))throw Ot(h),Error("ML-KEM.encapsulate: wrong publicKey modulus");Ot(h);let S=o.create().update(p).update(r(d)).digest(),y=t.encrypt(d,p,S.subarray(32,64));return Ot(S.subarray(32)),{cipherText:y,sharedSecret:S.subarray(0,32)}},decapsulate:(d,p)=>{Re(p,a.bytesLen,"secretKey"),Re(d,s.cipherText,"cipherText");let m=a.bytesLen-96,h=m+32,S=r(p.subarray(m/2,h));if(!qf(S,p.subarray(h,h+32)))throw Error("invalid secretKey: hash check failed");let[y,v,x,_]=a.decode(p),k=t.decrypt(d,y),O=o.create().update(k).update(x).digest(),L=O.subarray(0,32),P=t.encrypt(v,k,O.subarray(32,64)),K=qf(d,P),z=n.create({dkLen:32}).update(_).update(d).digest();return Ot(k,P,!K?L:z),K?L:z}}}function tV(e,t,r){return Ln.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}var er=256,wo=3329,HH=3303,VH=17,Su,WH,Is,GH,FS,QH=(e)=>{if(e>=12)return{encode:(r)=>r,decode:(r)=>r};let t=2**(e-1);return{encode:(r)=>((r<<e)+wo/2)/wo,decode:(r)=>r*wo+t>>>e}},yu=(e)=>GH(e,QH(e)),eV=(e)=>{let{K:t,PRF:r,XOF:o,HASH512:n,ETA1:i,ETA2:s,du:a,dv:l}=e,u=yu(1),d=yu(l),p=yu(a),m=As("publicKey",Ff(yu(12),t),32),h=Ff(yu(12),t),S=As("ciphertext",Ff(p,t),d),y=As("seed",32,32);return{secretCoder:h,lengths:{secretKey:h.bytesLen,publicKey:m.bytesLen,cipherText:S.bytesLen},keygen:(v)=>{Re(v,32,"seed");let x=new Uint8Array(33);x.set(v),x[32]=t;let _=n(x),[k,O]=y.decode(_),L=[],P=[];for(let W=0;W<t;W++)L.push(Is.encode(bu(r,O,W,i)));let K=o(k);for(let W=0;W<t;W++){let ee=Is.encode(bu(r,O,t+W,i));for(let j=0;j<t;j++){let T=j1(K.get(j,W));ks(ee,Kf(T,L[j]))}P.push(ee)}K.clean();let z={publicKey:m.encode([P,k]),secretKey:h.encode(L)};return Ot(k,O,L,P,x,_),z},encrypt:(v,x,_)=>{let[k,O]=m.decode(v),L=[];for(let j=0;j<t;j++)L.push(Is.encode(bu(r,_,j,i)));let P=o(O),K=new Uint16Array(er),z=[];for(let j=0;j<t;j++){let T=bu(r,_,t+j,s),Z=new Uint16Array(er);for(let A=0;A<t;A++){let R=j1(P.get(j,A));ks(Z,Kf(R,L[A]))}ks(T,Is.decode(Z)),z.push(T),ks(K,Kf(k[j],L[j])),Ot(Z)}P.clean();let W=bu(r,_,2*t,s);ks(W,Is.decode(K));let ee=u.decode(x);return ks(ee,W),Ot(k,L,K,W),S.encode([z,ee])},decrypt:(v,x)=>{let[_,k]=S.decode(v),O=h.decode(x),L=new Uint16Array(er);for(let P=0;P<t;P++)ks(L,Kf(O[P],Is.encode(_[P])));return YH(k,Is.decode(L)),Ot(L,O,_),u.encode(k)}}},KS,HSe,vu,B1;var U1=b(()=>{Mf();Dr();Z1();Jf();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */({mod:Su,nttZetas:WH,NTT:Is,bitsCoder:GH}=D1({N:er,Q:wo,F:HH,ROOT_OF_UNITY:VH,newPoly:(e)=>new Uint16Array(e),brvBits:7,isKyber:!0})),FS={512:{N:er,Q:wo,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128},768:{N:er,Q:wo,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192},1024:{N:er,Q:wo,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}};KS={HASH256:Es,HASH512:R1,KDF:Ln,XOF:L1,PRF:tV},HSe=JS({...KS,...FS[512]}),vu=JS({...KS,...FS[768]}),B1=JS({...KS,...FS[1024]})});function rV(e,t=!1){let{lengths:r,keygen:o}=e;if(t){let i=e.Point.Fn;if(!i)throw Error("No Point.Fn");o=(s=Zn(r.seed))=>{Re(s,r.seed,"seed");let a=i.isLE?si(s):ii(s),l=i.toBytes(i.create(a));return{secretKey:l,publicKey:e.getPublicKey(l)}}}return{lengths:{secretKey:r.secretKey,publicKey:r.publicKey,seed:r.seed},keygen:o,getPublicKey:(n)=>e.getPublicKey(n)}}function HS(e,t=!1){let r=rV(e,t);if(!e.getSharedSecret)throw Error("wrong curve");return{lengths:{...r.lengths,msg:r.lengths.seed,cipherText:r.lengths.publicKey},keygen:r.keygen,getPublicKey:r.getPublicKey,encapsulate(o,n=Zn(e.lengths.seed)){let i=this.keygen(n).secretKey,s=this.decapsulate(o,i),a=e.getPublicKey(i);return Ot(i),{sharedSecret:s,cipherText:a}},decapsulate(o,n){let i=e.getSharedSecret(n,o);return e.lengths.publicKeyHasPrefix?i.subarray(1):i}}}function wu(e,t){return As(t,...e.map((r)=>{if(typeof r.lengths[t]!=="number")throw Error("wrong length: "+t);return r.lengths[t]}))}function VS(e){return(t,r)=>e(t,{dkLen:r})}function nV(e,t,...r){let o=wu(r,"seed"),n=wu(r,"publicKey");if(e===void 0)e=o.bytesLen;Zt(e);function i(s){Re(s,e);let a=o.decode(t(s,o.bytesLen)),l=r.map((p,m)=>p.keygen(a[m])),u=l.map((p)=>p.secretKey),d=l.map((p)=>p.publicKey);return{secretKey:u,publicKey:d}}return{info:{lengths:{seed:e,publicKey:n.bytesLen,secretKey:e}},getPublicKey(s){return this.keygen(s).publicKey},keygen(s=Zn(e)){let{publicKey:a,secretKey:l}=i(s),u=n.encode(a);return Ot(a),Ot(l),{secretKey:s,publicKey:u}},expandDecapsulationKey:i,realSeedLen:e}}function Hf(e,t,r,o,...n){let i=nV(e,r,...n),s=wu(n,"cipherText"),a=wu(n,"publicKey"),l=wu(n,"msg");if(t===void 0)t=l.bytesLen;return Zt(t),{lengths:{...i.info.lengths,msg:t,msgRand:l.bytesLen,cipherText:s.bytesLen},getPublicKey:i.getPublicKey,keygen:i.keygen,encapsulate(u,d=Zn(l.bytesLen)){let p=a.decode(u),m=l.decode(d),h=n.map((x,_)=>x.encapsulate(p[_],m[_])),S=h.map((x)=>x.sharedSecret),y=h.map((x)=>x.cipherText),v={sharedSecret:o(p,y,S),cipherText:s.encode(y)};return Ot(S,y),v},decapsulate(u,d){let p=s.decode(u),{publicKey:m,secretKey:h}=i.expandDecapsulationKey(d),S=n.map((y,v)=>y.decapsulate(p[v],h[v]));return o(m,p,S)}}}function M1(e,t,r,o,n){return Vr(o),Vr(n),Hf(32,32,VS(o),(i,s,a)=>n(At(a[0],a[1],s[1],i[1],ai(e))),t,r)}function oV(e,t,r,o,n){return Vr(o),Vr(n),Hf(32,32,VS(o),(i,s,a)=>{let l=At(a[0],a[1],s[0],i[0],s[1],i[1],ai(e)),u=32,d=At(ai("hybrid_prk"),l),p=b1(n,d),m=At(Na(32,2),ai("shared_secret"),ai("")),h=S1(n,p,m,32);return Ot(p,m,d,l),h},t,r)}function sV(e,t,r,o){let n=e.Point.Fn;if(!n)throw Error("no Point.Fn");function i(s){let a;for(let d=0,p=t;;d=p,p+=t){if(p>s.length)throw Error("rejection sampling failed");if(a=n.fromBytes(s.subarray(d,p),!0),n.isValidNot0(a))break}let l=n.toBytes(n.create(a)),u=e.getPublicKey(l,!1);return{secretKey:l,publicKey:u}}return{lengths:{secretKey:t,publicKey:r,seed:o,msg:o,cipherText:r},keygen(s=Zn(o)){return Re(s,o,"seed"),i(s)},getPublicKey(s){return e.getPublicKey(s,!1)},encapsulate(s,a=Zn(o)){Re(a,o,"rand");let{secretKey:l}=i(a),u=this.decapsulate(s,l),d=e.getPublicKey(l,!1);return Ot(l),{sharedSecret:u,cipherText:d}},decapsulate(s,a){return e.getSharedSecret(a,s).subarray(1)}}}function aV(e,t,r,o){let{secretKey:n,publicKeyUncompressed:i}=r.lengths;if(!n||!i)throw Error("wrong curve");let s=sV(r,n,i,o),a=64,l=a+o;return Hf(32,32,(u)=>{Re(u,32);let d=Ln(u,{dkLen:l}),p=d.subarray(0,a),m=d.subarray(a,l);return At(p,m)},(u,d,p)=>Es(At(p[0],p[1],d[1],u[1],ai(e))),t,s)}var ove,ive,q1,sve,iV,cV,Vf,F1;var J1=b(()=>{m1();g1();Da();v1();LS();Mf();Dr();U1();Jf();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ove=M1("QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)",vu,HS(ZS,!0),Ln,Es),ive=M1("QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)",B1,HS(h1,!0),Ln,Es);q1=HS(f1),sve=oV("KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)",vu,q1,Ln,Bf),iV=(()=>Hf(32,32,VS(Ln),(e,t,r)=>Es(At(r[0],r[1],t[1],e[1],ai("\\.//^\\"))),vu,q1))();cV=(()=>aV("MLKEM768-P256",vu,ZS,128))(),Vf=iV,F1=cV});function xo(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw TypeError(r+"expected boolean, got type="+typeof e)}return e}function Qf(e){if(typeof e==="bigint"){if(!Wf(e))throw RangeError("positive bigint expected, got "+e)}else GS(e);return e}function jn(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw RangeError(r+"expected safe integer, got "+e)}}function xu(e){let t=Qf(e).toString(16);return t.length&1?"0"+t:t}function K1(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?Gf:BigInt("0x"+e)}function Rs(e){return K1(hf(e))}function pn(e){return K1(hf(pi(Mt(e)).reverse()))}function Yf(e,t){if(St(t),t===0)throw RangeError("zero length");e=Qf(e);let r=e.toString(16);if(r.length>t*2)throw RangeError("number too large");return Wl(r.padStart(t*2,"0"))}function _u(e,t){return Yf(e,t).reverse()}function H1(e,t){if(e=Ye(e),t=Ye(t),e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function pi(e){return Uint8Array.from(Ye(e))}function Xf(e){if(typeof e!=="string")throw TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw RangeError(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}function lV(e,t,r){return Wf(e)&&Wf(t)&&Wf(r)&&t<=e&&e<r}function _o(e,t,r,o){if(!lV(t,r,o))throw RangeError("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function Ja(e){if(e<Gf)throw Error("expected non-negative bigint, got "+e);let t;for(t=0;e>Gf;e>>=WS,t+=1);return t}function V1(e,t,r){if(St(e,"hashLen"),St(t,"qByteLen"),typeof r!=="function")throw TypeError("hmacFn must be a function");let o=(v)=>new Uint8Array(v),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,l=o(e),u=o(e),d=0,p=()=>{l.fill(1),u.fill(0),d=0},m=(...v)=>r(u,Kt(l,...v)),h=(v=n)=>{if(u=m(i,v),l=m(),v.length===0)return;u=m(s,v),l=m()},S=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let v=0,x=[];while(v<t){l=m();let _=l.slice();x.push(_),v+=l.length}return Kt(...x)};return(v,x)=>{p(),h(v);let _=void 0;while((_=x(S()))===void 0)h();return p(),_}}function Gr(e,t={},r={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw TypeError("expected valid options object");function o(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw TypeError(`param "${i}" is invalid: expected own property`);let l=e[i];if(a&&l===void 0)return;let u=typeof l;if(u!==s||l===null)throw TypeError(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,l])=>o(a,l,s));n(t,!1),n(r,!0)}var Ye=(e,t,r)=>Mt(e,t,r),GS,Ua,Kt=(...e)=>Hb(...e),Ma=(e)=>Wl(e),qa,Fa=(e)=>mo(e),Gf,WS,Wf=(e)=>typeof e==="bigint"&&Gf<=e,Eu=(e)=>(WS<<BigInt(e))-WS,QS=()=>{throw Error("not implemented")};var fi=b(()=>{Jr();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */GS=St,Ua=hf,qa=Fb,Gf=BigInt(0),WS=BigInt(1)});function it(e,t){if(t<=Ht)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=Ht?r:t+r}function Qr(e,t,r){if(t<Ht)throw Error("pow2: expected non-negative exponent, got "+t);let o=e;while(t-- >Ht)o*=o,o%=r;return o}function W1(e,t){if(e===Ht)throw Error("invert: expected non-zero number");if(t<=Ht)throw Error("invert: expected positive modulus, got "+t);let r=it(e,t),o=t,n=Ht,i=ht,s=ht,a=Ht;while(r!==Ht){let u=o/r,d=o-r*u,p=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=p,a=m}if(o!==ht)throw Error("invert: does not exist");return it(n,t)}function YS(e,t,r){let o=e;if(!o.eql(o.sqr(t),r))throw Error("Cannot find square root")}function nz(e,t){let r=e,o=(r.ORDER+ht)/X1,n=r.pow(t,o);return YS(r,n,t),n}function pV(e,t){let r=e,o=(r.ORDER-ez)/tz,n=r.mul(t,Ts),i=r.pow(n,o),s=r.mul(t,i),a=r.mul(r.mul(s,Ts),i),l=r.mul(s,r.sub(a,r.ONE));return YS(r,l,t),l}function fV(e){let t=em(e),r=oz(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+uV)/rz;return(a,l)=>{let u=a,d=u.pow(l,s),p=u.mul(d,o),m=u.mul(d,n),h=u.mul(d,i),S=u.eql(u.sqr(p),l),y=u.eql(u.sqr(m),l);d=u.cmov(d,p,S),p=u.cmov(h,m,y);let v=u.eql(u.sqr(p),l),x=u.cmov(d,p,v);return YS(u,x,l),x}}function oz(e){if(e<Y1)throw Error("sqrt is not defined for small field");let t=e-ht,r=0;while(t%Ts===Ht)t/=Ts,r++;let o=Ts,n=em(e);while(G1(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return nz;let i=n.pow(o,t),s=(t+ht)/Ts;return function(l,u){let d=l;if(d.is0(u))return u;if(G1(d,u)!==1)throw Error("Cannot find square root");let p=r,m=d.mul(d.ONE,i),h=d.pow(u,t),S=d.pow(u,s);while(!d.eql(h,d.ONE)){if(d.is0(h))return d.ZERO;let y=1,v=d.sqr(h);while(!d.eql(v,d.ONE))if(y++,v=d.sqr(v),y===p)throw Error("Cannot find square root");let x=ht<<BigInt(p-y-1),_=d.pow(m,x);p=y,m=d.sqr(_),h=d.mul(h,m),S=d.mul(S,_)}return S}}function mV(e){if(e%X1===Y1)return nz;if(e%tz===ez)return pV;if(e%rz===dV)return fV(e);return oz(e)}function XS(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=hV.reduce((o,n)=>(o[n]="function",o),t);if(Gr(e,r),jn(e.BYTES,"BYTES"),jn(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=ht)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function gV(e,t,r){let o=e;if(r<Ht)throw Error("invalid exponent, negatives unsupported");if(r===Ht)return o.ONE;if(r===ht)return t;let n=o.ONE,i=t;while(r>Ht){if(r&ht)n=o.mul(n,i);i=o.sqr(i),r>>=ht}return n}function Au(e,t,r=!1){let o=e,n=Array(t.length).fill(r?o.ZERO:void 0),i=t.reduce((a,l,u)=>{if(o.is0(l))return a;return n[u]=a,o.mul(a,l)},o.ONE),s=o.inv(i);return t.reduceRight((a,l,u)=>{if(o.is0(l))return a;return n[u]=o.mul(a,n[u]),o.mul(a,l)},s),n}function G1(e,t){let r=e,o=(r.ORDER-ht)/Ts,n=r.pow(t,o),i=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),a=r.eql(n,r.neg(r.ONE));if(!i&&!s&&!a)throw Error("invalid Legendre symbol result");return i?1:s?0:-1}function yV(e,t){if(t!==void 0)GS(t);if(e<=Ht)throw Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw Error("invalid n length: expected positive bit length, got "+t);let r=Ja(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected bit length (${r}) >= n.length (${t})`);let o=t!==void 0?t:r,n=Math.ceil(o/8);return{nBitLength:o,nByteLength:n}}class ev{ORDER;BITS;BYTES;isLE;ZERO=Ht;ONE=ht;_lengths;_mod;constructor(e,t={}){if(e<=ht)throw Error("invalid field: expected ORDER > 1, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0});if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=Object.freeze(t.allowedLengths.slice());if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=yV(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,Object.freeze(this)}create(e){return it(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return Ht<=e&&e<this.ORDER}is0(e){return e===Ht}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ht)===ht}neg(e){return it(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return it(e*e,this.ORDER)}add(e,t){return it(e+t,this.ORDER)}sub(e,t){return it(e-t,this.ORDER)}mul(e,t){return it(e*t,this.ORDER)}pow(e,t){return gV(this,e,t)}div(e,t){return it(e*W1(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return W1(e,this.ORDER)}sqrt(e){let t=Q1.get(this);if(!t)Q1.set(this,t=mV(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?_u(e,this.BYTES):Yf(e,this.BYTES)}fromBytes(e,t=!1){Ye(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,n?0:l.length-e.length),e=l}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?pn(e):Rs(e);if(s)a=it(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Au(this,e)}cmov(e,t,r){return xo(r,"condition"),r?t:e}}function em(e,t={}){return new ev(e,t)}function iz(e){if(typeof e!=="bigint")throw Error("field order must be bigint");if(e<=ht)throw Error("field order must be greater than 1");let t=Ja(e-ht);return Math.ceil(t/8)}function tv(e){let t=iz(e);return t+Math.ceil(t/2)}function sz(e,t,r=!1){Ye(e);let o=e.length,n=iz(t),i=Math.max(tv(t),16);if(o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?pn(e):Rs(e),a=it(s,t-ht)+ht;return r?_u(a,n):Yf(a,n)}var Ht,ht,Ts,Y1,X1,ez,uV,tz,dV,rz,Eo=(e,t)=>(it(e,t)&ht)===ht,hV,Q1;var Iu=b(()=>{fi();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ht=BigInt(0),ht=BigInt(1),Ts=BigInt(2),Y1=BigInt(3),X1=BigInt(4),ez=BigInt(5),uV=BigInt(7),tz=BigInt(8),dV=BigInt(9),rz=BigInt(16);hV=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Q1=new WeakMap;Object.freeze(ev.prototype)});function ku(e,t){let r=t.negate();return e?r:t}function Os(e,t){let r=Au(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function uz(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function rv(e,t){uz(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=Eu(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function az(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),l=e>>s;if(a>o)a-=i,l+=$s;let u=t*o,d=u+Math.abs(a)-1,p=a===0,m=a<0,h=t%2!==0;return{nextN:l,offset:d,isZero:p,isNeg:m,isNegF:h,offsetF:u}}function ov(e){return dz.get(e)||1}function cz(e){if(e!==Ka)throw Error("invalid wNAF")}class Ru{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>Ka){if(t&$s)r=r.add(o);o=o.double(),t>>=$s}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=rv(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let l=1;l<o;l++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=rv(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:m}=az(r,s,i);if(r=a,u)n=n.add(ku(p,t[m]));else o=o.add(ku(d,t[l]))}return cz(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=rv(e,this.bits);for(let i=0;i<n.windows;i++){if(r===Ka)break;let{nextN:s,offset:a,isZero:l,isNeg:u}=az(r,i,n);if(r=s,l)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return cz(r),o}getPrecomputes(e,t,r){let o=nv.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);nv.set(t,o)}}return o}cached(e,t,r){let o=ov(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=ov(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){uz(t,this.bits),dz.set(e,t),nv.delete(e)}hasCache(e){return ov(e)!==1}}function pz(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>Ka||o>Ka){if(r&$s)i=i.add(n);if(o&$s)s=s.add(n);n=n.double(),r>>=$s,o>>=$s}return{p1:i,p2:s}}function lz(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return XS(t),t}else return em(e,{isLE:r})}function tm(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let l of["p","n","h"]){let u=t[l];if(!(typeof u==="bigint"&&u>Ka))throw Error(`CURVE.${l} must be positive bigint`)}let n=lz(t.p,r.Fp,o),i=lz(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(t[l]))throw Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function Tu(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}var Ka,$s,nv,dz;var rm=b(()=>{fi();Iu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ka=BigInt(0),$s=BigInt(1);nv=new WeakMap,dz=new WeakMap});function $u(e,t){if(jn(e),jn(t),t<0||t>4)throw Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let o=t-1;o>=0;o--)r[o]=e&255,e>>>=8;return new Uint8Array(r)}function bV(e,t){let r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e[o]^t[o];return r}function SV(e){if(!qa(e)&&typeof e!=="string")throw Error("DST must be Uint8Array or ascii string");let t=typeof e==="string"?Xf(e):e;if(t.length===0)throw Error("DST must be non-empty");return t}function iv(e,t,r,o){if(Ye(e),jn(r),t=SV(t),t.length>255)t=o(Kt(Xf("H2C-OVERSIZE-DST-"),t));let{outputLen:n,blockLen:i}=o,s=Math.ceil(r/n);if(r>65535||s>255)throw Error("expand_message_xmd: invalid lenInBytes");let a=Kt(t,$u(t.length,1)),l=new Uint8Array(i),u=$u(r,2),d=Array(s),p=o(Kt(l,e,u,$u(0,1),a));d[0]=o(Kt(p,$u(1,1),a));for(let h=1;h<s;h++){let S=[bV(p,d[h-1]),$u(h+1,1),a];d[h]=o(Kt(...S))}return Kt(...d).slice(0,r)}var fz="HashToScalar-";var mz=b(()=>{fi()});function vV(e,t,r){_o("scalar",e,Bn,r);let[[o,n],[i,s]]=t,a=hz(s*e,r),l=hz(-n*e,r),u=e-a*o-l*i,d=-a*n-l*s,p=u<Bn,m=d<Bn;if(p)u=-u;if(m)d=-d;let h=Eu(Math.ceil(Ja(r)/2))+mi;if(u<Bn||u>=h||d<Bn||d>=h)throw Error("splitScalar (endomorphism): failed for k");return{k1neg:p,k1:u,k2neg:m,k2:d}}function av(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function sv(e,t){Gr(e);let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(xo(r.lowS,"lowS"),xo(r.prehash,"prehash"),r.format!==void 0)av(r.format);return r}function bz(e,t={}){let r=tm("weierstrass",e,t),o=r.Fp,n=r.Fn,i=r.CURVE,{h:s,n:a}=i;Gr(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:l,allowInfinityPoint:u}=t;if(l){if(!o.is0(i.a)||typeof l.beta!=="bigint"||!Array.isArray(l.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let d=vz(o,n);function p(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function m(j,T,Z){if(u&&T.is0())return Uint8Array.of(0);let{x:A,y:R}=T.toAffine(),I=o.toBytes(A);if(xo(Z,"isCompressed"),Z){p();let q=!o.isOdd(R);return Kt(Sz(q),I)}else return Kt(Uint8Array.of(4),I,o.toBytes(R))}function h(j){Ye(j,void 0,"Point");let{publicKey:T,publicKeyUncompressed:Z}=d,A=j.length,R=j[0],I=j.subarray(1);if(u&&A===1&&R===0)return{x:o.ZERO,y:o.ZERO};if(A===T&&(R===2||R===3)){let q=o.fromBytes(I);if(!o.isValid(q))throw Error("bad point: is not on curve, wrong x");let N=v(q),H;try{H=o.sqrt(N)}catch(ae){let me=ae instanceof Error?": "+ae.message:"";throw Error("bad point: is not on curve, sqrt error"+me)}p();let G=o.isOdd(H);if((R&1)===1!==G)H=o.neg(H);return{x:q,y:H}}else if(A===Z&&R===4){let q=o.BYTES,N=o.fromBytes(I.subarray(0,q)),H=o.fromBytes(I.subarray(q,q*2));if(!x(N,H))throw Error("bad point: is not on curve");return{x:N,y:H}}else throw Error(`bad point: got length ${A}, expected compressed=${T} or uncompressed=${Z}`)}let S=t.toBytes===void 0?m:t.toBytes,y=t.fromBytes===void 0?h:t.fromBytes;function v(j){let T=o.sqr(j),Z=o.mul(T,j);return o.add(o.add(Z,o.mul(j,i.a)),i.b)}function x(j,T){let Z=o.sqr(T),A=v(j);return o.eql(Z,A)}if(!x(i.Gx,i.Gy))throw Error("bad curve params: generator point");let _=o.mul(o.pow(i.a,nm),wV),k=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(_,k)))throw Error("bad curve params: a or b");function O(j,T,Z=!1){if(!o.isValid(T)||Z&&o.is0(T))throw Error(`bad point coordinate ${j}`);return T}function L(j){if(!(j instanceof z))throw Error("Weierstrass Point expected")}function P(j){if(!l||!l.basises)throw Error("no endo");return vV(j,l.basises,n.ORDER)}function K(j,T,Z,A,R){return Z=new z(o.mul(Z.X,j),Z.Y,Z.Z),T=ku(A,T),Z=ku(R,Z),T.add(Z)}class z{static BASE=new z(i.Gx,i.Gy,o.ONE);static ZERO=new z(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(j,T,Z){this.X=O("x",j),this.Y=O("y",T,!0),this.Z=O("z",Z),Object.freeze(this)}static CURVE(){return i}static fromAffine(j){let{x:T,y:Z}=j||{};if(!j||!o.isValid(T)||!o.isValid(Z))throw Error("invalid affine point");if(j instanceof z)throw Error("projective point not allowed");if(o.is0(T)&&o.is0(Z))return z.ZERO;return new z(T,Z,o.ONE)}static fromBytes(j){let T=z.fromAffine(y(Ye(j,void 0,"point")));return T.assertValidity(),T}static fromHex(j){return z.fromBytes(Ma(j))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(j=8,T=!0){if(ee.createCache(this,j),!T)this.multiply(nm);return this}assertValidity(){let j=this;if(j.is0()){if(t.allowInfinityPoint&&o.is0(j.X)&&o.eql(j.Y,o.ONE)&&o.is0(j.Z))return;throw Error("bad point: ZERO")}let{x:T,y:Z}=j.toAffine();if(!o.isValid(T)||!o.isValid(Z))throw Error("bad point: x or y not field elements");if(!x(T,Z))throw Error("bad point: equation left != right");if(!j.isTorsionFree())throw Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:j}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(j)}equals(j){L(j);let{X:T,Y:Z,Z:A}=this,{X:R,Y:I,Z:q}=j,N=o.eql(o.mul(T,q),o.mul(R,A)),H=o.eql(o.mul(Z,q),o.mul(I,A));return N&&H}negate(){return new z(this.X,o.neg(this.Y),this.Z)}double(){let{a:j,b:T}=i,Z=o.mul(T,nm),{X:A,Y:R,Z:I}=this,q=o.ZERO,N=o.ZERO,H=o.ZERO,G=o.mul(A,A),re=o.mul(R,R),ae=o.mul(I,I),me=o.mul(A,R);return me=o.add(me,me),H=o.mul(A,I),H=o.add(H,H),q=o.mul(j,H),N=o.mul(Z,ae),N=o.add(q,N),q=o.sub(re,N),N=o.add(re,N),N=o.mul(q,N),q=o.mul(me,q),H=o.mul(Z,H),ae=o.mul(j,ae),me=o.sub(G,ae),me=o.mul(j,me),me=o.add(me,H),H=o.add(G,G),G=o.add(H,G),G=o.add(G,ae),G=o.mul(G,me),N=o.add(N,G),ae=o.mul(R,I),ae=o.add(ae,ae),G=o.mul(ae,me),q=o.sub(q,G),H=o.mul(ae,re),H=o.add(H,H),H=o.add(H,H),new z(q,N,H)}add(j){L(j);let{X:T,Y:Z,Z:A}=this,{X:R,Y:I,Z:q}=j,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=i.a,ae=o.mul(i.b,nm),me=o.mul(T,R),Se=o.mul(Z,I),xe=o.mul(A,q),ke=o.add(T,Z),Ie=o.add(R,I);ke=o.mul(ke,Ie),Ie=o.add(me,Se),ke=o.sub(ke,Ie),Ie=o.add(T,A);let _e=o.add(R,q);return Ie=o.mul(Ie,_e),_e=o.add(me,xe),Ie=o.sub(Ie,_e),_e=o.add(Z,A),N=o.add(I,q),_e=o.mul(_e,N),N=o.add(Se,xe),_e=o.sub(_e,N),G=o.mul(re,Ie),N=o.mul(ae,xe),G=o.add(N,G),N=o.sub(Se,G),G=o.add(Se,G),H=o.mul(N,G),Se=o.add(me,me),Se=o.add(Se,me),xe=o.mul(re,xe),Ie=o.mul(ae,Ie),Se=o.add(Se,xe),xe=o.sub(me,xe),xe=o.mul(re,xe),Ie=o.add(Ie,xe),me=o.mul(Se,Ie),H=o.add(H,me),me=o.mul(_e,Ie),N=o.mul(ke,N),N=o.sub(N,me),me=o.mul(ke,Se),G=o.mul(_e,G),G=o.add(G,me),new z(N,H,G)}subtract(j){return L(j),this.add(j.negate())}is0(){return this.equals(z.ZERO)}multiply(j){let{endo:T}=t;if(!n.isValidNot0(j))throw RangeError("invalid scalar: out of range");let Z,A,R=(I)=>ee.cached(this,I,(q)=>Os(z,q));if(T){let{k1neg:I,k1:q,k2neg:N,k2:H}=P(j),{p:G,f:re}=R(q),{p:ae,f:me}=R(H);A=re.add(me),Z=K(T.beta,G,ae,I,N)}else{let{p:I,f:q}=R(j);Z=I,A=q}return Os(z,[Z,A])[0]}multiplyUnsafe(j){let{endo:T}=t,Z=this,A=j;if(!n.isValid(A))throw RangeError("invalid scalar: out of range");if(A===Bn||Z.is0())return z.ZERO;if(A===mi)return Z;if(ee.hasCache(this))return this.multiply(A);if(T){let{k1neg:R,k1:I,k2neg:q,k2:N}=P(A),{p1:H,p2:G}=pz(z,Z,I,N);return K(T.beta,H,G,R,q)}else return ee.unsafe(Z,A)}toAffine(j){let T=this,Z=j,{X:A,Y:R,Z:I}=T;if(o.eql(I,o.ONE))return{x:A,y:R};let q=T.is0();if(Z==null)Z=q?o.ONE:o.inv(I);let N=o.mul(A,Z),H=o.mul(R,Z),G=o.mul(I,Z);if(q)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}isTorsionFree(){let{isTorsionFree:j}=t;if(s===mi)return!0;if(j)return j(z,this);return ee.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:j}=t;if(s===mi)return this;if(j)return j(z,this);return this.multiplyUnsafe(s)}isSmallOrder(){if(s===mi)return this.is0();return this.clearCofactor().is0()}toBytes(j=!0){return xo(j,"isCompressed"),this.assertValidity(),S(z,this,j)}toHex(j=!0){return Ua(this.toBytes(j))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let W=n.BITS,ee=new Ru(z,t.endo?Math.ceil(W/2):W);if(W>=8)z.BASE.precompute(8);return Object.freeze(z.prototype),Object.freeze(z),z}function Sz(e){return Uint8Array.of(e?2:3)}function vz(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function xV(e,t={}){let{Fn:r}=e,o=t.randomBytes===void 0?Fa:t.randomBytes,n=Object.assign(vz(e.Fp,r),{seed:Math.max(tv(r.ORDER),16)});function i(h){try{let S=r.fromBytes(h);return r.isValidNot0(S)}catch(S){return!1}}function s(h,S){let{publicKey:y,publicKeyUncompressed:v}=n;try{let x=h.length;if(S===!0&&x!==y)return!1;if(S===!1&&x!==v)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h){return h=h===void 0?o(n.seed):h,sz(Ye(h,n.seed,"seed"),r.ORDER)}function l(h,S=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(S)}function u(h){let{secretKey:S,publicKey:y,publicKeyUncompressed:v}=n,x=r._lengths;if(!qa(h))return;let _=Ye(h,void 0,"key").length,k=_===y||_===v,O=_===S||!!x?.includes(_);if(k&&O)return;return k}function d(h,S,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(S)===!1)throw Error("second arg must be public key");let v=r.fromBytes(h);return e.fromBytes(S).multiply(v).toBytes(y)}let p={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=Tu(a,l);return Object.freeze(p),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:d,keygen:m,Point:e,utils:p,lengths:n})}function wz(e,t,r={}){let o=t;fo(o),Gr(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes===void 0?Fa:r.randomBytes,i=r.hmac===void 0?(R,I)=>zn(o,R,I):r.hmac,{Fp:s,Fn:a}=e,{ORDER:l,BITS:u}=a,{keygen:d,getPublicKey:p,getSharedSecret:m,utils:h,lengths:S}=xV(e,r),y={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},v=l*yz+mi<s.ORDER;function x(R){let I=l>>mi;return R>I}function _(R,I){if(!a.isValidNot0(I))throw Error(`invalid signature ${R}: out of range 1..Point.Fn.ORDER`);return I}function k(){if(v)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(R,I){av(I);let q=S.signature,N=I==="compact"?q:I==="recovered"?q+1:void 0;return Ye(R,N)}class L{r;s;recovery;constructor(R,I,q){if(this.r=_("r",R),this.s=_("s",I),q!=null){if(k(),![0,1,2,3].includes(q))throw Error("invalid recovery id");this.recovery=q}Object.freeze(this)}static fromBytes(R,I=y.format){O(R,I);let q;if(I==="der"){let{r:re,s:ae}=fn.toSig(Ye(R));return new L(re,ae)}if(I==="recovered")q=R[0],I="compact",R=R.subarray(1);let N=S.signature/2,H=R.subarray(0,N),G=R.subarray(N,N*2);return new L(a.fromBytes(H),a.fromBytes(G),q)}static fromHex(R,I){return this.fromBytes(Ma(R),I)}assertRecovery(){let{recovery:R}=this;if(R==null)throw Error("invalid recovery id: must be present");return R}addRecoveryBit(R){return new L(this.r,this.s,R)}recoverPublicKey(R){let{r:I,s:q}=this,N=this.assertRecovery(),H=N===2||N===3?I+l:I;if(!s.isValid(H))throw Error("invalid recovery id: sig.r+curve.n != R.x");let G=s.toBytes(H),re=e.fromBytes(Kt(Sz((N&1)===0),G)),ae=a.inv(H),me=K(Ye(R,void 0,"msgHash")),Se=a.create(-me*ae),xe=a.create(q*ae),ke=e.BASE.multiplyUnsafe(Se).add(re.multiplyUnsafe(xe));if(ke.is0())throw Error("invalid recovery: point at infinify");return ke.assertValidity(),ke}hasHighS(){return x(this.s)}toBytes(R=y.format){if(av(R),R==="der")return Ma(fn.hexFromSig(this));let{r:I,s:q}=this,N=a.toBytes(I),H=a.toBytes(q);if(R==="recovered")return k(),Kt(Uint8Array.of(this.assertRecovery()),N,H);return Kt(N,H)}toHex(R){return Ua(this.toBytes(R))}}Object.freeze(L.prototype),Object.freeze(L);let P=r.bits2int===void 0?function(I){if(I.length>8192)throw Error("input is too large");let q=Rs(I),N=I.length*8-u;return N>0?q>>BigInt(N):q}:r.bits2int,K=r.bits2int_modN===void 0?function(I){return a.create(P(I))}:r.bits2int_modN,z=Eu(u);function W(R){return _o("num < 2^"+u,R,Bn,z),a.toBytes(R)}function ee(R,I){return Ye(R,void 0,"message"),I?Ye(o(R),void 0,"prehashed message"):R}function j(R,I,q){let{lowS:N,prehash:H,extraEntropy:G}=sv(q,y);R=ee(R,H);let re=K(R),ae=a.fromBytes(I);if(!a.isValidNot0(ae))throw Error("invalid private key");let me=[W(ae),W(re)];if(G!=null&&G!==!1){let Ie=G===!0?n(S.secretKey):G;me.push(Ye(Ie,void 0,"extraEntropy"))}let Se=Kt(...me),xe=re;function ke(Ie){let _e=P(Ie);if(!a.isValidNot0(_e))return;let Ue=a.inv(_e),De=e.BASE.multiply(_e).toAffine(),Qe=a.create(De.x);if(Qe===Bn)return;let bt=a.create(Ue*a.create(xe+Qe*ae));if(bt===Bn)return;let Tt=(De.x===Qe?0:2)|Number(De.y&mi),Dt=bt;if(N&&x(bt))Dt=a.neg(bt),Tt^=1;return new L(Qe,Dt,v?void 0:Tt)}return{seed:Se,k2sig:ke}}function T(R,I,q={}){let{seed:N,k2sig:H}=j(R,I,q);return V1(o.outputLen,a.BYTES,i)(N,H).toBytes(q.format)}function Z(R,I,q,N={}){let{lowS:H,prehash:G,format:re}=sv(N,y);if(q=Ye(q,void 0,"publicKey"),I=ee(I,G),!qa(R)){let ae=R instanceof L?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+ae)}O(R,re);try{let ae=L.fromBytes(R,re),me=e.fromBytes(q);if(H&&ae.hasHighS())return!1;let{r:Se,s:xe}=ae,ke=K(I),Ie=a.inv(xe),_e=a.create(ke*Ie),Ue=a.create(Se*Ie),De=e.BASE.multiplyUnsafe(_e).add(me.multiplyUnsafe(Ue));if(De.is0())return!1;return a.create(De.x)===Se}catch(ae){return!1}}function A(R,I,q={}){let{prehash:N}=sv(q,y);return I=ee(I,N),L.fromBytes(R,"recovered").recoverPublicKey(I).toBytes()}return Object.freeze({keygen:d,getPublicKey:p,getSharedSecret:m,utils:h,lengths:S,Point:e,sign:T,verify:Z,recoverPublicKey:A,Signature:L,hash:o})}var hz=(e,t)=>(e+(e>=0?t:-t)/yz)/t,gz,fn,Bn,mi,yz,nm,wV;var xz=b(()=>{Gl();Jr();fi();rm();Iu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */gz=class gz extends Error{constructor(e=""){super(e)}};fn={Err:gz,_tlv:{encode:(e,t)=>{let{Err:r}=fn;if(jn(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(typeof t!=="string")throw TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=xu(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?xu(n.length/2|128):"";return xu(e)+i+n+t},decode(e,t){let{Err:r}=fn;t=Ye(t,void 0,"DER data");let o=0;if(e<0||e>255)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let l=n&127;if(!l)throw new r("tlv.decode(long): indefinite length not supported");if(l>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+l);if(u.length!==l)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=l,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=fn;if(Qf(e),e<Bn)throw new t("integer: negative integers are not allowed");let r=xu(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=fn;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Rs(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=fn,n=Ye(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=o.decode(2,i),{v:u,l:d}=o.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=fn,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}};Object.freeze(fn._tlv);Object.freeze(fn._int);Object.freeze(fn);Bn=BigInt(0),mi=BigInt(1),yz=BigInt(2),nm=BigInt(3),wV=BigInt(4)});var _V,EV,Ha;var _z=b(()=>{Ta();xz();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */_V=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),EV=bz(_V),Ha=wz(EV,vt)});function IV(e,t,r,o){let n=e.sqr(r),i=e.sqr(o),s=e.add(e.mul(t.a,n),i),a=e.add(e.ONE,e.mul(t.d,e.mul(n,i)));return e.eql(s,a)}function Ez(e,t={}){let r=t,o=tm("edwards",e,r,r.FpFnLE),{Fp:n,Fn:i}=o,s=o.CURVE,{h:a}=s;Gr(r,{},{uvRatio:"function"});let l=cv<<BigInt(i.BYTES*8)-xr,u=(y)=>n.create(y),d=r.uvRatio===void 0?(y,v)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,v))}}catch(x){return{isValid:!1,value:hi}}}:r.uvRatio;if(!IV(n,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");function p(y,v,x=!1){let _=x?xr:hi;return _o("coordinate "+y,v,_,l),v}function m(y){if(!(y instanceof h))throw Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,xr,u(s.Gx*s.Gy));static ZERO=new h(hi,xr,xr,hi);static Fp=n;static Fn=i;X;Y;Z;T;constructor(y,v,x,_){this.X=p("x",y),this.Y=p("y",v),this.Z=p("z",x,!0),this.T=p("t",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof h)throw Error("extended point not allowed");let{x:v,y:x}=y||{};return p("x",v),p("y",x),new h(v,x,xr,u(v*x))}static fromBytes(y,v=!1){let x=n.BYTES,{a:_,d:k}=s;y=pi(Ye(y,x,"point")),xo(v,"zip215");let O=pi(y),L=y[x-1];O[x-1]=L&-129;let P=pn(O),K=v?l:n.ORDER;_o("point.y",P,hi,K);let z=u(P*P),W=u(z-xr),ee=u(k*z-_),{isValid:j,value:T}=d(W,ee);if(!j)throw Error("bad point: invalid y coordinate");let Z=(T&xr)===xr,A=(L&128)!==0;if(!v&&T===hi&&A)throw Error("bad point: x=0 and x_0=1");if(A!==Z)T=u(-T);return h.fromAffine({x:T,y:P})}static fromHex(y,v=!1){return h.fromBytes(Ma(y),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,v=!0){if(S.createCache(this,y),!v)this.multiply(cv);return this}assertValidity(){let y=this,{a:v,d:x}=s;if(y.is0())throw Error("bad point: ZERO");let{X:_,Y:k,Z:O,T:L}=y,P=u(_*_),K=u(k*k),z=u(O*O),W=u(z*z),ee=u(P*v),j=u(z*u(ee+K)),T=u(W+u(x*u(P*K)));if(j!==T)throw Error("bad point: equation left != right (1)");let Z=u(_*k),A=u(O*L);if(Z!==A)throw Error("bad point: equation left != right (2)")}equals(y){m(y);let{X:v,Y:x,Z:_}=this,{X:k,Y:O,Z:L}=y,P=u(v*L),K=u(k*_),z=u(x*L),W=u(O*_);return P===K&&z===W}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:y}=s,{X:v,Y:x,Z:_}=this,k=u(v*v),O=u(x*x),L=u(cv*u(_*_)),P=u(y*k),K=v+x,z=u(u(K*K)-k-O),W=P+O,ee=W-L,j=P-O,T=u(z*ee),Z=u(W*j),A=u(z*j),R=u(ee*W);return new h(T,Z,R,A)}add(y){m(y);let{a:v,d:x}=s,{X:_,Y:k,Z:O,T:L}=this,{X:P,Y:K,Z:z,T:W}=y,ee=u(_*P),j=u(k*K),T=u(L*x*W),Z=u(O*z),A=u((_+k)*(P+K)-ee-j),R=Z-T,I=Z+T,q=u(j-v*ee),N=u(A*R),H=u(I*q),G=u(A*q),re=u(R*I);return new h(N,H,re,G)}subtract(y){return m(y),this.add(y.negate())}multiply(y){if(!i.isValidNot0(y))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:x}=S.cached(this,y,(_)=>Os(h,_));return Os(h,[v,x])[0]}multiplyUnsafe(y){if(!i.isValid(y))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(y===hi)return h.ZERO;if(this.is0()||y===xr)return this;return S.unsafe(this,y,(v)=>Os(h,v))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return S.unsafe(this,s.n).is0()}toAffine(y){let v=this,x=y,{X:_,Y:k,Z:O}=v,L=v.is0();if(x==null)x=L?AV:n.inv(O);let P=u(_*x),K=u(k*x),z=n.mul(O,x);if(L)return{x:hi,y:xr};if(z!==xr)throw Error("invZ was invalid");return{x:P,y:K}}clearCofactor(){if(a===xr)return this;return this.multiplyUnsafe(a)}toBytes(){let{x:y,y:v}=this.toAffine(),x=n.toBytes(v);return x[x.length-1]|=y&xr?128:0,x}toHex(){return Ua(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let S=new Ru(h,i.BITS);if(i.BITS>=8)h.BASE.precompute(8);return Object.freeze(h.prototype),Object.freeze(h),h}class lv{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){QS()}static fromHex(e){QS()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Ua(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}}var hi,xr,cv,AV;var Az=b(()=>{fi();rm();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */hi=BigInt(0),xr=BigInt(1),cv=BigInt(2),AV=BigInt(8)});function kV(e){return Gr(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...e})}function Iz(e){let t=kV(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let l=s===void 0?Fa:s,u=a?255:448,d=a?32:56,p=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?om**BigInt(254):om**BigInt(447),S=a?BigInt(8)*om**BigInt(251)-Va:BigInt(4)*om**BigInt(445)-Va,y=h+S+Va,v=(A)=>it(A,r),x=_(p);function _(A){return _u(v(A),d)}function k(A){let R=pi(Ye(A,d,"uCoordinate"));if(a)R[31]&=127;return v(pn(R))}function O(A){return pn(n(pi(Ye(A,d,"scalar"))))}function L(A,R){let I=ee(k(R),O(A));if(I===Ou)throw Error("invalid private or public key received");return _(I)}function P(A){return L(A,x)}let K=P,z=L;function W(A,R,I){let q=v(A*(R-I));return R=v(R-q),I=v(I+q),{x_2:R,x_3:I}}function ee(A,R){_o("u",A,Ou,r),_o("scalar",R,h,y);let I=R,q=A,N=Va,H=Ou,G=A,re=Va,ae=Ou;for(let Se=BigInt(u-1);Se>=Ou;Se--){let xe=I>>Se&Va;ae^=xe,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=xe;let ke=N+H,Ie=v(ke*ke),_e=N-H,Ue=v(_e*_e),De=Ie-Ue,Qe=G+re,bt=G-re,Tt=v(bt*ke),Dt=v(Qe*_e),lt=Tt+Dt,Or=Tt-Dt;G=v(lt*lt),re=v(q*v(Or*Or)),N=v(Ie*Ue),H=v(De*(Ie+v(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let me=i(H);return v(N*me)}let j={secretKey:d,publicKey:d,seed:d},T=(A)=>(A=A===void 0?l(d):A,Ye(A,j.seed,"seed"),A),Z={randomSecretKey:T};return Object.freeze(j),Object.freeze(Z),Object.freeze({keygen:Tu(T,K),getSharedSecret:z,getPublicKey:K,scalarMult:L,scalarMultBase:P,utils:Z,GuBytes:x.slice(),lengths:j})}var Ou,Va,om;var kz=b(()=>{fi();rm();Iu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ou=BigInt(0),Va=BigInt(1),om=BigInt(2)});function Oz(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=zs,a=e*e%i*e%i,l=Qr(a,Rz,i)*a%i,u=Qr(l,Ao,i)*e%i,d=Qr(u,$V,i)*u%i,p=Qr(d,t,i)*d%i,m=Qr(p,r,i)*p%i,h=Qr(m,o,i)*m%i,S=Qr(h,n,i)*h%i,y=Qr(S,n,i)*h%i,v=Qr(y,t,i)*d%i;return{pow_p_5_8:Qr(v,Rz,i)*e%i,b2:a}}function CV(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function mv(e,t){let r=zs,o=it(t*t*t,r),n=it(o*o*t,r),i=Oz(e*n).pow_p_5_8,s=it(e*o*i,r),a=it(t*s*s,r),l=s,u=it(s*uv,r),d=a===e,p=a===it(-e,r),m=a===it(-e*uv,r);if(d)s=l;if(p||m)s=u;if(Eo(s,r))s=it(-s,r);return{isValid:d||p,value:s}}function $z(e){let{d:t}=fv,r=zs,o=(x)=>gi.create(x),n=o(dv*e*e),i=o((n+Ao)*NV),s=BigInt(-1),a=o((s-t*n)*o(n+t)),{isValid:l,value:u}=mv(i,a),d=o(u*e);if(!Eo(d,r))d=o(-d);if(!l)u=d;if(!l)s=n;let p=o(s*(n-Ao)*DV-a),m=u*u,h=o((u+u)*a),S=o(p*zV),y=o(Ao-m),v=o(Ao+m);return new Cs(o(h*v),o(y*S),o(S*v),o(h*y))}var RV,Ao,Rz,TV,$V,OV,zs,fv,uv,Cs,gi,Cz,im,dv,zV,PV,NV,DV,Tz=(e)=>mv(Ao,e),LV,pv=(e)=>gi.create(pn(e)&LV),dr,ZV;var zz=b(()=>{Ta();Jr();Az();mz();Iu();kz();fi();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */RV=BigInt(0),Ao=BigInt(1),Rz=BigInt(2),TV=BigInt(3),$V=BigInt(5),OV=BigInt(8),zs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),fv=(()=>({p:zs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:OV,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();uv=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");Cs=Ez(fv,{uvRatio:mv}),gi=(()=>Cs.Fp)(),Cz=(()=>Cs.Fn)(),im=(()=>{let e=zs;return Iz({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=Oz(t);return it(Qr(r,TV,e)*o,e)},adjustScalarBytes:CV})})(),dv=uv,zV=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),PV=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),NV=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),DV=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),LV=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");dr=class dr extends lv{static BASE=(()=>new dr(Cs.BASE))();static ZERO=(()=>new dr(Cs.ZERO))();static Fp=(()=>gi)();static Fn=(()=>Cz)();constructor(e){super(e)}static fromAffine(e){return new dr(Cs.fromAffine(e))}assertSame(e){if(!(e instanceof dr))throw Error("RistrettoPoint expected")}init(e){return new dr(e)}static fromBytes(e){Mt(e,32);let{a:t,d:r}=fv,o=zs,n=(k)=>gi.create(k),i=pv(e);if(!H1(gi.toBytes(i),e)||Eo(i,o))throw Error("invalid ristretto255 encoding 1");let s=n(i*i),a=n(Ao+t*s),l=n(Ao-t*s),u=n(a*a),d=n(l*l),p=n(t*r*u-d),{isValid:m,value:h}=Tz(n(p*d)),S=n(h*l),y=n(h*S*p),v=n((i+i)*S);if(Eo(v,o))v=n(-v);let x=n(a*y),_=n(v*x);if(!m||Eo(_,o)||x===RV)throw Error("invalid ristretto255 encoding 2");return new dr(new Cs(v,x,Ao,_))}static fromHex(e){return dr.fromBytes(Wl(e))}toBytes(){let{X:e,Y:t,Z:r,T:o}=this.ep,n=zs,i=(y)=>gi.create(y),s=i(i(r+t)*i(r-t)),a=i(e*t),l=i(a*a),{value:u}=Tz(i(s*l)),d=i(u*s),p=i(u*a),m=i(d*p*o),h;if(Eo(o*m,n)){let y=i(t*dv),v=i(e*dv);e=y,t=v,h=i(d*PV)}else h=p;if(Eo(e*m,n))t=i(-t);let S=i((r-t)*h);if(Eo(S,n))S=i(-S);return gi.toBytes(S)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:o,Y:n}=e.ep,i=(l)=>gi.create(l),s=i(t*n)===i(r*o),a=i(r*n)===i(t*o);return s||a}is0(){return this.equals(dr.ZERO)}};Object.freeze(dr.BASE);Object.freeze(dr.ZERO);Object.freeze(dr.prototype);Object.freeze(dr);ZV=Object.freeze({Point:dr,hashToCurve(e,t){let r=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,o=iv(e,r,64,Sf);return ZV.deriveToCurve(o)},hashToScalar(e,t={DST:fz}){let r=iv(e,t.DST,64,Sf);return Cz.create(pn(r))},deriveToCurve(e){Mt(e,64);let t=pv(e.subarray(0,32)),r=$z(t),o=pv(e.subarray(32,64)),n=$z(o);return new dr(r.add(n))}})});async function Nz(e,t){if(jV)return await t();try{return await e()}catch(r){if(r instanceof ReferenceError||r instanceof DOMException&&r.name==="NotSupportedError")return await t();else throw r}}async function sm(e,t){return await Nz(async()=>{let r=hv(e)?e:await UV(e),o=await crypto.subtle.importKey("raw",MV(t),{name:"X25519"},Pz,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:o},r,256))},()=>{if(hv(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return im.scalarMult(e,t)})}async function Cu(e){return await Nz(async()=>sm(e,im.GuBytes),()=>{if(hv(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return im.scalarMultBase(e)})}async function UV(e){if(e.length!==32)throw Error("X25519 private key must be 32 bytes");let t=new Uint8Array([...BV,...e]);return crypto.subtle.importKey("pkcs8",t,{name:"X25519"},Pz,["deriveBits"])}function hv(e){return typeof CryptoKey<"u"&&e instanceof CryptoKey}function MV(e){return e}var Pz=!1,jV=!1,BV;var Dz=b(()=>{zz();BV=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32])});class gv{s;transcript=[];buf=new Uint8Array(0);constructor(e){this.s=e.getReader()}async readLine(){let e=[];while(!0){let t=this.buf.indexOf(10);if(t>=0)return e.push(this.buf.subarray(0,t)),this.transcript.push(this.buf.subarray(0,t+1)),this.buf=this.buf.subarray(t+1),FV(Ps(e));if(this.buf.length>0)e.push(this.buf),this.transcript.push(this.buf);let r=await this.s.read();if(r.done)return this.buf=Ps(e),null;this.buf=r.value}}close(){return this.s.releaseLock(),{rest:this.buf,transcript:Ps(this.transcript)}}}function FV(e){return e.forEach((t)=>{if(t<32||t>126)throw Error("invalid non-ASCII byte in header")}),new TextDecoder().decode(e)}function Ps(e){let t=e.reduce((n,i)=>n+i.length,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}function Wa(e,...t){return e.pipeThrough(new TransformStream({start(r){for(let o of t)r.enqueue(o)}}))}function am(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}async function yv(e){if(!(e instanceof ReadableStream))throw Error("readAll expects a ReadableStream<Uint8Array>");return new Uint8Array(await new Response(e).arrayBuffer())}async function Lz(e){if(!(e instanceof ReadableStream))throw Error("readAllString expects a ReadableStream<Uint8Array>");return await new Response(e).text()}async function Zz(e,t){let r=e.getReader(),o=[],n=0;while(n<t){let{done:l,value:u}=await r.read();if(l)throw Error("stream ended before reading "+t.toString()+" bytes");o.push(u),n+=u.length}r.releaseLock();let i=Ps(o),s=i.subarray(0,t),a=Wa(e,i.subarray(t));return{data:s,rest:a}}var bv=()=>{};class Un{args;body;constructor(e,t){this.args=e,this.body=t}}async function JV(e){let t=await e.readLine();if(t===null)throw Error("invalid stanza");let r=t.split(" ");if(r.length<2||r.shift()!=="->")return{next:t};for(let i of r)if(i.length===0)throw Error("invalid stanza");let o=[];for(;;){let i=await e.readLine();if(i===null)throw Error("invalid stanza");let s=Yt.decode(i);if(s.length>48)throw Error("invalid stanza");if(o.push(s),s.length<48)break}let n=Ps(o);return{s:new Un(r,n)}}async function jz(e){let t=new gv(e),r=await t.readLine();if(r!=="age-encryption.org/v1")throw Error("invalid version "+(r??"line"));let o=[];for(;;){let{s:n,next:i}=await JV(t);if(n!==void 0){o.push(n);continue}if(!i.startsWith("--- "))throw Error("invalid header");let s=Yt.decode(i.slice(4)),{rest:a,transcript:l}=t.close(),u=l.slice(0,l.length-1-i.length+3);return{stanzas:o,headerNoMAC:u,MAC:s,headerSize:l.length,rest:Wa(e,a)}}}function Sv(e){let t=[];t.push(`age-encryption.org/v1
|
|
3
|
+
var dK=Object.create;var{getPrototypeOf:pK,defineProperty:qb,getOwnPropertyNames:fK}=Object;var mK=Object.prototype.hasOwnProperty;function hK(e){return this[e]}var gK,yK,Vl=(e,t,r)=>{var o=e!=null&&typeof e==="object";if(o){var n=t?gK??=new WeakMap:yK??=new WeakMap,i=n.get(e);if(i)return i}r=e!=null?dK(pK(e)):{};let s=t||!e||!e.__esModule?qb(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of fK(e))if(!mK.call(s,a))qb(s,a,{get:hK.bind(e,a),enumerable:!0})}if(o)n.set(e,s);return s};var ye=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var bK=(e)=>e;function SK(e,t){this[e]=bK.bind(null,t)}var Lt=(e,t)=>{for(var r in t)qb(e,r,{get:t[r],enumerable:!0,configurable:!0,set:SK.bind(t,r)})};var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var Fr=import.meta.require;function Ve(e,t){if(e instanceof Error)return e.message;return t??String(e)}function Fb(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function St(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(`${r}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw RangeError(`${r}expected integer >= 0, got ${e}`)}}function Mt(e,t,r=""){let o=Fb(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+l;if(!o)throw TypeError(u);throw RangeError(u)}return e}function fo(e){if(typeof e!=="function"||typeof e.create!=="function")throw TypeError("Hash must wrapped by utils.createHasher");if(St(e.outputLen),St(e.blockLen),e.outputLen<1)throw Error('"outputLen" must be >= 1');if(e.blockLen<1)throw Error('"blockLen" must be >= 1')}function ka(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function ff(e,t){Mt(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw RangeError('"digestInto() output" expected to be of length >='+r)}function mf(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function cr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ra(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ln(e,t){return e<<32-t|e>>>t}function Fe(e,t){return e<<t|e>>>32-t>>>0}function $K(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function OK(e){for(let t=0;t<e.length;t++)e[t]=$K(e[t]);return e}function hf(e){if(Mt(e),SO)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=CK[e[r]];return t}function bO(e){if(e>=po._0&&e<=po._9)return e-po._0;if(e>=po.A&&e<=po.F)return e-(po.A-10);if(e>=po.a&&e<=po.f)return e-(po.a-10);return}function Wl(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(SO)try{return Uint8Array.fromHex(e)}catch(n){if(n instanceof SyntaxError)throw RangeError(n.message);throw n}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=bO(e.charCodeAt(i)),a=bO(e.charCodeAt(i+1));if(s===void 0||a===void 0){let l=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+l+'" at index '+i)}o[n]=s*16+a}return o}function zK(e){if(typeof e!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Kb(e,t=""){if(typeof e==="string")return zK(e);return Mt(e,void 0,t)}function Hb(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Mt(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function gf(e,t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw TypeError("options must be object or undefined");return Object.assign(e,t)}function Vb(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.canXOF=o.canXOF,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function mo(e=32){St(e,"bytesLength");let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var TK,Jb,SO,CK,po,Wb=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Jr=b(()=>{TK=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();Jb=TK?(e)=>e:OK,SO=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),CK=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));po={_0:48,_9:57,A:65,F:70,a:97,f:102}});class Gb{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(fo(e),Mt(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),cr(o)}update(e){return ka(this),this.iHash.update(e),this}digestInto(e){ka(this),ff(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var zn;var Gl=b(()=>{Jr();zn=(()=>{let e=(t,r,o)=>new Gb(t,r).update(o).digest();return e.create=(t,r)=>new Gb(t,r),e})()});function Ql(e,t,r){if(fo(e),r===void 0)r=new Uint8Array(e.outputLen);return zn(e,r,t)}function Yb(e,t,r,o=32){fo(e),St(o,"length"),Mt(t,void 0,"prk");let n=e.outputLen;if(t.length<n)throw Error('"prk" must be at least HashLen octets');if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=vO;else Mt(r,void 0,"info");let s=new Uint8Array(i*n),a=zn.create(e,t),l=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)Qb[0]=d+1,l.update(d===0?vO:u).update(r).update(Qb).digestInto(u),s.set(u,n*d),a._cloneInto(l);return a.destroy(),l.destroy(),cr(u,Qb),s.slice(0,o)}var Qb,vO,Yo=(e,t,r,o,n)=>Yb(e,Ql(e,t,r),o,n);var Xb=b(()=>{Gl();Jr();Qb=Uint8Array.of(0),vO=Uint8Array.of()});function wO(e,t,r){return e&t^~e&r}function xO(e,t,r){return e&t^e&r^t&r}class yf{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Ra(this.buffer)}update(e){ka(this),Mt(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=Ra(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){ka(this),ff(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,cr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=Ra(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let l=a/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var ho,qt;var _O=b(()=>{Jr();ho=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function PK(e,t=!1){if(t)return{h:Number(e&bf),l:Number(e>>EO&bf)};return{h:Number(e>>EO&bf)|0,l:Number(e&bf)|0}}function AO(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=PK(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}function Pn(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var bf,EO,eS=(e,t,r)=>e>>>r,tS=(e,t,r)=>e<<32-r|t>>>r,ms=(e,t,r)=>e>>>r|t<<32-r,hs=(e,t,r)=>e<<32-r|t>>>r,Yl=(e,t,r)=>e<<64-r|t>>>r-32,Xl=(e,t,r)=>e>>>r-32|t<<64-r,IO=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),kO=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,RO=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),TO=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,$O=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),OO=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var CO=b(()=>{bf=BigInt(4294967295),EO=BigInt(32)});var DK,Xo,zO,PO,NO,LK,ZK,ei,ti,DO,LO,vt,Sf;var Ta=b(()=>{_O();CO();Jr();DK=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Xo=new Uint32Array(64);zO=class zO extends yf{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)Xo[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=Xo[d-15],m=Xo[d-2],h=ln(p,7)^ln(p,18)^p>>>3,S=ln(m,17)^ln(m,19)^m>>>10;Xo[d]=S+Xo[d-7]+h+Xo[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:l,H:u}=this;for(let d=0;d<64;d++){let p=ln(s,6)^ln(s,11)^ln(s,25),m=u+p+wO(s,a,l)+DK[d]+Xo[d]|0,S=(ln(r,2)^ln(r,13)^ln(r,22))+xO(r,o,n)|0;u=l,l=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+S|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,l,u)}roundClean(){cr(Xo)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),cr(this.buffer)}};PO=class PO extends zO{A=ho[0]|0;B=ho[1]|0;C=ho[2]|0;D=ho[3]|0;E=ho[4]|0;F=ho[5]|0;G=ho[6]|0;H=ho[7]|0;constructor(){super(32)}};NO=(()=>AO(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e)=>BigInt(e))))(),LK=(()=>NO[0])(),ZK=(()=>NO[1])(),ei=new Uint32Array(80),ti=new Uint32Array(80);DO=class DO extends yf{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:l,El:u,Fh:d,Fl:p,Gh:m,Gl:h,Hh:S,Hl:y}=this;return[e,t,r,o,n,i,s,a,l,u,d,p,m,h,S,y]}set(e,t,r,o,n,i,s,a,l,u,d,p,m,h,S,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=h|0,this.Hh=S|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)ei[_]=e.getUint32(t),ti[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let k=ei[_-15]|0,O=ti[_-15]|0,L=ms(k,O,1)^ms(k,O,8)^eS(k,O,7),P=hs(k,O,1)^hs(k,O,8)^tS(k,O,7),K=ei[_-2]|0,z=ti[_-2]|0,W=ms(K,z,19)^Yl(K,z,61)^eS(K,z,6),ee=hs(K,z,19)^Xl(K,z,61)^tS(K,z,6),j=RO(P,ee,ti[_-7],ti[_-16]),T=TO(j,L,W,ei[_-7],ei[_-16]);ei[_]=T|0,ti[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:l,Dl:u,Eh:d,El:p,Fh:m,Fl:h,Gh:S,Gl:y,Hh:v,Hl:x}=this;for(let _=0;_<80;_++){let k=ms(d,p,14)^ms(d,p,18)^Yl(d,p,41),O=hs(d,p,14)^hs(d,p,18)^Xl(d,p,41),L=d&m^~d&S,P=p&h^~p&y,K=$O(x,O,P,ZK[_],ti[_]),z=OO(K,v,k,L,LK[_],ei[_]),W=K|0,ee=ms(r,o,28)^Yl(r,o,34)^Yl(r,o,39),j=hs(r,o,28)^Xl(r,o,34)^Xl(r,o,39),T=r&n^r&s^n&s,Z=o&i^o&a^i&a;v=S|0,x=y|0,S=m|0,y=h|0,m=d|0,h=p|0,{h:d,l:p}=Pn(l|0,u|0,z|0,W|0),l=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let A=IO(W,j,Z);r=kO(A,z,ee,T),o=A|0}({h:r,l:o}=Pn(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=Pn(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=Pn(this.Ch|0,this.Cl|0,s|0,a|0),{h:l,l:u}=Pn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=Pn(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:h}=Pn(this.Fh|0,this.Fl|0,m|0,h|0),{h:S,l:y}=Pn(this.Gh|0,this.Gl|0,S|0,y|0),{h:v,l:x}=Pn(this.Hh|0,this.Hl|0,v|0,x|0),this.set(r,o,n,i,s,a,l,u,d,p,m,h,S,y,v,x)}roundClean(){cr(ei,ti)}destroy(){this.destroyed=!0,cr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};LO=class LO extends DO{Ah=qt[0]|0;Al=qt[1]|0;Bh=qt[2]|0;Bl=qt[3]|0;Ch=qt[4]|0;Cl=qt[5]|0;Dh=qt[6]|0;Dl=qt[7]|0;Eh=qt[8]|0;El=qt[9]|0;Fh=qt[10]|0;Fl=qt[11]|0;Gh=qt[12]|0;Gl=qt[13]|0;Hh=qt[14]|0;Hl=qt[15]|0;constructor(){super(64)}};vt=Vb(()=>new PO,Wb(1)),Sf=Vb(()=>new LO,Wb(3))});function Ef(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function oS(e){if(!Ef(e))throw TypeError("Uint8Array expected")}function MO(e,t){if(!Array.isArray(t))return!1;if(t.length===0)return!0;if(e)return t.every((r)=>typeof r==="string");else return t.every((r)=>Number.isSafeInteger(r))}function qO(e){if(typeof e!=="function")throw TypeError("function expected");return!0}function ri(e,t){if(typeof t!=="string")throw TypeError(`${e}: string expected`);return!0}function tu(e){if(typeof e!=="number")throw TypeError(`number expected, got ${typeof e}`);if(!Number.isSafeInteger(e))throw RangeError(`invalid integer: ${e}`)}function wf(e){if(!Array.isArray(e))throw TypeError("array expected")}function xf(e,t){if(!MO(!0,t))throw TypeError(`${e}: array of strings expected`)}function iS(e,t){if(!MO(!1,t))throw TypeError(`${e}: array of numbers expected`)}function Cr(...e){let t=(i)=>i,r=(i,s)=>(a)=>i(s(a)),o=e.map((i)=>i.encode).reduceRight(r,t),n=e.map((i)=>i.decode).reduce(r,t);return{encode:o,decode:n}}function zr(e){let t=typeof e==="string"?e.split(""):e,r=t.length;xf("alphabet",t);let o=new Map(t.map((n,i)=>[n,i]));return{encode:(n)=>(wf(n),n.map((i)=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return t[i]})),decode:(n)=>(wf(n),n.map((i)=>{ri("alphabet.decode",i);let s=o.get(i);if(s===void 0)throw Error(`Unknown letter: "${i}". Allowed: ${e}`);return s}))}}function Pr(e=""){return ri("join",e),{encode:(t)=>(xf("join.decode",t),t.join(e)),decode:(t)=>(ri("join.decode",t),t.split(e))}}function Af(e,t="="){return tu(e),ri("padding",t),{encode(r){xf("padding.encode",r);while(r.length*e%8)r.push(t);return r},decode(r){xf("padding.decode",r);let o=r.length;if(o*e%8)throw Error("padding: invalid, string should have whole number of bytes");for(;o>0&&r[o-1]===t;o--)if((o-1)*e%8===0)throw Error("padding: invalid, string has too much padding");return r.slice(0,o)}}}function FO(e){return qO(e),{encode:(t)=>t,decode:(t)=>e(t)}}function ZO(e,t,r){if(t<2)throw RangeError(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(r<2)throw RangeError(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(wf(e),!e.length)return[];let o=0,n=[],i=Array.from(e,(a)=>{if(tu(a),a<0||a>=t)throw Error(`invalid integer: ${a}`);return a}),s=i.length;while(!0){let a=0,l=!0;for(let u=o;u<s;u++){let d=i[u],p=t*a,m=p+d;if(!Number.isSafeInteger(m)||p/t!==a||m-d!==p)throw Error("convertRadix: carry overflow");let h=m/r;a=m%r;let S=Math.floor(h);if(i[u]=S,!Number.isSafeInteger(S)||S*r+a!==m)throw Error("convertRadix: carry overflow");if(!l)continue;else if(!S)o=u;else l=!1}if(n.push(a),l)break}for(let a=0;a<e.length-1&&e[a]===0;a++)n.push(0);return n.reverse()}function rS(e,t,r,o){if(wf(e),t<=0||t>32)throw RangeError(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw RangeError(`convertRadix2: wrong to=${r}`);if(_f(t,r)>32)throw Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${_f(t,r)}`);let n=0,i=0,s=vf[t],a=vf[r]-1,l=[];for(let u of e){if(tu(u),u>=s)throw Error(`convertRadix2: invalid data word=${u} from=${t}`);if(n=n<<t|u,i+t>32)throw Error(`convertRadix2: carry overflow pos=${i} from=${t}`);i+=t;for(;i>=r;i-=r)l.push((n>>i-r&a)>>>0);let d=vf[i];if(d===void 0)throw Error("invalid carry");n&=d-1}if(n=n<<r-i&a,!o&&i>=t)throw Error("Excess padding");if(!o&&n>0)throw Error(`Non-zero padding: ${n}`);if(o&&i>0)l.push(n>>>0);return l}function jK(e){tu(e);let t=256;return{encode:(r)=>{if(!Ef(r))throw TypeError("radix.encode input should be Uint8Array");return ZO(Array.from(r),t,e)},decode:(r)=>(iS("radix.decode",r),Uint8Array.from(ZO(r,e,t)))}}function Kr(e,t=!1){if(tu(e),e<=0||e>32)throw RangeError("radix2: bits should be in (0..32]");if(_f(8,e)>32||_f(e,8)>32)throw RangeError("radix2: carry overflow");return{encode:(r)=>{if(!Ef(r))throw TypeError("radix2.encode input should be Uint8Array");return rS(Array.from(r),8,e,!t)},decode:(r)=>(iS("radix2.decode",r),Uint8Array.from(rS(r,e,8,t)))}}function jO(e){return qO(e),function(...t){try{return e.apply(null,t)}catch(r){}}}function eu(e){let t=e>>25,r=(e&33554431)<<5;for(let o=0;o<BO.length;o++)if((t>>o&1)===1)r^=BO[o];return r}function UO(e,t,r=1){let o=e.length,n=1;for(let i=0;i<o;i++){let s=e.charCodeAt(i);if(s<33||s>126)throw Error(`Invalid prefix (${e})`);n=eu(n)^s>>5}n=eu(n);for(let i=0;i<o;i++)n=eu(n)^e.charCodeAt(i)&31;for(let i of t)n=eu(n)^i;for(let i=0;i<6;i++)n=eu(n);return n^=r,nS.encode(rS([n%vf[30]],30,5,!1))}function VO(e){let t=e==="bech32"?1:734539939,r=Kr(5),o=r.decode,n=r.encode,i=jO(o);function s(p,m,h=90){if(ri("bech32.encode prefix",p),Ef(m))m=Array.from(m);iS("bech32.encode",m);let S=p.length;if(S===0)throw TypeError(`Invalid prefix length ${S}`);let y=S+7+m.length;if(h!==!1&&y>h)throw TypeError(`Length ${y} exceeds limit ${h}`);let v=p.toLowerCase(),x=UO(v,m,t);return`${v}1${nS.encode(m)}${x}`}function a(p,m=90){ri("bech32.decode input",p);let h=p.length;if(h<8||m!==!1&&h>m)throw TypeError(`invalid string length: ${h} (${p}). Expected (8..${m})`);let S=p.toLowerCase();if(p!==S&&p!==p.toUpperCase())throw Error("String must be lowercase or uppercase");let y=S.lastIndexOf("1");if(y===0||y===-1)throw Error('Letter "1" must be present between prefix and data only');let v=S.slice(0,y),x=S.slice(y+1);if(x.length<6)throw Error("Data must be at least 6 characters long");let _=nS.decode(x).slice(0,-6),k=UO(v,_,t);if(!x.endsWith(k))throw Error(`Invalid checksum in ${p}: expected "${k}"`);return{prefix:v,words:_}}let l=jO(a);function u(p){let{prefix:m,words:h}=a(p,!1);return{prefix:m,words:h,bytes:o(h)}}function d(p,m){return s(p,n(m))}return{encode:s,decode:a,encodeFromBytes:d,decodeToBytes:u,decodeUnsafe:l,fromWords:o,fromWordsUnsafe:i,toWords:n}}var JO=(e,t)=>t===0?e:JO(t,e%t),_f=(e,t)=>e+(t-JO(e,t)),vf,abe,cbe,lbe,ube,dbe,pbe,KO,BK,HO=(e,t)=>{ri("base64",e);let r=t?"base64url":"base64";if(e.length>0&&BK.test(e))throw Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},sS,Yt,fbe,mbe,aS=(e)=>Cr(jK(58),zr(e),Pr("")),hbe,gbe,ybe,nS,BO,Nr,bbe,UK,MK,Sbe;var ru=b(()=>{/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */vf=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();abe=Object.freeze(Cr(Kr(4),zr("0123456789ABCDEF"),Pr(""))),cbe=Object.freeze(Cr(Kr(5),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Af(5),Pr(""))),lbe=Object.freeze(Cr(Kr(5),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Pr(""))),ube=Object.freeze(Cr(Kr(5),zr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Af(5),Pr(""))),dbe=Object.freeze(Cr(Kr(5),zr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Pr(""))),pbe=Object.freeze(Cr(Kr(5),zr("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Pr(""),FO((e)=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),KO=(()=>typeof Uint8Array.from([]).toBase64==="function"&&typeof Uint8Array.fromBase64==="function")(),BK=/[\t\n\f\r ]/,sS=Object.freeze(KO?{encode(e){return oS(e),e.toBase64()},decode(e){return HO(e,!1)}}:Cr(Kr(6),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Af(6),Pr(""))),Yt=Object.freeze(Cr(Kr(6),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Pr(""))),fbe=Object.freeze(KO?{encode(e){return oS(e),e.toBase64({alphabet:"base64url"})},decode(e){return HO(e,!0)}}:Cr(Kr(6),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Af(6),Pr(""))),mbe=Object.freeze(Cr(Kr(6),zr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Pr(""))),hbe=Object.freeze(aS("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),gbe=Object.freeze(aS("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")),ybe=Object.freeze(aS("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz")),nS=Cr(zr("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Pr("")),BO=[996825010,642813549,513874426,1027748829,705979059];Nr=Object.freeze(VO("bech32")),bbe=Object.freeze(VO("bech32m")),UK=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),MK={encode(e){return oS(e),e.toHex()},decode(e){return ri("hex",e),Uint8Array.fromHex(e)}},Sbe=Object.freeze(UK?MK:Cr(Kr(4),zr("0123456789abcdef"),Pr(""),FO((e)=>{if(typeof e!=="string"||e.length%2!==0)throw TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})))});function FK(e,t,r,o){fo(e);let n=gf({dkLen:32,asyncTick:10},o),{c:i,dkLen:s,asyncTick:a}=n;if(St(i,"c"),St(s,"dkLen"),St(a,"asyncTick"),i<1)throw Error("iterations (c) must be >= 1");if(s<1)throw Error('"dkLen" must be >= 1');if(s>4294967295*e.outputLen)throw Error("derived key too long");let l=Kb(t,"password"),u=Kb(r,"salt"),d=new Uint8Array(s),p=zn.create(e,l),m=p._cloneInto().update(u);return{c:i,dkLen:s,asyncTick:a,DK:d,PRF:p,PRFSalt:m}}function JK(e,t,r,o,n){if(e.destroy(),t.destroy(),o)o.destroy();return cr(n),r}function cS(e,t,r,o){let{c:n,dkLen:i,DK:s,PRF:a,PRFSalt:l}=FK(e,t,r,o),u,d=new Uint8Array(4),p=Ra(d),m=new Uint8Array(a.outputLen);for(let h=1,S=0;S<i;h++,S+=a.outputLen){let y=s.subarray(S,S+a.outputLen);p.setInt32(0,h,!1),(u=l._cloneInto(u)).update(d).digestInto(m),y.set(m.subarray(0,y.length));for(let v=1;v<n;v++){a._cloneInto(u).update(m).digestInto(m);for(let x=0;x<y.length;x++)y[x]^=m[x]}}return JK(a,l,s,u,m)}var WO=b(()=>{Gl();Jr()});function GO(e,t,r,o,n,i){let s=e[t++]^r[o++],a=e[t++]^r[o++],l=e[t++]^r[o++],u=e[t++]^r[o++],d=e[t++]^r[o++],p=e[t++]^r[o++],m=e[t++]^r[o++],h=e[t++]^r[o++],S=e[t++]^r[o++],y=e[t++]^r[o++],v=e[t++]^r[o++],x=e[t++]^r[o++],_=e[t++]^r[o++],k=e[t++]^r[o++],O=e[t++]^r[o++],L=e[t++]^r[o++],P=s,K=a,z=l,W=u,ee=d,j=p,T=m,Z=h,A=S,R=y,I=v,q=x,N=_,H=k,G=O,re=L;for(let ae=0;ae<8;ae+=2)ee^=Fe(P+N|0,7),A^=Fe(ee+P|0,9),N^=Fe(A+ee|0,13),P^=Fe(N+A|0,18),R^=Fe(j+K|0,7),H^=Fe(R+j|0,9),K^=Fe(H+R|0,13),j^=Fe(K+H|0,18),G^=Fe(I+T|0,7),z^=Fe(G+I|0,9),T^=Fe(z+G|0,13),I^=Fe(T+z|0,18),W^=Fe(re+q|0,7),Z^=Fe(W+re|0,9),q^=Fe(Z+W|0,13),re^=Fe(q+Z|0,18),K^=Fe(P+W|0,7),z^=Fe(K+P|0,9),W^=Fe(z+K|0,13),P^=Fe(W+z|0,18),T^=Fe(j+ee|0,7),Z^=Fe(T+j|0,9),ee^=Fe(Z+T|0,13),j^=Fe(ee+Z|0,18),q^=Fe(I+R|0,7),A^=Fe(q+I|0,9),R^=Fe(A+q|0,13),I^=Fe(R+A|0,18),N^=Fe(re+G|0,7),H^=Fe(N+re|0,9),G^=Fe(H+N|0,13),re^=Fe(G+H|0,18);n[i++]=s+P|0,n[i++]=a+K|0,n[i++]=l+z|0,n[i++]=u+W|0,n[i++]=d+ee|0,n[i++]=p+j|0,n[i++]=m+T|0,n[i++]=h+Z|0,n[i++]=S+A|0,n[i++]=y+R|0,n[i++]=v+I|0,n[i++]=x+q|0,n[i++]=_+N|0,n[i++]=k+H|0,n[i++]=O+G|0,n[i++]=L+re|0}function lS(e,t,r,o,n){let i=o+0,s=o+16*n;for(let a=0;a<16;a++)r[s+a]=e[t+(2*n-1)*16+a];for(let a=0;a<n;a++,i+=16,t+=16){if(GO(r,s,e,t,r,i),a>0)s+=16;GO(r,i,e,t+=16,r,s)}}function KK(e,t,r){let o=gf({dkLen:32,asyncTick:10,maxmem:1073742848},r),{N:n,r:i,p:s,dkLen:a,asyncTick:l,maxmem:u,onProgress:d}=o;if(St(n,"N"),St(i,"r"),St(s,"p"),St(a,"dkLen"),St(l,"asyncTick"),St(u,"maxmem"),d!==void 0&&typeof d!=="function")throw Error("progressCb must be a function");let p=128*i,m=p/4,h=Math.pow(2,32);if(n<=1||(n&n-1)!==0||n>h)throw Error('"N" expected a power of 2, and 2^1 <= N <= 2^32');if(s<1||s>(h-1)*32/p)throw Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)');if(a<1||a>(h-1)*32)throw Error('"dkLen" expected integer 1..(2^32 - 1) * 32');let S=p*(n+s+1);if(S>u)throw Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))='+S+", maxmem="+u);let y=cS(vt,e,t,{c:1,dkLen:p*s}),v=mf(y),x=mf(new Uint8Array(p*n)),_=mf(new Uint8Array(p)),k=()=>{};if(d){let O=2*n*s,L=Math.max(Math.floor(O/1e4),1),P=0;k=()=>{if(P++,d&&(!(P%L)||P===O))d(P/O)}}return{N:n,r:i,p:s,dkLen:a,blockSize32:m,V:x,B32:v,B:y,tmp:_,blockMixCb:k,asyncTick:l}}function HK(e,t,r,o,n){let i=cS(vt,e,r,{c:1,dkLen:t});return cr(r,o,n),i}function uS(e,t,r){let{N:o,r:n,p:i,dkLen:s,blockSize32:a,V:l,B32:u,B:d,tmp:p,blockMixCb:m}=KK(e,t,r);Jb(u);for(let h=0;h<i;h++){let S=a*h;for(let y=0;y<a;y++)l[y]=u[S+y];for(let y=0,v=0;y<o-1;y++)lS(l,v,l,v+=a,n),m();lS(l,(o-1)*a,u,S,n),m();for(let y=0;y<o;y++){let v=(u[S+a-16]&o-1)>>>0;for(let x=0;x<a;x++)p[x]=u[S+x]^l[v*a+x];lS(p,0,u,S,n),m()}}return Jb(u),HK(e,s,d,l,p)}var QO=b(()=>{WO();Ta();Jr()});function VK(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function If(e){if(typeof e!=="boolean")throw TypeError(`boolean expected, not ${e}`)}function $a(e){if(typeof e!=="number")throw TypeError("number expected, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError("positive integer expected, got "+e)}function $t(e,t,r=""){let o=VK(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+l;if(!o)throw TypeError(u);throw RangeError(u)}return e}function dS(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function YO(e,t,r=!1){$t(e,void 0,"output");let o=t.outputLen;if(e.length<o)throw RangeError("digestInto() expects output buffer of length at least "+o);if(r&&!Oa(e))throw Error("invalid output, must be aligned")}function Nn(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function un(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function WK(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function XO(e,t){if(t==null||typeof t!=="object")throw Error("options must be defined");return Object.assign(e,t)}function eC(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function tC(e,t,r){let o=t,n=r||(()=>[]),i=(a,l)=>o(l,...n(a)).update(a).digest(),s=o(new Uint8Array(e),...n(new Uint8Array(0)));return i.outputLen=s.outputLen,i.blockLen=s.blockLen,i.create=(a,...l)=>o(a,...l),i}function nu(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if($t(t,void 0,"output"),t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!Oa(t))throw Error("invalid output, must be aligned");return t}function nC(e,t,r){$a(e),$a(t),If(r);let o=new Uint8Array(16),n=WK(o);return n.setBigUint64(0,BigInt(t),r),n.setBigUint64(8,BigInt(e),r),o}function Oa(e){return e.byteOffset%4===0}function Ca(e){return Uint8Array.from($t(e))}var gs,GK=(e)=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255,QK=(e)=>{for(let t=0;t<e.length;t++)e[t]=GK(e[t]);return e},go,rC=(e,t)=>{function r(o,...n){if($t(o,void 0,"key"),e.nonceLength!==void 0){let d=n[0];$t(d,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let i=e.tagLength;if(i&&n[1]!==void 0)$t(n[1],void 0,"AAD");let s=t(o,...n),a=(d,p)=>{if(p!==void 0){if(d!==2)throw Error("cipher output not supported");$t(p,void 0,"output")}},l=!1;return{encrypt(d,p){if(l)throw Error("cannot encrypt() twice with same key + nonce");return l=!0,$t(d),a(s.encrypt.length,p),s.encrypt(d,p)},decrypt(d,p){if($t(d),i&&d.length<i)throw Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,p),s.decrypt(d,p)}}}return Object.assign(r,e),r};var kf=b(()=>{/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */gs=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)(),go=gs?(e)=>e:QK});function Je(e,t){return e<<t|e>>>32-t}function tH(e,t,r,o,n,i,s,a){let l=n.length,u=new Uint8Array(ou),d=Nn(u),p=gs&&Oa(n)&&Oa(i),m=p?Nn(n):oC,h=p?Nn(i):oC;if(!gs){for(let S=0;S<l;s++){if(e(t,r,o,d,s,a),go(d),s>=pS)throw Error("arx: counter overflow");let y=Math.min(ou,l-S);for(let v=0,x;v<y;v++)x=S+v,i[x]=n[x]^u[v];S+=y}return}for(let S=0;S<l;s++){if(e(t,r,o,d,s,a),s>=pS)throw Error("arx: counter overflow");let y=Math.min(ou,l-S);if(p&&y===ou){let v=S/4;if(S%4!==0)throw Error("arx: invalid block position");for(let x=0,_;x<eH;x++)_=v+x,h[_]=m[_]^d[x];S+=ou;continue}for(let v=0,x;v<y;v++)x=S+v,i[x]=n[x]^u[v];S+=y}}function sC(e,t){let{allowShortKeys:r,extendNonceFn:o,counterLength:n,counterRight:i,rounds:s}=XO({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=="function")throw Error("core must be a function");return $a(n),$a(s),If(i),If(r),(a,l,u,d,p=0)=>{$t(a,void 0,"key"),$t(l,void 0,"nonce"),$t(u,void 0,"data");let m=u.length;if(d=nu(m,d,!1),$a(p),p<0||p>=pS)throw Error("arx: counter overflow");let h=[],S=a.length,y,v;if(S===32)h.push(y=Ca(a)),v=XK;else if(S===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),v=YK,h.push(y);else throw $t(a,32,"arx key"),Error("invalid key size");if(!gs||!Oa(l))h.push(l=Ca(l));let x=Nn(y);if(o){if(l.length!==24)throw Error("arx: extended nonce must be 24 bytes");let O=l.subarray(0,16);if(gs)o(v,x,Nn(O),x);else{let L=go(Uint32Array.from(v));o(L,x,Nn(O),x),un(L),go(x)}l=l.subarray(16)}else if(!gs)go(x);let _=16-n;if(_!==l.length)throw Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){let O=new Uint8Array(12);O.set(l,i?0:12-l.length),l=O,h.push(l)}let k=go(Nn(l));try{return tH(e,v,x,k,u,d,p,s),d}finally{un(...h)}}}var iC=(e)=>Uint8Array.from(e.split(""),(t)=>t.charCodeAt(0)),YK,XK,ou=64,eH=16,pS,oC;var aC=b(()=>{kf();YK=(()=>go(Nn(iC("expand 16-byte k"))))(),XK=(()=>go(Nn(iC("expand 32-byte k"))))();pS=(()=>4294967295)(),oC=Uint32Array.of()});function Ft(e,t){return e[t++]&255|(e[t++]&255)<<8}class cC{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Ca($t(e,32,"key"));let t=Ft(e,0),r=Ft(e,2),o=Ft(e,4),n=Ft(e,6),i=Ft(e,8),s=Ft(e,10),a=Ft(e,12),l=Ft(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|n<<9)&8191,this.r[4]=(n>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|s<<2)&8191,this.r[7]=(s>>>11|a<<5)&8065,this.r[8]=(a>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ft(e,16+2*u)}process(e,t,r=!1){let o=r?0:2048,{h:n,r:i}=this,s=i[0],a=i[1],l=i[2],u=i[3],d=i[4],p=i[5],m=i[6],h=i[7],S=i[8],y=i[9],v=Ft(e,t+0),x=Ft(e,t+2),_=Ft(e,t+4),k=Ft(e,t+6),O=Ft(e,t+8),L=Ft(e,t+10),P=Ft(e,t+12),K=Ft(e,t+14),z=n[0]+(v&8191),W=n[1]+((v>>>13|x<<3)&8191),ee=n[2]+((x>>>10|_<<6)&8191),j=n[3]+((_>>>7|k<<9)&8191),T=n[4]+((k>>>4|O<<12)&8191),Z=n[5]+(O>>>1&8191),A=n[6]+((O>>>14|L<<2)&8191),R=n[7]+((L>>>11|P<<5)&8191),I=n[8]+((P>>>8|K<<8)&8191),q=n[9]+(K>>>5|o),N=0,H=N+z*s+W*(5*y)+ee*(5*S)+j*(5*h)+T*(5*m);N=H>>>13,H&=8191,H+=Z*(5*p)+A*(5*d)+R*(5*u)+I*(5*l)+q*(5*a),N+=H>>>13,H&=8191;let G=N+z*a+W*s+ee*(5*y)+j*(5*S)+T*(5*h);N=G>>>13,G&=8191,G+=Z*(5*m)+A*(5*p)+R*(5*d)+I*(5*u)+q*(5*l),N+=G>>>13,G&=8191;let re=N+z*l+W*a+ee*s+j*(5*y)+T*(5*S);N=re>>>13,re&=8191,re+=Z*(5*h)+A*(5*m)+R*(5*p)+I*(5*d)+q*(5*u),N+=re>>>13,re&=8191;let ae=N+z*u+W*l+ee*a+j*s+T*(5*y);N=ae>>>13,ae&=8191,ae+=Z*(5*S)+A*(5*h)+R*(5*m)+I*(5*p)+q*(5*d),N+=ae>>>13,ae&=8191;let me=N+z*d+W*u+ee*l+j*a+T*s;N=me>>>13,me&=8191,me+=Z*(5*y)+A*(5*S)+R*(5*h)+I*(5*m)+q*(5*p),N+=me>>>13,me&=8191;let Se=N+z*p+W*d+ee*u+j*l+T*a;N=Se>>>13,Se&=8191,Se+=Z*s+A*(5*y)+R*(5*S)+I*(5*h)+q*(5*m),N+=Se>>>13,Se&=8191;let xe=N+z*m+W*p+ee*d+j*u+T*l;N=xe>>>13,xe&=8191,xe+=Z*a+A*s+R*(5*y)+I*(5*S)+q*(5*h),N+=xe>>>13,xe&=8191;let ke=N+z*h+W*m+ee*p+j*d+T*u;N=ke>>>13,ke&=8191,ke+=Z*l+A*a+R*s+I*(5*y)+q*(5*S),N+=ke>>>13,ke&=8191;let Ie=N+z*S+W*h+ee*m+j*p+T*d;N=Ie>>>13,Ie&=8191,Ie+=Z*u+A*l+R*a+I*s+q*(5*y),N+=Ie>>>13,Ie&=8191;let _e=N+z*y+W*S+ee*h+j*m+T*p;N=_e>>>13,_e&=8191,_e+=Z*d+A*u+R*l+I*a+q*s,N+=_e>>>13,_e&=8191,N=(N<<2)+N|0,N=N+H|0,H=N&8191,N=N>>>13,G+=N,n[0]=H,n[1]=G,n[2]=re,n[3]=ae,n[4]=me,n[5]=Se,n[6]=xe,n[7]=ke,n[8]=Ie,n[9]=_e}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let s=2;s<10;s++)e[s]+=o,o=e[s]>>>13,e[s]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let s=1;s<10;s++)r[s]=e[s]+o,o=r[s]>>>13,r[s]&=8191;r[9]-=8192;let n=(o^1)-1;for(let s=0;s<10;s++)r[s]&=n;n=~n;for(let s=0;s<10;s++)e[s]=e[s]&n|r[s];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let s=1;s<8;s++)i=(e[s]+t[s]|0)+(i>>>16)|0,e[s]=i&65535;un(r)}update(e){dS(this),$t(e),e=Ca(e);let{buffer:t,blockLen:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(r-this.pos,o-n);if(i===r){for(;r<=o-n;n+=r)this.process(e,n);continue}if(t.set(e.subarray(n,n+i),this.pos),this.pos+=i,n+=i,this.pos===r)this.process(t,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,un(this.h,this.r,this.buffer,this.pad)}digestInto(e){dS(this),YO(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:o}=this;if(o){t[o++]=1;for(;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let i=0;i<8;i++)e[n++]=r[i]>>>0,e[n++]=r[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}var lC;var uC=b(()=>{kf();lC=tC(32,(e)=>new cC(e))});function rH(e,t,r,o,n,i=20){let s=e[0],a=e[1],l=e[2],u=e[3],d=t[0],p=t[1],m=t[2],h=t[3],S=t[4],y=t[5],v=t[6],x=t[7],_=n,k=r[0],O=r[1],L=r[2],P=s,K=a,z=l,W=u,ee=d,j=p,T=m,Z=h,A=S,R=y,I=v,q=x,N=_,H=k,G=O,re=L;for(let me=0;me<i;me+=2)P=P+ee|0,N=Je(N^P,16),A=A+N|0,ee=Je(ee^A,12),P=P+ee|0,N=Je(N^P,8),A=A+N|0,ee=Je(ee^A,7),K=K+j|0,H=Je(H^K,16),R=R+H|0,j=Je(j^R,12),K=K+j|0,H=Je(H^K,8),R=R+H|0,j=Je(j^R,7),z=z+T|0,G=Je(G^z,16),I=I+G|0,T=Je(T^I,12),z=z+T|0,G=Je(G^z,8),I=I+G|0,T=Je(T^I,7),W=W+Z|0,re=Je(re^W,16),q=q+re|0,Z=Je(Z^q,12),W=W+Z|0,re=Je(re^W,8),q=q+re|0,Z=Je(Z^q,7),P=P+j|0,re=Je(re^P,16),I=I+re|0,j=Je(j^I,12),P=P+j|0,re=Je(re^P,8),I=I+re|0,j=Je(j^I,7),K=K+T|0,N=Je(N^K,16),q=q+N|0,T=Je(T^q,12),K=K+T|0,N=Je(N^K,8),q=q+N|0,T=Je(T^q,7),z=z+Z|0,H=Je(H^z,16),A=A+H|0,Z=Je(Z^A,12),z=z+Z|0,H=Je(H^z,8),A=A+H|0,Z=Je(Z^A,7),W=W+ee|0,G=Je(G^W,16),R=R+G|0,ee=Je(ee^R,12),W=W+ee|0,G=Je(G^W,8),R=R+G|0,ee=Je(ee^R,7);let ae=0;o[ae++]=s+P|0,o[ae++]=a+K|0,o[ae++]=l+z|0,o[ae++]=u+W|0,o[ae++]=d+ee|0,o[ae++]=p+j|0,o[ae++]=m+T|0,o[ae++]=h+Z|0,o[ae++]=S+A|0,o[ae++]=y+R|0,o[ae++]=v+I|0,o[ae++]=x+q|0,o[ae++]=_+N|0,o[ae++]=k+H|0,o[ae++]=O+G|0,o[ae++]=L+re|0}function pC(e,t,r,o,n){if(n!==void 0)$t(n,void 0,"AAD");let i=e(t,r,iH),s=nC(o.length,n?n.length:0,!0),a=lC.create(i);if(n)dC(a,n);dC(a,o),a.update(s);let l=a.digest();return un(i,s),l}var nH,oH,dC=(e,t)=>{e.update(t);let r=t.length%16;if(r)e.update(oH.subarray(r))},iH,sH=(e)=>(t,r,o)=>({encrypt(i,s){let a=i.length;s=nu(a+16,s,!1),s.set(i);let l=s.subarray(0,-16);e(t,r,l,l,1);let u=pC(e,t,r,l,o);return s.set(u,a),un(u),s},decrypt(i,s){s=nu(i.length-16,s,!1);let a=i.subarray(0,-16),l=i.subarray(-16),u=pC(e,t,r,a,o);if(!eC(l,u))throw un(u),Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,r,s,s,1),un(u),s}}),Hr;var fS=b(()=>{aC();uC();kf();nH=sC(rH,{counterRight:!1,counterLength:4,allowShortKeys:!1}),oH=new Uint8Array(16),iH=new Uint8Array(32);Hr=rC({blockSize:64,nonceLength:12,tagLength:16},sH(nH))});function za(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Zt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw Error(`${r}expected integer >= 0, got ${e}`)}}function Re(e,t,r=""){let o=za(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`;throw Error(s+"expected Uint8Array"+a+", got "+l)}return e}function Vr(e){if(typeof e!=="function"||typeof e.create!=="function")throw Error("Hash must wrapped by utils.createHasher");Zt(e.outputLen),Zt(e.blockLen)}function bo(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Rf(e,t){Re(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw Error('"digestInto() output" expected to be of length >='+r)}function Tf(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function wr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function $f(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function dn(e,t){return e<<32-t|e>>>t}function cH(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function lH(e){for(let t=0;t<e.length;t++)e[t]=cH(e[t]);return e}function ys(e){if(Re(e),mC)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=uH[e[r]];return t}function fC(e){if(e>=yo._0&&e<=yo._9)return e-yo._0;if(e>=yo.A&&e<=yo.F)return e-(yo.A-10);if(e>=yo.a&&e<=yo.f)return e-(yo.a-10);return}function bs(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);if(mC)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=fC(e.charCodeAt(i)),a=fC(e.charCodeAt(i+1));if(s===void 0||a===void 0){let l=e[i]+e[i+1];throw Error('hex string expected, got non-hex character "'+l+'" at index '+i)}o[n]=s*16+a}return o}function At(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Re(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function Pa(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function ni(e=32){let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}var aH,mS,mC,uH,yo,oi=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Dr=b(()=>{/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */aH=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();mS=aH?(e)=>e:lH,mC=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),uH=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));yo={_0:48,_9:57,A:65,F:70,a:97,f:102}});function iu(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw Error(r+"expected boolean, got type="+typeof e)}return e}function hC(e){if(typeof e==="bigint"){if(!Of(e))throw Error("positive bigint expected, got "+e)}else Zt(e);return e}function su(e){let t=hC(e).toString(16);return t.length&1?"0"+t:t}function gC(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);return e===""?gS:BigInt("0x"+e)}function ii(e){return gC(ys(e))}function si(e){return gC(ys(Cf(Re(e)).reverse()))}function Na(e,t){Zt(t),e=hC(e);let r=bs(e.toString(16).padStart(t*2,"0"));if(r.length!==t)throw Error("number too large");return r}function au(e,t){return Na(e,t).reverse()}function Cf(e){return Uint8Array.from(e)}function ai(e){return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw Error(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}function dH(e,t,r){return Of(e)&&Of(t)&&Of(r)&&t<=e&&e<r}function cu(e,t,r,o){if(!dH(t,r,o))throw Error("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function yS(e){let t;for(t=0;e>gS;e>>=hS,t+=1);return t}function yC(e,t,r){if(Zt(e,"hashLen"),Zt(t,"qByteLen"),typeof r!=="function")throw Error("hmacFn must be a function");let o=(v)=>new Uint8Array(v),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,l=o(e),u=o(e),d=0,p=()=>{l.fill(1),u.fill(0),d=0},m=(...v)=>r(u,At(l,...v)),h=(v=n)=>{if(u=m(i,v),l=m(),v.length===0)return;u=m(s,v),l=m()},S=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let v=0,x=[];while(v<t){l=m();let _=l.slice();x.push(_),v+=l.length}return At(...x)};return(v,x)=>{p(),h(v);let _=void 0;while(!(_=x(S())))h();return p(),_}}function Ss(e,t={},r={}){if(!e||typeof e!=="object")throw Error("expected valid options object");function o(i,s,a){let l=e[i];if(a&&l===void 0)return;let u=typeof l;if(u!==s||l===null)throw Error(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,l])=>o(a,l,s));n(t,!1),n(r,!0)}function bS(e){let t=new WeakMap;return(r,...o)=>{let n=t.get(r);if(n!==void 0)return n;let i=e(r,...o);return t.set(r,i),i}}var gS,hS,Of=(e)=>typeof e==="bigint"&&gS<=e,lu=(e)=>(hS<<BigInt(e))-hS;var Da=b(()=>{Dr();Dr();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */gS=BigInt(0),hS=BigInt(1)});function lr(e,t){let r=e%t;return r>=ur?r:t+r}function Wr(e,t,r){let o=e;while(t-- >ur)o*=o,o%=r;return o}function bC(e,t){if(e===ur)throw Error("invert: expected non-zero number");if(t<=ur)throw Error("invert: expected positive modulus, got "+t);let r=lr(e,t),o=t,n=ur,i=Xt,s=Xt,a=ur;while(r!==ur){let u=o/r,d=o%r,p=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=p,a=m}if(o!==Xt)throw Error("invert: does not exist");return lr(n,t)}function SS(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function AC(e,t){let r=(e.ORDER+Xt)/wC,o=e.pow(t,r);return SS(e,o,t),o}function mH(e,t){let r=(e.ORDER-xC)/_C,o=e.mul(t,vs),n=e.pow(o,r),i=e.mul(t,n),s=e.mul(e.mul(i,vs),n),a=e.mul(i,e.sub(s,e.ONE));return SS(e,a,t),a}function hH(e){let t=zf(e),r=IC(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+pH)/EC;return(a,l)=>{let u=a.pow(l,s),d=a.mul(u,o),p=a.mul(u,n),m=a.mul(u,i),h=a.eql(a.sqr(d),l),S=a.eql(a.sqr(p),l);u=a.cmov(u,d,h),d=a.cmov(m,p,S);let y=a.eql(a.sqr(d),l),v=a.cmov(u,d,y);return SS(a,v,l),v}}function IC(e){if(e<vC)throw Error("sqrt is not defined for small field");let t=e-Xt,r=0;while(t%vs===ur)t/=vs,r++;let o=vs,n=zf(e);while(SC(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return AC;let i=n.pow(o,t),s=(t+Xt)/vs;return function(l,u){if(l.is0(u))return u;if(SC(l,u)!==1)throw Error("Cannot find square root");let d=r,p=l.mul(l.ONE,i),m=l.pow(u,t),h=l.pow(u,s);while(!l.eql(m,l.ONE)){if(l.is0(m))return l.ZERO;let S=1,y=l.sqr(m);while(!l.eql(y,l.ONE))if(S++,y=l.sqr(y),S===d)throw Error("Cannot find square root");let v=Xt<<BigInt(d-S-1),x=l.pow(p,v);d=S,p=l.sqr(x),m=l.mul(m,p),h=l.mul(h,x)}return h}}function gH(e){if(e%wC===vC)return AC;if(e%_C===xC)return mH;if(e%EC===fH)return hH(e);return IC(e)}function vS(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=yH.reduce((o,n)=>(o[n]="function",o),t);return Ss(e,r),e}function bH(e,t,r){if(r<ur)throw Error("invalid exponent, negatives unsupported");if(r===ur)return e.ONE;if(r===Xt)return t;let o=e.ONE,n=t;while(r>ur){if(r&Xt)o=e.mul(o,n);n=e.sqr(n),r>>=Xt}return o}function uu(e,t,r=!1){let o=Array(t.length).fill(r?e.ZERO:void 0),n=t.reduce((s,a,l)=>{if(e.is0(a))return s;return o[l]=s,e.mul(s,a)},e.ONE),i=e.inv(n);return t.reduceRight((s,a,l)=>{if(e.is0(a))return s;return o[l]=e.mul(s,o[l]),e.mul(s,a)},i),o}function SC(e,t){let r=(e.ORDER-Xt)/vs,o=e.pow(t,r),n=e.eql(o,e.ONE),i=e.eql(o,e.ZERO),s=e.eql(o,e.neg(e.ONE));if(!n&&!i&&!s)throw Error("invalid Legendre symbol result");return n?1:i?0:-1}function SH(e,t){if(t!==void 0)Zt(t);let r=t!==void 0?t:e.toString(2).length,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}class kC{ORDER;BITS;BYTES;isLE;ZERO=ur;ONE=Xt;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=ur)throw Error("invalid field: expected ORDER > 0, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")this.sqrt=t.sqrt;if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=t.allowedLengths?.slice();if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=SH(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return lr(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof e);return ur<=e&&e<this.ORDER}is0(e){return e===ur}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Xt)===Xt}neg(e){return lr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return lr(e*e,this.ORDER)}add(e,t){return lr(e+t,this.ORDER)}sub(e,t){return lr(e-t,this.ORDER)}mul(e,t){return lr(e*t,this.ORDER)}pow(e,t){return bH(this,e,t)}div(e,t){return lr(e*bC(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return bC(e,this.ORDER)}sqrt(e){if(!this._sqrt)this._sqrt=gH(this.ORDER);return this._sqrt(this,e)}toBytes(e){return this.isLE?au(e,this.BYTES):Na(e,this.BYTES)}fromBytes(e,t=!1){Re(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,n?0:l.length-e.length),e=l}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?si(e):ii(e);if(s)a=lr(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return uu(this,e)}cmov(e,t,r){return r?t:e}}function zf(e,t={}){return new kC(e,t)}function RC(e){if(typeof e!=="bigint")throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function wS(e){let t=RC(e);return t+Math.ceil(t/2)}function TC(e,t,r=!1){Re(e);let o=e.length,n=RC(t),i=wS(t);if(o<16||o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?si(e):ii(e),a=lr(s,t-Xt)+Xt;return r?au(a,n):Na(a,n)}var ur,Xt,vs,vC,wC,xC,pH,_C,fH,EC,yH;var du=b(()=>{Da();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ur=BigInt(0),Xt=BigInt(1),vs=BigInt(2),vC=BigInt(3),wC=BigInt(4),xC=BigInt(5),pH=BigInt(7),_C=BigInt(8),fH=BigInt(9),EC=BigInt(16);yH=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function pu(e,t){let r=t.negate();return e?r:t}function AS(e,t){let r=uu(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function zC(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function xS(e,t){zC(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=lu(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function $C(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),l=e>>s;if(a>o)a-=i,l+=ws;let u=t*o,d=u+Math.abs(a)-1,p=a===0,m=a<0,h=t%2!==0;return{nextN:l,offset:d,isZero:p,isNeg:m,isNegF:h,offsetF:u}}function ES(e){return PC.get(e)||1}function OC(e){if(e!==La)throw Error("invalid wNAF")}class IS{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>La){if(t&ws)r=r.add(o);o=o.double(),t>>=ws}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=xS(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let l=1;l<o;l++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=xS(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:m}=$C(r,s,i);if(r=a,u)n=n.add(pu(p,t[m]));else o=o.add(pu(d,t[l]))}return OC(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=xS(e,this.bits);for(let i=0;i<n.windows;i++){if(r===La)break;let{nextN:s,offset:a,isZero:l,isNeg:u}=$C(r,i,n);if(r=s,l)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return OC(r),o}getPrecomputes(e,t,r){let o=_S.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);_S.set(t,o)}}return o}cached(e,t,r){let o=ES(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=ES(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){zC(t,this.bits),PC.set(e,t),_S.delete(e)}hasCache(e){return ES(e)!==1}}function NC(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>La||o>La){if(r&ws)i=i.add(n);if(o&ws)s=s.add(n);n=n.double(),r>>=ws,o>>=ws}return{p1:i,p2:s}}function CC(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return vS(t),t}else return zf(e,{isLE:r})}function DC(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let l of["p","n","h"]){let u=t[l];if(!(typeof u==="bigint"&&u>La))throw Error(`CURVE.${l} must be positive bigint`)}let n=CC(t.p,r.Fp,o),i=CC(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(t[l]))throw Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function Pf(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}var La,ws,_S,PC;var kS=b(()=>{Da();du();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */La=BigInt(0),ws=BigInt(1);_S=new WeakMap,PC=new WeakMap});function vH(e){return Ss(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function LC(e){let t=vH(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let l=s||ni,u=a?255:448,d=a?32:56,p=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?Nf**BigInt(254):Nf**BigInt(447),S=a?BigInt(8)*Nf**BigInt(251)-Za:BigInt(4)*Nf**BigInt(445)-Za,y=h+S+Za,v=(A)=>lr(A,r),x=_(p);function _(A){return au(v(A),d)}function k(A){let R=Cf(Re(A,d,"uCoordinate"));if(a)R[31]&=127;return v(si(R))}function O(A){return si(n(Cf(Re(A,d,"scalar"))))}function L(A,R){let I=ee(k(R),O(A));if(I===fu)throw Error("invalid private or public key received");return _(I)}function P(A){return L(A,x)}let K=P,z=L;function W(A,R,I){let q=v(A*(R-I));return R=v(R-q),I=v(I+q),{x_2:R,x_3:I}}function ee(A,R){cu("u",A,fu,r),cu("scalar",R,h,y);let I=R,q=A,N=Za,H=fu,G=A,re=Za,ae=fu;for(let Se=BigInt(u-1);Se>=fu;Se--){let xe=I>>Se&Za;ae^=xe,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=xe;let ke=N+H,Ie=v(ke*ke),_e=N-H,Ue=v(_e*_e),De=Ie-Ue,Qe=G+re,bt=G-re,Tt=v(bt*ke),Dt=v(Qe*_e),lt=Tt+Dt,Or=Tt-Dt;G=v(lt*lt),re=v(q*v(Or*Or)),N=v(Ie*Ue),H=v(De*(Ie+v(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let me=i(H);return v(N*me)}let j={secretKey:d,publicKey:d,seed:d},T=(A=l(d))=>(Re(A,j.seed,"seed"),A),Z={randomSecretKey:T};return Object.freeze({keygen:Pf(T,K),getSharedSecret:z,getPublicKey:K,scalarMult:L,scalarMultBase:P,utils:Z,GuBytes:x.slice(),lengths:j})}var fu,Za,Nf;var ZC=b(()=>{Da();kS();du();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */fu=BigInt(0),Za=BigInt(1),Nf=BigInt(2)});class RS{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Vr(e),Re(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),wr(o)}update(e){return bo(this),this.iHash.update(e),this}digestInto(e){bo(this),Re(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var ja=(e,t,r)=>new RS(e,t).update(r).digest();var TS=b(()=>{Dr();ja.create=(e,t)=>new RS(e,t)});function wH(e,t,r){let[[o,n],[i,s]]=t,a=jC(s*e,r),l=jC(-n*e,r),u=e-a*o-l*i,d=-a*n-l*s,p=u<So,m=d<So;if(p)u=-u;if(m)d=-d;let h=lu(Math.ceil(yS(r)/2))+Ba;if(u<So||u>=h||d<So||d>=h)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:p,k1:u,k2neg:m,k2:d}}function OS(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function $S(e,t){let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(iu(r.lowS,"lowS"),iu(r.prehash,"prehash"),r.format!==void 0)OS(r.format);return r}function CS(e,t={}){let r=DC("weierstrass",e,t),{Fp:o,Fn:n}=r,i=r.CURVE,{h:s,n:a}=i;Ss(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:l}=t;if(l){if(!o.is0(i.a)||typeof l.beta!=="bigint"||!Array.isArray(l.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let u=qC(o,n);function d(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function p(T,Z,A){let{x:R,y:I}=Z.toAffine(),q=o.toBytes(R);if(iu(A,"isCompressed"),A){d();let N=!o.isOdd(I);return At(MC(N),q)}else return At(Uint8Array.of(4),q,o.toBytes(I))}function m(T){Re(T,void 0,"Point");let{publicKey:Z,publicKeyUncompressed:A}=u,R=T.length,I=T[0],q=T.subarray(1);if(R===Z&&(I===2||I===3)){let N=o.fromBytes(q);if(!o.isValid(N))throw Error("bad point: is not on curve, wrong x");let H=y(N),G;try{G=o.sqrt(H)}catch(me){let Se=me instanceof Error?": "+me.message:"";throw Error("bad point: is not on curve, sqrt error"+Se)}d();let re=o.isOdd(G);if((I&1)===1!==re)G=o.neg(G);return{x:N,y:G}}else if(R===A&&I===4){let N=o.BYTES,H=o.fromBytes(q.subarray(0,N)),G=o.fromBytes(q.subarray(N,N*2));if(!v(H,G))throw Error("bad point: is not on curve");return{x:H,y:G}}else throw Error(`bad point: got length ${R}, expected compressed=${Z} or uncompressed=${A}`)}let h=t.toBytes||p,S=t.fromBytes||m;function y(T){let Z=o.sqr(T),A=o.mul(Z,T);return o.add(o.add(A,o.mul(T,i.a)),i.b)}function v(T,Z){let A=o.sqr(Z),R=y(T);return o.eql(A,R)}if(!v(i.Gx,i.Gy))throw Error("bad curve params: generator point");let x=o.mul(o.pow(i.a,Df),xH),_=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(x,_)))throw Error("bad curve params: a or b");function k(T,Z,A=!1){if(!o.isValid(Z)||A&&o.is0(Z))throw Error(`bad point coordinate ${T}`);return Z}function O(T){if(!(T instanceof W))throw Error("Weierstrass Point expected")}function L(T){if(!l||!l.basises)throw Error("no endo");return wH(T,l.basises,n.ORDER)}let P=bS((T,Z)=>{let{X:A,Y:R,Z:I}=T;if(o.eql(I,o.ONE))return{x:A,y:R};let q=T.is0();if(Z==null)Z=q?o.ONE:o.inv(I);let N=o.mul(A,Z),H=o.mul(R,Z),G=o.mul(I,Z);if(q)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}),K=bS((T)=>{if(T.is0()){if(t.allowInfinityPoint&&!o.is0(T.Y))return;throw Error("bad point: ZERO")}let{x:Z,y:A}=T.toAffine();if(!o.isValid(Z)||!o.isValid(A))throw Error("bad point: x or y not field elements");if(!v(Z,A))throw Error("bad point: equation left != right");if(!T.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});function z(T,Z,A,R,I){return A=new W(o.mul(A.X,T),A.Y,A.Z),Z=pu(R,Z),A=pu(I,A),Z.add(A)}class W{static BASE=new W(i.Gx,i.Gy,o.ONE);static ZERO=new W(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(T,Z,A){this.X=k("x",T),this.Y=k("y",Z,!0),this.Z=k("z",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(T){let{x:Z,y:A}=T||{};if(!T||!o.isValid(Z)||!o.isValid(A))throw Error("invalid affine point");if(T instanceof W)throw Error("projective point not allowed");if(o.is0(Z)&&o.is0(A))return W.ZERO;return new W(Z,A,o.ONE)}static fromBytes(T){let Z=W.fromAffine(S(Re(T,void 0,"point")));return Z.assertValidity(),Z}static fromHex(T){return W.fromBytes(bs(T))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(T=8,Z=!0){if(j.createCache(this,T),!Z)this.multiply(Df);return this}assertValidity(){K(this)}hasEvenY(){let{y:T}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(T)}equals(T){O(T);let{X:Z,Y:A,Z:R}=this,{X:I,Y:q,Z:N}=T,H=o.eql(o.mul(Z,N),o.mul(I,R)),G=o.eql(o.mul(A,N),o.mul(q,R));return H&&G}negate(){return new W(this.X,o.neg(this.Y),this.Z)}double(){let{a:T,b:Z}=i,A=o.mul(Z,Df),{X:R,Y:I,Z:q}=this,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=o.mul(R,R),ae=o.mul(I,I),me=o.mul(q,q),Se=o.mul(R,I);return Se=o.add(Se,Se),G=o.mul(R,q),G=o.add(G,G),N=o.mul(T,G),H=o.mul(A,me),H=o.add(N,H),N=o.sub(ae,H),H=o.add(ae,H),H=o.mul(N,H),N=o.mul(Se,N),G=o.mul(A,G),me=o.mul(T,me),Se=o.sub(re,me),Se=o.mul(T,Se),Se=o.add(Se,G),G=o.add(re,re),re=o.add(G,re),re=o.add(re,me),re=o.mul(re,Se),H=o.add(H,re),me=o.mul(I,q),me=o.add(me,me),re=o.mul(me,Se),N=o.sub(N,re),G=o.mul(me,ae),G=o.add(G,G),G=o.add(G,G),new W(N,H,G)}add(T){O(T);let{X:Z,Y:A,Z:R}=this,{X:I,Y:q,Z:N}=T,H=o.ZERO,G=o.ZERO,re=o.ZERO,ae=i.a,me=o.mul(i.b,Df),Se=o.mul(Z,I),xe=o.mul(A,q),ke=o.mul(R,N),Ie=o.add(Z,A),_e=o.add(I,q);Ie=o.mul(Ie,_e),_e=o.add(Se,xe),Ie=o.sub(Ie,_e),_e=o.add(Z,R);let Ue=o.add(I,N);return _e=o.mul(_e,Ue),Ue=o.add(Se,ke),_e=o.sub(_e,Ue),Ue=o.add(A,R),H=o.add(q,N),Ue=o.mul(Ue,H),H=o.add(xe,ke),Ue=o.sub(Ue,H),re=o.mul(ae,_e),H=o.mul(me,ke),re=o.add(H,re),H=o.sub(xe,re),re=o.add(xe,re),G=o.mul(H,re),xe=o.add(Se,Se),xe=o.add(xe,Se),ke=o.mul(ae,ke),_e=o.mul(me,_e),xe=o.add(xe,ke),ke=o.sub(Se,ke),ke=o.mul(ae,ke),_e=o.add(_e,ke),Se=o.mul(xe,_e),G=o.add(G,Se),Se=o.mul(Ue,_e),H=o.mul(Ie,H),H=o.sub(H,Se),Se=o.mul(Ie,xe),re=o.mul(Ue,re),re=o.add(re,Se),new W(H,G,re)}subtract(T){return this.add(T.negate())}is0(){return this.equals(W.ZERO)}multiply(T){let{endo:Z}=t;if(!n.isValidNot0(T))throw Error("invalid scalar: out of range");let A,R,I=(q)=>j.cached(this,q,(N)=>AS(W,N));if(Z){let{k1neg:q,k1:N,k2neg:H,k2:G}=L(T),{p:re,f:ae}=I(N),{p:me,f:Se}=I(G);R=ae.add(Se),A=z(Z.beta,re,me,q,H)}else{let{p:q,f:N}=I(T);A=q,R=N}return AS(W,[A,R])[0]}multiplyUnsafe(T){let{endo:Z}=t,A=this;if(!n.isValid(T))throw Error("invalid scalar: out of range");if(T===So||A.is0())return W.ZERO;if(T===Ba)return A;if(j.hasCache(this))return this.multiply(T);if(Z){let{k1neg:R,k1:I,k2neg:q,k2:N}=L(T),{p1:H,p2:G}=NC(W,A,I,N);return z(Z.beta,H,G,R,q)}else return j.unsafe(A,T)}toAffine(T){return P(this,T)}isTorsionFree(){let{isTorsionFree:T}=t;if(s===Ba)return!0;if(T)return T(W,this);return j.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:T}=t;if(s===Ba)return this;if(T)return T(W,this);return this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(T=!0){return iu(T,"isCompressed"),this.assertValidity(),h(W,this,T)}toHex(T=!0){return ys(this.toBytes(T))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let ee=n.BITS,j=new IS(W,t.endo?Math.ceil(ee/2):ee);return W.BASE.precompute(8),W}function MC(e){return Uint8Array.of(e?2:3)}function qC(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function _H(e,t={}){let{Fn:r}=e,o=t.randomBytes||ni,n=Object.assign(qC(e.Fp,r),{seed:wS(r.ORDER)});function i(h){try{let S=r.fromBytes(h);return r.isValidNot0(S)}catch(S){return!1}}function s(h,S){let{publicKey:y,publicKeyUncompressed:v}=n;try{let x=h.length;if(S===!0&&x!==y)return!1;if(S===!1&&x!==v)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h=o(n.seed)){return TC(Re(h,n.seed,"seed"),r.ORDER)}function l(h,S=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(S)}function u(h){let{secretKey:S,publicKey:y,publicKeyUncompressed:v}=n;if(!za(h))return;if("_lengths"in r&&r._lengths||S===y)return;let x=Re(h,void 0,"key").length;return x===y||x===v}function d(h,S,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(S)===!1)throw Error("second arg must be public key");let v=r.fromBytes(h);return e.fromBytes(S).multiply(v).toBytes(y)}let p={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=Pf(a,l);return Object.freeze({getPublicKey:l,getSharedSecret:d,keygen:m,Point:e,utils:p,lengths:n})}function zS(e,t,r={}){Vr(t),Ss(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes||ni,n=r.hmac||((A,R)=>ja(t,A,R)),{Fp:i,Fn:s}=e,{ORDER:a,BITS:l}=s,{keygen:u,getPublicKey:d,getSharedSecret:p,utils:m,lengths:h}=_H(e,r),S={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=a*UC<i.ORDER;function v(A){let R=a>>Ba;return A>R}function x(A,R){if(!s.isValidNot0(R))throw Error(`invalid signature ${A}: out of range 1..Point.Fn.ORDER`);return R}function _(){if(y)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function k(A,R){OS(R);let I=h.signature,q=R==="compact"?I:R==="recovered"?I+1:void 0;return Re(A,q)}class O{r;s;recovery;constructor(A,R,I){if(this.r=x("r",A),this.s=x("s",R),I!=null){if(_(),![0,1,2,3].includes(I))throw Error("invalid recovery id");this.recovery=I}Object.freeze(this)}static fromBytes(A,R=S.format){k(A,R);let I;if(R==="der"){let{r:G,s:re}=ci.toSig(Re(A));return new O(G,re)}if(R==="recovered")I=A[0],R="compact",A=A.subarray(1);let q=h.signature/2,N=A.subarray(0,q),H=A.subarray(q,q*2);return new O(s.fromBytes(N),s.fromBytes(H),I)}static fromHex(A,R){return this.fromBytes(bs(A),R)}assertRecovery(){let{recovery:A}=this;if(A==null)throw Error("invalid recovery id: must be present");return A}addRecoveryBit(A){return new O(this.r,this.s,A)}recoverPublicKey(A){let{r:R,s:I}=this,q=this.assertRecovery(),N=q===2||q===3?R+a:R;if(!i.isValid(N))throw Error("invalid recovery id: sig.r+curve.n != R.x");let H=i.toBytes(N),G=e.fromBytes(At(MC((q&1)===0),H)),re=s.inv(N),ae=P(Re(A,void 0,"msgHash")),me=s.create(-ae*re),Se=s.create(I*re),xe=e.BASE.multiplyUnsafe(me).add(G.multiplyUnsafe(Se));if(xe.is0())throw Error("invalid recovery: point at infinify");return xe.assertValidity(),xe}hasHighS(){return v(this.s)}toBytes(A=S.format){if(OS(A),A==="der")return bs(ci.hexFromSig(this));let{r:R,s:I}=this,q=s.toBytes(R),N=s.toBytes(I);if(A==="recovered")return _(),At(Uint8Array.of(this.assertRecovery()),q,N);return At(q,N)}toHex(A){return ys(this.toBytes(A))}}let L=r.bits2int||function(R){if(R.length>8192)throw Error("input is too large");let I=ii(R),q=R.length*8-l;return q>0?I>>BigInt(q):I},P=r.bits2int_modN||function(R){return s.create(L(R))},K=lu(l);function z(A){return cu("num < 2^"+l,A,So,K),s.toBytes(A)}function W(A,R){return Re(A,void 0,"message"),R?Re(t(A),void 0,"prehashed message"):A}function ee(A,R,I){let{lowS:q,prehash:N,extraEntropy:H}=$S(I,S);A=W(A,N);let G=P(A),re=s.fromBytes(R);if(!s.isValidNot0(re))throw Error("invalid private key");let ae=[z(re),z(G)];if(H!=null&&H!==!1){let ke=H===!0?o(h.secretKey):H;ae.push(Re(ke,void 0,"extraEntropy"))}let me=At(...ae),Se=G;function xe(ke){let Ie=L(ke);if(!s.isValidNot0(Ie))return;let _e=s.inv(Ie),Ue=e.BASE.multiply(Ie).toAffine(),De=s.create(Ue.x);if(De===So)return;let Qe=s.create(_e*s.create(Se+De*re));if(Qe===So)return;let bt=(Ue.x===De?0:2)|Number(Ue.y&Ba),Tt=Qe;if(q&&v(Qe))Tt=s.neg(Qe),bt^=1;return new O(De,Tt,y?void 0:bt)}return{seed:me,k2sig:xe}}function j(A,R,I={}){let{seed:q,k2sig:N}=ee(A,R,I);return yC(t.outputLen,s.BYTES,n)(q,N).toBytes(I.format)}function T(A,R,I,q={}){let{lowS:N,prehash:H,format:G}=$S(q,S);if(I=Re(I,void 0,"publicKey"),R=W(R,H),!za(A)){let re=A instanceof O?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+re)}k(A,G);try{let re=O.fromBytes(A,G),ae=e.fromBytes(I);if(N&&re.hasHighS())return!1;let{r:me,s:Se}=re,xe=P(R),ke=s.inv(Se),Ie=s.create(xe*ke),_e=s.create(me*ke),Ue=e.BASE.multiplyUnsafe(Ie).add(ae.multiplyUnsafe(_e));if(Ue.is0())return!1;return s.create(Ue.x)===me}catch(re){return!1}}function Z(A,R,I={}){let{prehash:q}=$S(I,S);return R=W(R,q),O.fromBytes(A,"recovered").recoverPublicKey(R).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:p,utils:m,lengths:h,Point:e,sign:j,verify:T,recoverPublicKey:Z,Signature:O,hash:t})}var jC=(e,t)=>(e+(e>=0?t:-t)/UC)/t,BC,ci,So,Ba,UC,Df,xH;var FC=b(()=>{TS();Dr();Da();kS();du();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BC=class BC extends Error{constructor(e=""){super(e)}};ci={Err:BC,_tlv:{encode:(e,t)=>{let{Err:r}=ci;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=su(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?su(n.length/2|128):"";return su(e)+i+n+t},decode(e,t){let{Err:r}=ci,o=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let l=n&127;if(!l)throw new r("tlv.decode(long): indefinite length not supported");if(l>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+l);if(u.length!==l)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=l,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=ci;if(e<So)throw new t("integer: negative integers are not allowed");let r=su(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=ci;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return ii(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=ci,n=Re(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=o.decode(2,i),{v:u,l:d}=o.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=ci,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}},So=BigInt(0),Ba=BigInt(1),UC=BigInt(2),Df=BigInt(3),xH=BigInt(4)});function JC(e,t,r){return e&t^~e&r}function KC(e,t,r){return e&t^e&r^t&r}class Lf{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=$f(this.buffer)}update(e){bo(this),Re(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=$f(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){bo(this),Rf(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,wr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=$f(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let l=a/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var vo,Jt;var HC=b(()=>{Dr();vo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Jt=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428])});function EH(e,t=!1){if(t)return{h:Number(e&Zf),l:Number(e>>VC&Zf)};return{h:Number(e>>VC&Zf)|0,l:Number(e&Zf)|0}}function jf(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=EH(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}function Dn(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var Zf,VC,PS=(e,t,r)=>e>>>r,NS=(e,t,r)=>e<<32-r|t>>>r,xs=(e,t,r)=>e>>>r|t<<32-r,_s=(e,t,r)=>e<<32-r|t>>>r,mu=(e,t,r)=>e<<64-r|t>>>r-32,hu=(e,t,r)=>e>>>r-32|t<<64-r,WC=(e,t,r)=>e<<r|t>>>32-r,GC=(e,t,r)=>t<<r|e>>>32-r,QC=(e,t,r)=>t<<r-32|e>>>64-r,YC=(e,t,r)=>e<<r-32|t>>>64-r,XC=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),e1=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,t1=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),r1=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,n1=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),o1=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var DS=b(()=>{Zf=BigInt(4294967295),VC=BigInt(32)});var IH,li,i1,s1,a1,kH,RH,ui,di,c1,l1,Bf,u1;var LS=b(()=>{HC();DS();Dr();IH=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),li=new Uint32Array(64);i1=class i1 extends Lf{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)li[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=li[d-15],m=li[d-2],h=dn(p,7)^dn(p,18)^p>>>3,S=dn(m,17)^dn(m,19)^m>>>10;li[d]=S+li[d-7]+h+li[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:l,H:u}=this;for(let d=0;d<64;d++){let p=dn(s,6)^dn(s,11)^dn(s,25),m=u+p+JC(s,a,l)+IH[d]+li[d]|0,S=(dn(r,2)^dn(r,13)^dn(r,22))+KC(r,o,n)|0;u=l,l=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+S|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,l,u)}roundClean(){wr(li)}destroy(){this.set(0,0,0,0,0,0,0,0),wr(this.buffer)}};s1=class s1 extends i1{A=vo[0]|0;B=vo[1]|0;C=vo[2]|0;D=vo[3]|0;E=vo[4]|0;F=vo[5]|0;G=vo[6]|0;H=vo[7]|0;constructor(){super(32)}};a1=(()=>jf(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e)=>BigInt(e))))(),kH=(()=>a1[0])(),RH=(()=>a1[1])(),ui=new Uint32Array(80),di=new Uint32Array(80);c1=class c1 extends Lf{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:l,El:u,Fh:d,Fl:p,Gh:m,Gl:h,Hh:S,Hl:y}=this;return[e,t,r,o,n,i,s,a,l,u,d,p,m,h,S,y]}set(e,t,r,o,n,i,s,a,l,u,d,p,m,h,S,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=h|0,this.Hh=S|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)ui[_]=e.getUint32(t),di[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let k=ui[_-15]|0,O=di[_-15]|0,L=xs(k,O,1)^xs(k,O,8)^PS(k,O,7),P=_s(k,O,1)^_s(k,O,8)^NS(k,O,7),K=ui[_-2]|0,z=di[_-2]|0,W=xs(K,z,19)^mu(K,z,61)^PS(K,z,6),ee=_s(K,z,19)^hu(K,z,61)^NS(K,z,6),j=t1(P,ee,di[_-7],di[_-16]),T=r1(j,L,W,ui[_-7],ui[_-16]);ui[_]=T|0,di[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:l,Dl:u,Eh:d,El:p,Fh:m,Fl:h,Gh:S,Gl:y,Hh:v,Hl:x}=this;for(let _=0;_<80;_++){let k=xs(d,p,14)^xs(d,p,18)^mu(d,p,41),O=_s(d,p,14)^_s(d,p,18)^hu(d,p,41),L=d&m^~d&S,P=p&h^~p&y,K=n1(x,O,P,RH[_],di[_]),z=o1(K,v,k,L,kH[_],ui[_]),W=K|0,ee=xs(r,o,28)^mu(r,o,34)^mu(r,o,39),j=_s(r,o,28)^hu(r,o,34)^hu(r,o,39),T=r&n^r&s^n&s,Z=o&i^o&a^i&a;v=S|0,x=y|0,S=m|0,y=h|0,m=d|0,h=p|0,{h:d,l:p}=Dn(l|0,u|0,z|0,W|0),l=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let A=XC(W,j,Z);r=e1(A,z,ee,T),o=A|0}({h:r,l:o}=Dn(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=Dn(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=Dn(this.Ch|0,this.Cl|0,s|0,a|0),{h:l,l:u}=Dn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=Dn(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:h}=Dn(this.Fh|0,this.Fl|0,m|0,h|0),{h:S,l:y}=Dn(this.Gh|0,this.Gl|0,S|0,y|0),{h:v,l:x}=Dn(this.Hh|0,this.Hl|0,v|0,x|0),this.set(r,o,n,i,s,a,l,u,d,p,m,h,S,y,v,x)}roundClean(){wr(ui,di)}destroy(){wr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};l1=class l1 extends c1{Ah=Jt[0]|0;Al=Jt[1]|0;Bh=Jt[2]|0;Bl=Jt[3]|0;Ch=Jt[4]|0;Cl=Jt[5]|0;Dh=Jt[6]|0;Dl=Jt[7]|0;Eh=Jt[8]|0;El=Jt[9]|0;Fh=Jt[10]|0;Fl=Jt[11]|0;Gh=Jt[12]|0;Gl=Jt[13]|0;Hh=Jt[14]|0;Hl=Jt[15]|0;constructor(){super(48)}};Bf=Pa(()=>new s1,oi(1)),u1=Pa(()=>new l1,oi(2))});function CH(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=p1,a=e*e%i*e%i,l=Wr(a,d1,i)*a%i,u=Wr(l,TH,i)*e%i,d=Wr(u,OH,i)*u%i,p=Wr(d,t,i)*d%i,m=Wr(p,r,i)*p%i,h=Wr(m,o,i)*m%i,S=Wr(h,n,i)*h%i,y=Wr(S,n,i)*h%i,v=Wr(y,t,i)*d%i;return{pow_p_5_8:Wr(v,d1,i)*e%i,b2:a}}function zH(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var TH,d1,$H,OH,xSe,p1,f1;var m1=b(()=>{du();ZC();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */TH=BigInt(1),d1=BigInt(2),$H=BigInt(3),OH=BigInt(5),xSe=BigInt(8),p1=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");f1=(()=>{let e=p1;return LC({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=CH(t);return lr(Wr(r,$H,e)*o,e)},adjustScalarBytes:zH})})()});var PH,NH,DH,ZS,LH,h1;var g1=b(()=>{LS();FC();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */PH=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),NH=(()=>({p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")}))(),DH=CS(PH),ZS=zS(DH,Bf),LH=CS(NH),h1=zS(LH,u1)});function b1(e,t,r){if(Vr(e),r===void 0)r=new Uint8Array(e.outputLen);return ja(e,r,t)}function S1(e,t,r,o=32){Vr(e),Zt(o,"length");let n=e.outputLen;if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=y1;else Re(r,void 0,"info");let s=new Uint8Array(i*n),a=ja.create(e,t),l=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)jS[0]=d+1,l.update(d===0?y1:u).update(r).update(jS).digestInto(u),s.set(u,n*d),a._cloneInto(l);return a.destroy(),l.destroy(),wr(u,jS),s.slice(0,o)}var jS,y1;var v1=b(()=>{TS();Dr();jS=Uint8Array.of(0),y1=Uint8Array.of()});function JH(e,t=24){let r=new Uint32Array(10);for(let o=24-t;o<24;o++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,l=(s+2)%10,u=r[l],d=r[l+1],p=w1(u,d,1)^r[a],m=x1(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[s+h]^=p,e[s+h+1]^=m}let n=e[2],i=e[3];for(let s=0;s<24;s++){let a=E1[s],l=w1(n,i,a),u=x1(n,i,a),d=_1[s];n=e[d],i=e[d+1],e[d]=l,e[d+1]=u}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=qH[o],e[1]^=FH[o]}wr(r)}class Uf{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,t,r,o=!1,n=24){if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=o,this.rounds=n,Zt(r,"outputLen"),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Tf(this.state)}clone(){return this._cloneInto()}keccak(){mS(this.state32),JH(this.state32,this.rounds),mS(this.state32),this.posOut=0,this.pos=0}update(e){bo(this),Re(e);let{blockLen:t,state:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(t-this.pos,o-n);for(let s=0;s<i;s++)r[this.pos++]^=e[n++];if(this.pos===t)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:o}=this;if(e[r]^=t,(t&128)!==0&&r===o-1)this.keccak();e[o-1]^=128,this.keccak()}writeInto(e){bo(this,!1),Re(e),this.finish();let t=this.state,{blockLen:r}=this;for(let o=0,n=e.length;o<n;){if(this.posOut>=r)this.keccak();let i=Math.min(r-this.posOut,n-o);e.set(t.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Zt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Rf(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,wr(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:o,rounds:n,enableXOF:i}=this;return e||=new Uf(t,r,o,i,n),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}}var ZH,gu,jH,BH,UH,MH,_1,E1,A1,I1,qH,FH,w1=(e,t,r)=>r>32?QC(e,t,r):WC(e,t,r),x1=(e,t,r)=>r>32?YC(e,t,r):GC(e,t,r),k1=(e,t,r,o={})=>Pa(()=>new Uf(t,e,r),o),Es,R1,T1=(e,t,r,o={})=>Pa((n={})=>new Uf(t,e,n.dkLen===void 0?r:n.dkLen,!0),o),$1,Ln;var Mf=b(()=>{DS();Dr();ZH=BigInt(0),gu=BigInt(1),jH=BigInt(2),BH=BigInt(7),UH=BigInt(256),MH=BigInt(113),_1=[],E1=[],A1=[];for(let e=0,t=gu,r=1,o=0;e<24;e++){[r,o]=[o,(2*r+3*o)%5],_1.push(2*(5*o+r)),E1.push((e+1)*(e+2)/2%64);let n=ZH;for(let i=0;i<7;i++)if(t=(t<<gu^(t>>BH)*MH)%UH,t&jH)n^=gu<<(gu<<BigInt(i))-gu;A1.push(n)}I1=jf(A1,!0),qH=I1[0],FH=I1[1];Es=k1(6,136,32,oi(8)),R1=k1(6,72,64,oi(10)),$1=T1(31,168,16,oi(11)),Ln=T1(31,136,32,oi(12))});function BS(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error("wrong u32 integer:"+e);return e}function C1(e){return BS(e),(e&e-1)===0&&e!==0}function US(e,t){BS(e);let r=0;for(let o=0;o<t;o++,e>>>=1)r=r<<1|e&1;return r}function z1(e){return BS(e),31-Math.clz32(e)}function O1(e){let t=e.length;if(t<2||!C1(t))throw Error("n must be a power of 2 and greater than 1. Got "+t);let r=z1(t);for(let o=0;o<t;o++){let n=US(o,r);if(o<n){let i=e[o];e[o]=e[n],e[n]=i}}return e}var MS=(e,t)=>{let{N:r,roots:o,dit:n,invertButterflies:i=!1,skipStages:s=0,brp:a=!0}=t,l=z1(r);if(!C1(r))throw Error("FFT: Polynomial size should be power of two");let u=n!==i;return(d)=>{if(d.length!==r)throw Error("FFT: wrong Polynomial length");if(n&&a)O1(d);for(let p=0,m=1;p<l-s;p++){let h=n?p+1+s:l-p,S=1<<h,y=S>>1,v=r>>h;for(let x=0;x<r;x+=S)for(let _=0,k=m++;_<y;_++){let O=i?n?r-k:k:_*v,L=x+_,P=x+_+y,K=o[O],z=d[P],W=d[L];if(u){let ee=e.mul(z,K);d[L]=e.add(W,ee),d[P]=e.sub(W,ee)}else if(i)d[L]=e.add(z,W),d[P]=e.mul(e.sub(z,W),K);else d[L]=e.add(W,z),d[P]=e.mul(e.sub(W,z),K)}}if(!n&&a)O1(d);return d}};var P1=()=>{};function qf(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function N1(e){return Uint8Array.from(e)}function As(e,...t){let r=(n)=>typeof n==="number"?n:n.bytesLen,o=t.reduce((n,i)=>n+r(i),0);return{bytesLen:o,encode:(n)=>{let i=new Uint8Array(o);for(let s=0,a=0;s<t.length;s++){let l=t[s],u=r(l),d=typeof l==="number"?n[s]:l.encode(n[s]);if(Re(d,u,e),i.set(d,a),typeof l!=="number")d.fill(0);a+=u}return i},decode:(n)=>{Re(n,o,e);let i=[];for(let s of t){let a=r(s),l=n.subarray(0,a);i.push(typeof s==="number"?l:s.decode(l)),n=n.subarray(a)}return i}}}function Ff(e,t){let r=t*e.bytesLen;return{bytesLen:r,encode:(o)=>{if(o.length!==t)throw Error(`vecCoder.encode: wrong length=${o.length}. Expected: ${t}`);let n=new Uint8Array(r);for(let i=0,s=0;i<o.length;i++){let a=e.encode(o[i]);n.set(a,s),a.fill(0),s+=a.length}return n},decode:(o)=>{Re(o,r);let n=[];for(let i=0;i<o.length;i+=e.bytesLen)n.push(e.decode(o.subarray(i,i+e.bytesLen)));return n}}}function Ot(...e){for(let t of e)if(Array.isArray(t))for(let r of t)r.fill(0);else t.fill(0)}function qS(e){return(1<<e)-1}var Zn,LSe;var Jf=b(()=>{Dr();Dr();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */Zn=ni;LSe=Uint8Array.of()});var D1=(e)=>{let{newPoly:t,N:r,Q:o,F:n,ROOT_OF_UNITY:i,brvBits:s,isKyber:a}=e,l=(_,k=o)=>{let O=_%k|0;return(O>=0?O|0:k+O|0)|0},u=(_,k=o)=>{let O=l(_,k)|0;return(O>k>>1?O-k|0:O)|0};function d(){let _=t(r);for(let k=0;k<r;k++){let O=US(k,s),L=BigInt(i)**BigInt(O)%BigInt(o);_[k]=Number(L)|0}return _}let p=d(),m={add:(_,k)=>l((_|0)+(k|0))|0,sub:(_,k)=>l((_|0)-(k|0))|0,mul:(_,k)=>l((_|0)*(k|0))|0,inv:(_)=>{throw Error("not implemented")}},h={N:r,roots:p,invertButterflies:!0,skipStages:a?1:0,brp:!1},S=MS(m,{dit:!1,...h}),y=MS(m,{dit:!0,...h});return{mod:l,smod:u,nttZetas:p,NTT:{encode:(_)=>S(_),decode:(_)=>{y(_);for(let k=0;k<_.length;k++)_[k]=l(n*_[k]);return _}},bitsCoder:(_,k)=>{let O=qS(_),L=_*(r/8);return{bytesLen:L,encode:(P)=>{let K=new Uint8Array(L);for(let z=0,W=0,ee=0,j=0;z<P.length;z++){W|=(k.encode(P[z])&O)<<ee,ee+=_;for(;ee>=8;ee-=8,W>>=8)K[j++]=W&qS(ee)}return K},decode:(P)=>{let K=t(r);for(let z=0,W=0,ee=0,j=0;z<P.length;z++){W|=P[z]<<ee,ee+=8;for(;ee>=_;ee-=_,W>>=_)K[j++]=k.decode(W&O)}return K}}}}},KH=(e)=>(t,r)=>{if(!r)r=e.blockLen;let o=new Uint8Array(t.length+2);o.set(t);let n=t.length,i=new Uint8Array(r),s=e.create({}),a=0,l=0;return{stats:()=>({calls:a,xofs:l}),get:(u,d)=>(o[n+0]=u,o[n+1]=d,s.destroy(),s=e.create({}).update(o),a++,()=>(l++,s.xofInto(i))),clean:()=>{s.destroy(),Ot(i,o)}}},L1;var Z1=b(()=>{P1();Mf();Jf();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */L1=KH($1)});function ks(e,t){for(let r=0;r<er;r++)e[r]=Su(e[r]+t[r])}function YH(e,t){for(let r=0;r<er;r++)e[r]=Su(e[r]-t[r])}function XH(e,t,r,o,n){let i=Su(t*o*n+e*r),s=Su(e*o+t*r);return{c0:i,c1:s}}function Kf(e,t){for(let r=0;r<er/2;r++){let o=WH[64+(r>>1)];if(r&1)o=-o;let{c0:n,c1:i}=XH(e[2*r+0],e[2*r+1],t[2*r+0],t[2*r+1],o);e[2*r+0]=n,e[2*r+1]=i}return e}function j1(e){let t=new Uint16Array(er);for(let r=0;r<er;){let o=e();if(o.length%3)throw Error("SampleNTT: unaligned block");for(let n=0;r<er&&n+3<=o.length;n+=3){let i=(o[n+0]>>0|o[n+1]<<8)&4095,s=(o[n+1]>>4|o[n+2]<<4)&4095;if(i<wo)t[r++]=i;if(r<er&&s<wo)t[r++]=s}}return t}function bu(e,t,r,o){let n=e(o*er/4,t,r),i=new Uint16Array(er),s=Tf(n),a=0;for(let l=0,u=0,d=0,p=0;l<s.length;l++){let m=s[l];for(let h=0;h<32;h++)if(d+=m&1,m>>=1,a+=1,a===o)p=d,d=0;else if(a===2*o)i[u++]=Su(p-d),d=0,a=0}if(a)throw Error(`sampleCBD: leftover bits: ${a}`);return i}function JS(e){let t=eV(e),{HASH256:r,HASH512:o,KDF:n}=e,{secretCoder:i,lengths:s}=t,a=As("secretKey",s.secretKey,s.publicKey,32,32),l=32,u=64;return{info:{type:"ml-kem"},lengths:{...s,seed:64,msg:32,msgRand:32,secretKey:a.bytesLen},keygen:(d=Zn(64))=>{Re(d,64,"seed");let{publicKey:p,secretKey:m}=t.keygen(d.subarray(0,32)),h=r(p),S=a.encode([m,p,h,d.subarray(32)]);return Ot(m,h),{publicKey:p,secretKey:S}},getPublicKey:(d)=>{let[p,m,h,S]=a.decode(d);return Uint8Array.from(m)},encapsulate:(d,p=Zn(32))=>{Re(d,s.publicKey,"publicKey"),Re(p,32,"message");let m=d.subarray(0,384*e.K),h=i.encode(i.decode(N1(m)));if(!qf(h,m))throw Ot(h),Error("ML-KEM.encapsulate: wrong publicKey modulus");Ot(h);let S=o.create().update(p).update(r(d)).digest(),y=t.encrypt(d,p,S.subarray(32,64));return Ot(S.subarray(32)),{cipherText:y,sharedSecret:S.subarray(0,32)}},decapsulate:(d,p)=>{Re(p,a.bytesLen,"secretKey"),Re(d,s.cipherText,"cipherText");let m=a.bytesLen-96,h=m+32,S=r(p.subarray(m/2,h));if(!qf(S,p.subarray(h,h+32)))throw Error("invalid secretKey: hash check failed");let[y,v,x,_]=a.decode(p),k=t.decrypt(d,y),O=o.create().update(k).update(x).digest(),L=O.subarray(0,32),P=t.encrypt(v,k,O.subarray(32,64)),K=qf(d,P),z=n.create({dkLen:32}).update(_).update(d).digest();return Ot(k,P,!K?L:z),K?L:z}}}function tV(e,t,r){return Ln.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}var er=256,wo=3329,HH=3303,VH=17,Su,WH,Is,GH,FS,QH=(e)=>{if(e>=12)return{encode:(r)=>r,decode:(r)=>r};let t=2**(e-1);return{encode:(r)=>((r<<e)+wo/2)/wo,decode:(r)=>r*wo+t>>>e}},yu=(e)=>GH(e,QH(e)),eV=(e)=>{let{K:t,PRF:r,XOF:o,HASH512:n,ETA1:i,ETA2:s,du:a,dv:l}=e,u=yu(1),d=yu(l),p=yu(a),m=As("publicKey",Ff(yu(12),t),32),h=Ff(yu(12),t),S=As("ciphertext",Ff(p,t),d),y=As("seed",32,32);return{secretCoder:h,lengths:{secretKey:h.bytesLen,publicKey:m.bytesLen,cipherText:S.bytesLen},keygen:(v)=>{Re(v,32,"seed");let x=new Uint8Array(33);x.set(v),x[32]=t;let _=n(x),[k,O]=y.decode(_),L=[],P=[];for(let W=0;W<t;W++)L.push(Is.encode(bu(r,O,W,i)));let K=o(k);for(let W=0;W<t;W++){let ee=Is.encode(bu(r,O,t+W,i));for(let j=0;j<t;j++){let T=j1(K.get(j,W));ks(ee,Kf(T,L[j]))}P.push(ee)}K.clean();let z={publicKey:m.encode([P,k]),secretKey:h.encode(L)};return Ot(k,O,L,P,x,_),z},encrypt:(v,x,_)=>{let[k,O]=m.decode(v),L=[];for(let j=0;j<t;j++)L.push(Is.encode(bu(r,_,j,i)));let P=o(O),K=new Uint16Array(er),z=[];for(let j=0;j<t;j++){let T=bu(r,_,t+j,s),Z=new Uint16Array(er);for(let A=0;A<t;A++){let R=j1(P.get(j,A));ks(Z,Kf(R,L[A]))}ks(T,Is.decode(Z)),z.push(T),ks(K,Kf(k[j],L[j])),Ot(Z)}P.clean();let W=bu(r,_,2*t,s);ks(W,Is.decode(K));let ee=u.decode(x);return ks(ee,W),Ot(k,L,K,W),S.encode([z,ee])},decrypt:(v,x)=>{let[_,k]=S.decode(v),O=h.decode(x),L=new Uint16Array(er);for(let P=0;P<t;P++)ks(L,Kf(O[P],Is.encode(_[P])));return YH(k,Is.decode(L)),Ot(L,O,_),u.encode(k)}}},KS,VSe,vu,B1;var U1=b(()=>{Mf();Dr();Z1();Jf();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */({mod:Su,nttZetas:WH,NTT:Is,bitsCoder:GH}=D1({N:er,Q:wo,F:HH,ROOT_OF_UNITY:VH,newPoly:(e)=>new Uint16Array(e),brvBits:7,isKyber:!0})),FS={512:{N:er,Q:wo,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128},768:{N:er,Q:wo,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192},1024:{N:er,Q:wo,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}};KS={HASH256:Es,HASH512:R1,KDF:Ln,XOF:L1,PRF:tV},VSe=JS({...KS,...FS[512]}),vu=JS({...KS,...FS[768]}),B1=JS({...KS,...FS[1024]})});function rV(e,t=!1){let{lengths:r,keygen:o}=e;if(t){let i=e.Point.Fn;if(!i)throw Error("No Point.Fn");o=(s=Zn(r.seed))=>{Re(s,r.seed,"seed");let a=i.isLE?si(s):ii(s),l=i.toBytes(i.create(a));return{secretKey:l,publicKey:e.getPublicKey(l)}}}return{lengths:{secretKey:r.secretKey,publicKey:r.publicKey,seed:r.seed},keygen:o,getPublicKey:(n)=>e.getPublicKey(n)}}function HS(e,t=!1){let r=rV(e,t);if(!e.getSharedSecret)throw Error("wrong curve");return{lengths:{...r.lengths,msg:r.lengths.seed,cipherText:r.lengths.publicKey},keygen:r.keygen,getPublicKey:r.getPublicKey,encapsulate(o,n=Zn(e.lengths.seed)){let i=this.keygen(n).secretKey,s=this.decapsulate(o,i),a=e.getPublicKey(i);return Ot(i),{sharedSecret:s,cipherText:a}},decapsulate(o,n){let i=e.getSharedSecret(n,o);return e.lengths.publicKeyHasPrefix?i.subarray(1):i}}}function wu(e,t){return As(t,...e.map((r)=>{if(typeof r.lengths[t]!=="number")throw Error("wrong length: "+t);return r.lengths[t]}))}function VS(e){return(t,r)=>e(t,{dkLen:r})}function nV(e,t,...r){let o=wu(r,"seed"),n=wu(r,"publicKey");if(e===void 0)e=o.bytesLen;Zt(e);function i(s){Re(s,e);let a=o.decode(t(s,o.bytesLen)),l=r.map((p,m)=>p.keygen(a[m])),u=l.map((p)=>p.secretKey),d=l.map((p)=>p.publicKey);return{secretKey:u,publicKey:d}}return{info:{lengths:{seed:e,publicKey:n.bytesLen,secretKey:e}},getPublicKey(s){return this.keygen(s).publicKey},keygen(s=Zn(e)){let{publicKey:a,secretKey:l}=i(s),u=n.encode(a);return Ot(a),Ot(l),{secretKey:s,publicKey:u}},expandDecapsulationKey:i,realSeedLen:e}}function Hf(e,t,r,o,...n){let i=nV(e,r,...n),s=wu(n,"cipherText"),a=wu(n,"publicKey"),l=wu(n,"msg");if(t===void 0)t=l.bytesLen;return Zt(t),{lengths:{...i.info.lengths,msg:t,msgRand:l.bytesLen,cipherText:s.bytesLen},getPublicKey:i.getPublicKey,keygen:i.keygen,encapsulate(u,d=Zn(l.bytesLen)){let p=a.decode(u),m=l.decode(d),h=n.map((x,_)=>x.encapsulate(p[_],m[_])),S=h.map((x)=>x.sharedSecret),y=h.map((x)=>x.cipherText),v={sharedSecret:o(p,y,S),cipherText:s.encode(y)};return Ot(S,y),v},decapsulate(u,d){let p=s.decode(u),{publicKey:m,secretKey:h}=i.expandDecapsulationKey(d),S=n.map((y,v)=>y.decapsulate(p[v],h[v]));return o(m,p,S)}}}function M1(e,t,r,o,n){return Vr(o),Vr(n),Hf(32,32,VS(o),(i,s,a)=>n(At(a[0],a[1],s[1],i[1],ai(e))),t,r)}function oV(e,t,r,o,n){return Vr(o),Vr(n),Hf(32,32,VS(o),(i,s,a)=>{let l=At(a[0],a[1],s[0],i[0],s[1],i[1],ai(e)),u=32,d=At(ai("hybrid_prk"),l),p=b1(n,d),m=At(Na(32,2),ai("shared_secret"),ai("")),h=S1(n,p,m,32);return Ot(p,m,d,l),h},t,r)}function sV(e,t,r,o){let n=e.Point.Fn;if(!n)throw Error("no Point.Fn");function i(s){let a;for(let d=0,p=t;;d=p,p+=t){if(p>s.length)throw Error("rejection sampling failed");if(a=n.fromBytes(s.subarray(d,p),!0),n.isValidNot0(a))break}let l=n.toBytes(n.create(a)),u=e.getPublicKey(l,!1);return{secretKey:l,publicKey:u}}return{lengths:{secretKey:t,publicKey:r,seed:o,msg:o,cipherText:r},keygen(s=Zn(o)){return Re(s,o,"seed"),i(s)},getPublicKey(s){return e.getPublicKey(s,!1)},encapsulate(s,a=Zn(o)){Re(a,o,"rand");let{secretKey:l}=i(a),u=this.decapsulate(s,l),d=e.getPublicKey(l,!1);return Ot(l),{sharedSecret:u,cipherText:d}},decapsulate(s,a){return e.getSharedSecret(a,s).subarray(1)}}}function aV(e,t,r,o){let{secretKey:n,publicKeyUncompressed:i}=r.lengths;if(!n||!i)throw Error("wrong curve");let s=sV(r,n,i,o),a=64,l=a+o;return Hf(32,32,(u)=>{Re(u,32);let d=Ln(u,{dkLen:l}),p=d.subarray(0,a),m=d.subarray(a,l);return At(p,m)},(u,d,p)=>Es(At(p[0],p[1],d[1],u[1],ai(e))),t,s)}var ive,sve,q1,ave,iV,cV,Vf,F1;var J1=b(()=>{m1();g1();Da();v1();LS();Mf();Dr();U1();Jf();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ive=M1("QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)",vu,HS(ZS,!0),Ln,Es),sve=M1("QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)",B1,HS(h1,!0),Ln,Es);q1=HS(f1),ave=oV("KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)",vu,q1,Ln,Bf),iV=(()=>Hf(32,32,VS(Ln),(e,t,r)=>Es(At(r[0],r[1],t[1],e[1],ai("\\.//^\\"))),vu,q1))();cV=(()=>aV("MLKEM768-P256",vu,ZS,128))(),Vf=iV,F1=cV});function xo(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw TypeError(r+"expected boolean, got type="+typeof e)}return e}function Qf(e){if(typeof e==="bigint"){if(!Wf(e))throw RangeError("positive bigint expected, got "+e)}else GS(e);return e}function jn(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw RangeError(r+"expected safe integer, got "+e)}}function xu(e){let t=Qf(e).toString(16);return t.length&1?"0"+t:t}function K1(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?Gf:BigInt("0x"+e)}function Rs(e){return K1(hf(e))}function pn(e){return K1(hf(pi(Mt(e)).reverse()))}function Yf(e,t){if(St(t),t===0)throw RangeError("zero length");e=Qf(e);let r=e.toString(16);if(r.length>t*2)throw RangeError("number too large");return Wl(r.padStart(t*2,"0"))}function _u(e,t){return Yf(e,t).reverse()}function H1(e,t){if(e=Ye(e),t=Ye(t),e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function pi(e){return Uint8Array.from(Ye(e))}function Xf(e){if(typeof e!=="string")throw TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw RangeError(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}function lV(e,t,r){return Wf(e)&&Wf(t)&&Wf(r)&&t<=e&&e<r}function _o(e,t,r,o){if(!lV(t,r,o))throw RangeError("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function Ja(e){if(e<Gf)throw Error("expected non-negative bigint, got "+e);let t;for(t=0;e>Gf;e>>=WS,t+=1);return t}function V1(e,t,r){if(St(e,"hashLen"),St(t,"qByteLen"),typeof r!=="function")throw TypeError("hmacFn must be a function");let o=(v)=>new Uint8Array(v),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,l=o(e),u=o(e),d=0,p=()=>{l.fill(1),u.fill(0),d=0},m=(...v)=>r(u,Kt(l,...v)),h=(v=n)=>{if(u=m(i,v),l=m(),v.length===0)return;u=m(s,v),l=m()},S=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let v=0,x=[];while(v<t){l=m();let _=l.slice();x.push(_),v+=l.length}return Kt(...x)};return(v,x)=>{p(),h(v);let _=void 0;while((_=x(S()))===void 0)h();return p(),_}}function Gr(e,t={},r={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw TypeError("expected valid options object");function o(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw TypeError(`param "${i}" is invalid: expected own property`);let l=e[i];if(a&&l===void 0)return;let u=typeof l;if(u!==s||l===null)throw TypeError(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,l])=>o(a,l,s));n(t,!1),n(r,!0)}var Ye=(e,t,r)=>Mt(e,t,r),GS,Ua,Kt=(...e)=>Hb(...e),Ma=(e)=>Wl(e),qa,Fa=(e)=>mo(e),Gf,WS,Wf=(e)=>typeof e==="bigint"&&Gf<=e,Eu=(e)=>(WS<<BigInt(e))-WS,QS=()=>{throw Error("not implemented")};var fi=b(()=>{Jr();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */GS=St,Ua=hf,qa=Fb,Gf=BigInt(0),WS=BigInt(1)});function it(e,t){if(t<=Ht)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=Ht?r:t+r}function Qr(e,t,r){if(t<Ht)throw Error("pow2: expected non-negative exponent, got "+t);let o=e;while(t-- >Ht)o*=o,o%=r;return o}function W1(e,t){if(e===Ht)throw Error("invert: expected non-zero number");if(t<=Ht)throw Error("invert: expected positive modulus, got "+t);let r=it(e,t),o=t,n=Ht,i=ht,s=ht,a=Ht;while(r!==Ht){let u=o/r,d=o-r*u,p=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=p,a=m}if(o!==ht)throw Error("invert: does not exist");return it(n,t)}function YS(e,t,r){let o=e;if(!o.eql(o.sqr(t),r))throw Error("Cannot find square root")}function nz(e,t){let r=e,o=(r.ORDER+ht)/X1,n=r.pow(t,o);return YS(r,n,t),n}function pV(e,t){let r=e,o=(r.ORDER-ez)/tz,n=r.mul(t,Ts),i=r.pow(n,o),s=r.mul(t,i),a=r.mul(r.mul(s,Ts),i),l=r.mul(s,r.sub(a,r.ONE));return YS(r,l,t),l}function fV(e){let t=em(e),r=oz(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+uV)/rz;return(a,l)=>{let u=a,d=u.pow(l,s),p=u.mul(d,o),m=u.mul(d,n),h=u.mul(d,i),S=u.eql(u.sqr(p),l),y=u.eql(u.sqr(m),l);d=u.cmov(d,p,S),p=u.cmov(h,m,y);let v=u.eql(u.sqr(p),l),x=u.cmov(d,p,v);return YS(u,x,l),x}}function oz(e){if(e<Y1)throw Error("sqrt is not defined for small field");let t=e-ht,r=0;while(t%Ts===Ht)t/=Ts,r++;let o=Ts,n=em(e);while(G1(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return nz;let i=n.pow(o,t),s=(t+ht)/Ts;return function(l,u){let d=l;if(d.is0(u))return u;if(G1(d,u)!==1)throw Error("Cannot find square root");let p=r,m=d.mul(d.ONE,i),h=d.pow(u,t),S=d.pow(u,s);while(!d.eql(h,d.ONE)){if(d.is0(h))return d.ZERO;let y=1,v=d.sqr(h);while(!d.eql(v,d.ONE))if(y++,v=d.sqr(v),y===p)throw Error("Cannot find square root");let x=ht<<BigInt(p-y-1),_=d.pow(m,x);p=y,m=d.sqr(_),h=d.mul(h,m),S=d.mul(S,_)}return S}}function mV(e){if(e%X1===Y1)return nz;if(e%tz===ez)return pV;if(e%rz===dV)return fV(e);return oz(e)}function XS(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=hV.reduce((o,n)=>(o[n]="function",o),t);if(Gr(e,r),jn(e.BYTES,"BYTES"),jn(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=ht)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function gV(e,t,r){let o=e;if(r<Ht)throw Error("invalid exponent, negatives unsupported");if(r===Ht)return o.ONE;if(r===ht)return t;let n=o.ONE,i=t;while(r>Ht){if(r&ht)n=o.mul(n,i);i=o.sqr(i),r>>=ht}return n}function Au(e,t,r=!1){let o=e,n=Array(t.length).fill(r?o.ZERO:void 0),i=t.reduce((a,l,u)=>{if(o.is0(l))return a;return n[u]=a,o.mul(a,l)},o.ONE),s=o.inv(i);return t.reduceRight((a,l,u)=>{if(o.is0(l))return a;return n[u]=o.mul(a,n[u]),o.mul(a,l)},s),n}function G1(e,t){let r=e,o=(r.ORDER-ht)/Ts,n=r.pow(t,o),i=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),a=r.eql(n,r.neg(r.ONE));if(!i&&!s&&!a)throw Error("invalid Legendre symbol result");return i?1:s?0:-1}function yV(e,t){if(t!==void 0)GS(t);if(e<=Ht)throw Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw Error("invalid n length: expected positive bit length, got "+t);let r=Ja(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected bit length (${r}) >= n.length (${t})`);let o=t!==void 0?t:r,n=Math.ceil(o/8);return{nBitLength:o,nByteLength:n}}class ev{ORDER;BITS;BYTES;isLE;ZERO=Ht;ONE=ht;_lengths;_mod;constructor(e,t={}){if(e<=ht)throw Error("invalid field: expected ORDER > 1, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0});if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=Object.freeze(t.allowedLengths.slice());if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=yV(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,Object.freeze(this)}create(e){return it(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return Ht<=e&&e<this.ORDER}is0(e){return e===Ht}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ht)===ht}neg(e){return it(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return it(e*e,this.ORDER)}add(e,t){return it(e+t,this.ORDER)}sub(e,t){return it(e-t,this.ORDER)}mul(e,t){return it(e*t,this.ORDER)}pow(e,t){return gV(this,e,t)}div(e,t){return it(e*W1(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return W1(e,this.ORDER)}sqrt(e){let t=Q1.get(this);if(!t)Q1.set(this,t=mV(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?_u(e,this.BYTES):Yf(e,this.BYTES)}fromBytes(e,t=!1){Ye(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,n?0:l.length-e.length),e=l}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?pn(e):Rs(e);if(s)a=it(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Au(this,e)}cmov(e,t,r){return xo(r,"condition"),r?t:e}}function em(e,t={}){return new ev(e,t)}function iz(e){if(typeof e!=="bigint")throw Error("field order must be bigint");if(e<=ht)throw Error("field order must be greater than 1");let t=Ja(e-ht);return Math.ceil(t/8)}function tv(e){let t=iz(e);return t+Math.ceil(t/2)}function sz(e,t,r=!1){Ye(e);let o=e.length,n=iz(t),i=Math.max(tv(t),16);if(o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?pn(e):Rs(e),a=it(s,t-ht)+ht;return r?_u(a,n):Yf(a,n)}var Ht,ht,Ts,Y1,X1,ez,uV,tz,dV,rz,Eo=(e,t)=>(it(e,t)&ht)===ht,hV,Q1;var Iu=b(()=>{fi();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ht=BigInt(0),ht=BigInt(1),Ts=BigInt(2),Y1=BigInt(3),X1=BigInt(4),ez=BigInt(5),uV=BigInt(7),tz=BigInt(8),dV=BigInt(9),rz=BigInt(16);hV=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Q1=new WeakMap;Object.freeze(ev.prototype)});function ku(e,t){let r=t.negate();return e?r:t}function Os(e,t){let r=Au(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function uz(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function rv(e,t){uz(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=Eu(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function az(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),l=e>>s;if(a>o)a-=i,l+=$s;let u=t*o,d=u+Math.abs(a)-1,p=a===0,m=a<0,h=t%2!==0;return{nextN:l,offset:d,isZero:p,isNeg:m,isNegF:h,offsetF:u}}function ov(e){return dz.get(e)||1}function cz(e){if(e!==Ka)throw Error("invalid wNAF")}class Ru{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>Ka){if(t&$s)r=r.add(o);o=o.double(),t>>=$s}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=rv(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let l=1;l<o;l++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=rv(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:m}=az(r,s,i);if(r=a,u)n=n.add(ku(p,t[m]));else o=o.add(ku(d,t[l]))}return cz(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=rv(e,this.bits);for(let i=0;i<n.windows;i++){if(r===Ka)break;let{nextN:s,offset:a,isZero:l,isNeg:u}=az(r,i,n);if(r=s,l)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return cz(r),o}getPrecomputes(e,t,r){let o=nv.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);nv.set(t,o)}}return o}cached(e,t,r){let o=ov(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=ov(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){uz(t,this.bits),dz.set(e,t),nv.delete(e)}hasCache(e){return ov(e)!==1}}function pz(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>Ka||o>Ka){if(r&$s)i=i.add(n);if(o&$s)s=s.add(n);n=n.double(),r>>=$s,o>>=$s}return{p1:i,p2:s}}function lz(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return XS(t),t}else return em(e,{isLE:r})}function tm(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let l of["p","n","h"]){let u=t[l];if(!(typeof u==="bigint"&&u>Ka))throw Error(`CURVE.${l} must be positive bigint`)}let n=lz(t.p,r.Fp,o),i=lz(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(t[l]))throw Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function Tu(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}var Ka,$s,nv,dz;var rm=b(()=>{fi();Iu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ka=BigInt(0),$s=BigInt(1);nv=new WeakMap,dz=new WeakMap});function $u(e,t){if(jn(e),jn(t),t<0||t>4)throw Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let o=t-1;o>=0;o--)r[o]=e&255,e>>>=8;return new Uint8Array(r)}function bV(e,t){let r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e[o]^t[o];return r}function SV(e){if(!qa(e)&&typeof e!=="string")throw Error("DST must be Uint8Array or ascii string");let t=typeof e==="string"?Xf(e):e;if(t.length===0)throw Error("DST must be non-empty");return t}function iv(e,t,r,o){if(Ye(e),jn(r),t=SV(t),t.length>255)t=o(Kt(Xf("H2C-OVERSIZE-DST-"),t));let{outputLen:n,blockLen:i}=o,s=Math.ceil(r/n);if(r>65535||s>255)throw Error("expand_message_xmd: invalid lenInBytes");let a=Kt(t,$u(t.length,1)),l=new Uint8Array(i),u=$u(r,2),d=Array(s),p=o(Kt(l,e,u,$u(0,1),a));d[0]=o(Kt(p,$u(1,1),a));for(let h=1;h<s;h++){let S=[bV(p,d[h-1]),$u(h+1,1),a];d[h]=o(Kt(...S))}return Kt(...d).slice(0,r)}var fz="HashToScalar-";var mz=b(()=>{fi()});function vV(e,t,r){_o("scalar",e,Bn,r);let[[o,n],[i,s]]=t,a=hz(s*e,r),l=hz(-n*e,r),u=e-a*o-l*i,d=-a*n-l*s,p=u<Bn,m=d<Bn;if(p)u=-u;if(m)d=-d;let h=Eu(Math.ceil(Ja(r)/2))+mi;if(u<Bn||u>=h||d<Bn||d>=h)throw Error("splitScalar (endomorphism): failed for k");return{k1neg:p,k1:u,k2neg:m,k2:d}}function av(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function sv(e,t){Gr(e);let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(xo(r.lowS,"lowS"),xo(r.prehash,"prehash"),r.format!==void 0)av(r.format);return r}function bz(e,t={}){let r=tm("weierstrass",e,t),o=r.Fp,n=r.Fn,i=r.CURVE,{h:s,n:a}=i;Gr(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:l,allowInfinityPoint:u}=t;if(l){if(!o.is0(i.a)||typeof l.beta!=="bigint"||!Array.isArray(l.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let d=vz(o,n);function p(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function m(j,T,Z){if(u&&T.is0())return Uint8Array.of(0);let{x:A,y:R}=T.toAffine(),I=o.toBytes(A);if(xo(Z,"isCompressed"),Z){p();let q=!o.isOdd(R);return Kt(Sz(q),I)}else return Kt(Uint8Array.of(4),I,o.toBytes(R))}function h(j){Ye(j,void 0,"Point");let{publicKey:T,publicKeyUncompressed:Z}=d,A=j.length,R=j[0],I=j.subarray(1);if(u&&A===1&&R===0)return{x:o.ZERO,y:o.ZERO};if(A===T&&(R===2||R===3)){let q=o.fromBytes(I);if(!o.isValid(q))throw Error("bad point: is not on curve, wrong x");let N=v(q),H;try{H=o.sqrt(N)}catch(ae){let me=ae instanceof Error?": "+ae.message:"";throw Error("bad point: is not on curve, sqrt error"+me)}p();let G=o.isOdd(H);if((R&1)===1!==G)H=o.neg(H);return{x:q,y:H}}else if(A===Z&&R===4){let q=o.BYTES,N=o.fromBytes(I.subarray(0,q)),H=o.fromBytes(I.subarray(q,q*2));if(!x(N,H))throw Error("bad point: is not on curve");return{x:N,y:H}}else throw Error(`bad point: got length ${A}, expected compressed=${T} or uncompressed=${Z}`)}let S=t.toBytes===void 0?m:t.toBytes,y=t.fromBytes===void 0?h:t.fromBytes;function v(j){let T=o.sqr(j),Z=o.mul(T,j);return o.add(o.add(Z,o.mul(j,i.a)),i.b)}function x(j,T){let Z=o.sqr(T),A=v(j);return o.eql(Z,A)}if(!x(i.Gx,i.Gy))throw Error("bad curve params: generator point");let _=o.mul(o.pow(i.a,nm),wV),k=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(_,k)))throw Error("bad curve params: a or b");function O(j,T,Z=!1){if(!o.isValid(T)||Z&&o.is0(T))throw Error(`bad point coordinate ${j}`);return T}function L(j){if(!(j instanceof z))throw Error("Weierstrass Point expected")}function P(j){if(!l||!l.basises)throw Error("no endo");return vV(j,l.basises,n.ORDER)}function K(j,T,Z,A,R){return Z=new z(o.mul(Z.X,j),Z.Y,Z.Z),T=ku(A,T),Z=ku(R,Z),T.add(Z)}class z{static BASE=new z(i.Gx,i.Gy,o.ONE);static ZERO=new z(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(j,T,Z){this.X=O("x",j),this.Y=O("y",T,!0),this.Z=O("z",Z),Object.freeze(this)}static CURVE(){return i}static fromAffine(j){let{x:T,y:Z}=j||{};if(!j||!o.isValid(T)||!o.isValid(Z))throw Error("invalid affine point");if(j instanceof z)throw Error("projective point not allowed");if(o.is0(T)&&o.is0(Z))return z.ZERO;return new z(T,Z,o.ONE)}static fromBytes(j){let T=z.fromAffine(y(Ye(j,void 0,"point")));return T.assertValidity(),T}static fromHex(j){return z.fromBytes(Ma(j))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(j=8,T=!0){if(ee.createCache(this,j),!T)this.multiply(nm);return this}assertValidity(){let j=this;if(j.is0()){if(t.allowInfinityPoint&&o.is0(j.X)&&o.eql(j.Y,o.ONE)&&o.is0(j.Z))return;throw Error("bad point: ZERO")}let{x:T,y:Z}=j.toAffine();if(!o.isValid(T)||!o.isValid(Z))throw Error("bad point: x or y not field elements");if(!x(T,Z))throw Error("bad point: equation left != right");if(!j.isTorsionFree())throw Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:j}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(j)}equals(j){L(j);let{X:T,Y:Z,Z:A}=this,{X:R,Y:I,Z:q}=j,N=o.eql(o.mul(T,q),o.mul(R,A)),H=o.eql(o.mul(Z,q),o.mul(I,A));return N&&H}negate(){return new z(this.X,o.neg(this.Y),this.Z)}double(){let{a:j,b:T}=i,Z=o.mul(T,nm),{X:A,Y:R,Z:I}=this,q=o.ZERO,N=o.ZERO,H=o.ZERO,G=o.mul(A,A),re=o.mul(R,R),ae=o.mul(I,I),me=o.mul(A,R);return me=o.add(me,me),H=o.mul(A,I),H=o.add(H,H),q=o.mul(j,H),N=o.mul(Z,ae),N=o.add(q,N),q=o.sub(re,N),N=o.add(re,N),N=o.mul(q,N),q=o.mul(me,q),H=o.mul(Z,H),ae=o.mul(j,ae),me=o.sub(G,ae),me=o.mul(j,me),me=o.add(me,H),H=o.add(G,G),G=o.add(H,G),G=o.add(G,ae),G=o.mul(G,me),N=o.add(N,G),ae=o.mul(R,I),ae=o.add(ae,ae),G=o.mul(ae,me),q=o.sub(q,G),H=o.mul(ae,re),H=o.add(H,H),H=o.add(H,H),new z(q,N,H)}add(j){L(j);let{X:T,Y:Z,Z:A}=this,{X:R,Y:I,Z:q}=j,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=i.a,ae=o.mul(i.b,nm),me=o.mul(T,R),Se=o.mul(Z,I),xe=o.mul(A,q),ke=o.add(T,Z),Ie=o.add(R,I);ke=o.mul(ke,Ie),Ie=o.add(me,Se),ke=o.sub(ke,Ie),Ie=o.add(T,A);let _e=o.add(R,q);return Ie=o.mul(Ie,_e),_e=o.add(me,xe),Ie=o.sub(Ie,_e),_e=o.add(Z,A),N=o.add(I,q),_e=o.mul(_e,N),N=o.add(Se,xe),_e=o.sub(_e,N),G=o.mul(re,Ie),N=o.mul(ae,xe),G=o.add(N,G),N=o.sub(Se,G),G=o.add(Se,G),H=o.mul(N,G),Se=o.add(me,me),Se=o.add(Se,me),xe=o.mul(re,xe),Ie=o.mul(ae,Ie),Se=o.add(Se,xe),xe=o.sub(me,xe),xe=o.mul(re,xe),Ie=o.add(Ie,xe),me=o.mul(Se,Ie),H=o.add(H,me),me=o.mul(_e,Ie),N=o.mul(ke,N),N=o.sub(N,me),me=o.mul(ke,Se),G=o.mul(_e,G),G=o.add(G,me),new z(N,H,G)}subtract(j){return L(j),this.add(j.negate())}is0(){return this.equals(z.ZERO)}multiply(j){let{endo:T}=t;if(!n.isValidNot0(j))throw RangeError("invalid scalar: out of range");let Z,A,R=(I)=>ee.cached(this,I,(q)=>Os(z,q));if(T){let{k1neg:I,k1:q,k2neg:N,k2:H}=P(j),{p:G,f:re}=R(q),{p:ae,f:me}=R(H);A=re.add(me),Z=K(T.beta,G,ae,I,N)}else{let{p:I,f:q}=R(j);Z=I,A=q}return Os(z,[Z,A])[0]}multiplyUnsafe(j){let{endo:T}=t,Z=this,A=j;if(!n.isValid(A))throw RangeError("invalid scalar: out of range");if(A===Bn||Z.is0())return z.ZERO;if(A===mi)return Z;if(ee.hasCache(this))return this.multiply(A);if(T){let{k1neg:R,k1:I,k2neg:q,k2:N}=P(A),{p1:H,p2:G}=pz(z,Z,I,N);return K(T.beta,H,G,R,q)}else return ee.unsafe(Z,A)}toAffine(j){let T=this,Z=j,{X:A,Y:R,Z:I}=T;if(o.eql(I,o.ONE))return{x:A,y:R};let q=T.is0();if(Z==null)Z=q?o.ONE:o.inv(I);let N=o.mul(A,Z),H=o.mul(R,Z),G=o.mul(I,Z);if(q)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}isTorsionFree(){let{isTorsionFree:j}=t;if(s===mi)return!0;if(j)return j(z,this);return ee.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:j}=t;if(s===mi)return this;if(j)return j(z,this);return this.multiplyUnsafe(s)}isSmallOrder(){if(s===mi)return this.is0();return this.clearCofactor().is0()}toBytes(j=!0){return xo(j,"isCompressed"),this.assertValidity(),S(z,this,j)}toHex(j=!0){return Ua(this.toBytes(j))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let W=n.BITS,ee=new Ru(z,t.endo?Math.ceil(W/2):W);if(W>=8)z.BASE.precompute(8);return Object.freeze(z.prototype),Object.freeze(z),z}function Sz(e){return Uint8Array.of(e?2:3)}function vz(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function xV(e,t={}){let{Fn:r}=e,o=t.randomBytes===void 0?Fa:t.randomBytes,n=Object.assign(vz(e.Fp,r),{seed:Math.max(tv(r.ORDER),16)});function i(h){try{let S=r.fromBytes(h);return r.isValidNot0(S)}catch(S){return!1}}function s(h,S){let{publicKey:y,publicKeyUncompressed:v}=n;try{let x=h.length;if(S===!0&&x!==y)return!1;if(S===!1&&x!==v)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h){return h=h===void 0?o(n.seed):h,sz(Ye(h,n.seed,"seed"),r.ORDER)}function l(h,S=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(S)}function u(h){let{secretKey:S,publicKey:y,publicKeyUncompressed:v}=n,x=r._lengths;if(!qa(h))return;let _=Ye(h,void 0,"key").length,k=_===y||_===v,O=_===S||!!x?.includes(_);if(k&&O)return;return k}function d(h,S,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(S)===!1)throw Error("second arg must be public key");let v=r.fromBytes(h);return e.fromBytes(S).multiply(v).toBytes(y)}let p={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=Tu(a,l);return Object.freeze(p),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:d,keygen:m,Point:e,utils:p,lengths:n})}function wz(e,t,r={}){let o=t;fo(o),Gr(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes===void 0?Fa:r.randomBytes,i=r.hmac===void 0?(R,I)=>zn(o,R,I):r.hmac,{Fp:s,Fn:a}=e,{ORDER:l,BITS:u}=a,{keygen:d,getPublicKey:p,getSharedSecret:m,utils:h,lengths:S}=xV(e,r),y={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},v=l*yz+mi<s.ORDER;function x(R){let I=l>>mi;return R>I}function _(R,I){if(!a.isValidNot0(I))throw Error(`invalid signature ${R}: out of range 1..Point.Fn.ORDER`);return I}function k(){if(v)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(R,I){av(I);let q=S.signature,N=I==="compact"?q:I==="recovered"?q+1:void 0;return Ye(R,N)}class L{r;s;recovery;constructor(R,I,q){if(this.r=_("r",R),this.s=_("s",I),q!=null){if(k(),![0,1,2,3].includes(q))throw Error("invalid recovery id");this.recovery=q}Object.freeze(this)}static fromBytes(R,I=y.format){O(R,I);let q;if(I==="der"){let{r:re,s:ae}=fn.toSig(Ye(R));return new L(re,ae)}if(I==="recovered")q=R[0],I="compact",R=R.subarray(1);let N=S.signature/2,H=R.subarray(0,N),G=R.subarray(N,N*2);return new L(a.fromBytes(H),a.fromBytes(G),q)}static fromHex(R,I){return this.fromBytes(Ma(R),I)}assertRecovery(){let{recovery:R}=this;if(R==null)throw Error("invalid recovery id: must be present");return R}addRecoveryBit(R){return new L(this.r,this.s,R)}recoverPublicKey(R){let{r:I,s:q}=this,N=this.assertRecovery(),H=N===2||N===3?I+l:I;if(!s.isValid(H))throw Error("invalid recovery id: sig.r+curve.n != R.x");let G=s.toBytes(H),re=e.fromBytes(Kt(Sz((N&1)===0),G)),ae=a.inv(H),me=K(Ye(R,void 0,"msgHash")),Se=a.create(-me*ae),xe=a.create(q*ae),ke=e.BASE.multiplyUnsafe(Se).add(re.multiplyUnsafe(xe));if(ke.is0())throw Error("invalid recovery: point at infinify");return ke.assertValidity(),ke}hasHighS(){return x(this.s)}toBytes(R=y.format){if(av(R),R==="der")return Ma(fn.hexFromSig(this));let{r:I,s:q}=this,N=a.toBytes(I),H=a.toBytes(q);if(R==="recovered")return k(),Kt(Uint8Array.of(this.assertRecovery()),N,H);return Kt(N,H)}toHex(R){return Ua(this.toBytes(R))}}Object.freeze(L.prototype),Object.freeze(L);let P=r.bits2int===void 0?function(I){if(I.length>8192)throw Error("input is too large");let q=Rs(I),N=I.length*8-u;return N>0?q>>BigInt(N):q}:r.bits2int,K=r.bits2int_modN===void 0?function(I){return a.create(P(I))}:r.bits2int_modN,z=Eu(u);function W(R){return _o("num < 2^"+u,R,Bn,z),a.toBytes(R)}function ee(R,I){return Ye(R,void 0,"message"),I?Ye(o(R),void 0,"prehashed message"):R}function j(R,I,q){let{lowS:N,prehash:H,extraEntropy:G}=sv(q,y);R=ee(R,H);let re=K(R),ae=a.fromBytes(I);if(!a.isValidNot0(ae))throw Error("invalid private key");let me=[W(ae),W(re)];if(G!=null&&G!==!1){let Ie=G===!0?n(S.secretKey):G;me.push(Ye(Ie,void 0,"extraEntropy"))}let Se=Kt(...me),xe=re;function ke(Ie){let _e=P(Ie);if(!a.isValidNot0(_e))return;let Ue=a.inv(_e),De=e.BASE.multiply(_e).toAffine(),Qe=a.create(De.x);if(Qe===Bn)return;let bt=a.create(Ue*a.create(xe+Qe*ae));if(bt===Bn)return;let Tt=(De.x===Qe?0:2)|Number(De.y&mi),Dt=bt;if(N&&x(bt))Dt=a.neg(bt),Tt^=1;return new L(Qe,Dt,v?void 0:Tt)}return{seed:Se,k2sig:ke}}function T(R,I,q={}){let{seed:N,k2sig:H}=j(R,I,q);return V1(o.outputLen,a.BYTES,i)(N,H).toBytes(q.format)}function Z(R,I,q,N={}){let{lowS:H,prehash:G,format:re}=sv(N,y);if(q=Ye(q,void 0,"publicKey"),I=ee(I,G),!qa(R)){let ae=R instanceof L?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+ae)}O(R,re);try{let ae=L.fromBytes(R,re),me=e.fromBytes(q);if(H&&ae.hasHighS())return!1;let{r:Se,s:xe}=ae,ke=K(I),Ie=a.inv(xe),_e=a.create(ke*Ie),Ue=a.create(Se*Ie),De=e.BASE.multiplyUnsafe(_e).add(me.multiplyUnsafe(Ue));if(De.is0())return!1;return a.create(De.x)===Se}catch(ae){return!1}}function A(R,I,q={}){let{prehash:N}=sv(q,y);return I=ee(I,N),L.fromBytes(R,"recovered").recoverPublicKey(I).toBytes()}return Object.freeze({keygen:d,getPublicKey:p,getSharedSecret:m,utils:h,lengths:S,Point:e,sign:T,verify:Z,recoverPublicKey:A,Signature:L,hash:o})}var hz=(e,t)=>(e+(e>=0?t:-t)/yz)/t,gz,fn,Bn,mi,yz,nm,wV;var xz=b(()=>{Gl();Jr();fi();rm();Iu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */gz=class gz extends Error{constructor(e=""){super(e)}};fn={Err:gz,_tlv:{encode:(e,t)=>{let{Err:r}=fn;if(jn(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(typeof t!=="string")throw TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=xu(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?xu(n.length/2|128):"";return xu(e)+i+n+t},decode(e,t){let{Err:r}=fn;t=Ye(t,void 0,"DER data");let o=0;if(e<0||e>255)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let l=n&127;if(!l)throw new r("tlv.decode(long): indefinite length not supported");if(l>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+l);if(u.length!==l)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=l,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=fn;if(Qf(e),e<Bn)throw new t("integer: negative integers are not allowed");let r=xu(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=fn;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Rs(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=fn,n=Ye(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=o.decode(2,i),{v:u,l:d}=o.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=fn,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}};Object.freeze(fn._tlv);Object.freeze(fn._int);Object.freeze(fn);Bn=BigInt(0),mi=BigInt(1),yz=BigInt(2),nm=BigInt(3),wV=BigInt(4)});var _V,EV,Ha;var _z=b(()=>{Ta();xz();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */_V=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),EV=bz(_V),Ha=wz(EV,vt)});function IV(e,t,r,o){let n=e.sqr(r),i=e.sqr(o),s=e.add(e.mul(t.a,n),i),a=e.add(e.ONE,e.mul(t.d,e.mul(n,i)));return e.eql(s,a)}function Ez(e,t={}){let r=t,o=tm("edwards",e,r,r.FpFnLE),{Fp:n,Fn:i}=o,s=o.CURVE,{h:a}=s;Gr(r,{},{uvRatio:"function"});let l=cv<<BigInt(i.BYTES*8)-xr,u=(y)=>n.create(y),d=r.uvRatio===void 0?(y,v)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,v))}}catch(x){return{isValid:!1,value:hi}}}:r.uvRatio;if(!IV(n,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");function p(y,v,x=!1){let _=x?xr:hi;return _o("coordinate "+y,v,_,l),v}function m(y){if(!(y instanceof h))throw Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,xr,u(s.Gx*s.Gy));static ZERO=new h(hi,xr,xr,hi);static Fp=n;static Fn=i;X;Y;Z;T;constructor(y,v,x,_){this.X=p("x",y),this.Y=p("y",v),this.Z=p("z",x,!0),this.T=p("t",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof h)throw Error("extended point not allowed");let{x:v,y:x}=y||{};return p("x",v),p("y",x),new h(v,x,xr,u(v*x))}static fromBytes(y,v=!1){let x=n.BYTES,{a:_,d:k}=s;y=pi(Ye(y,x,"point")),xo(v,"zip215");let O=pi(y),L=y[x-1];O[x-1]=L&-129;let P=pn(O),K=v?l:n.ORDER;_o("point.y",P,hi,K);let z=u(P*P),W=u(z-xr),ee=u(k*z-_),{isValid:j,value:T}=d(W,ee);if(!j)throw Error("bad point: invalid y coordinate");let Z=(T&xr)===xr,A=(L&128)!==0;if(!v&&T===hi&&A)throw Error("bad point: x=0 and x_0=1");if(A!==Z)T=u(-T);return h.fromAffine({x:T,y:P})}static fromHex(y,v=!1){return h.fromBytes(Ma(y),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,v=!0){if(S.createCache(this,y),!v)this.multiply(cv);return this}assertValidity(){let y=this,{a:v,d:x}=s;if(y.is0())throw Error("bad point: ZERO");let{X:_,Y:k,Z:O,T:L}=y,P=u(_*_),K=u(k*k),z=u(O*O),W=u(z*z),ee=u(P*v),j=u(z*u(ee+K)),T=u(W+u(x*u(P*K)));if(j!==T)throw Error("bad point: equation left != right (1)");let Z=u(_*k),A=u(O*L);if(Z!==A)throw Error("bad point: equation left != right (2)")}equals(y){m(y);let{X:v,Y:x,Z:_}=this,{X:k,Y:O,Z:L}=y,P=u(v*L),K=u(k*_),z=u(x*L),W=u(O*_);return P===K&&z===W}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:y}=s,{X:v,Y:x,Z:_}=this,k=u(v*v),O=u(x*x),L=u(cv*u(_*_)),P=u(y*k),K=v+x,z=u(u(K*K)-k-O),W=P+O,ee=W-L,j=P-O,T=u(z*ee),Z=u(W*j),A=u(z*j),R=u(ee*W);return new h(T,Z,R,A)}add(y){m(y);let{a:v,d:x}=s,{X:_,Y:k,Z:O,T:L}=this,{X:P,Y:K,Z:z,T:W}=y,ee=u(_*P),j=u(k*K),T=u(L*x*W),Z=u(O*z),A=u((_+k)*(P+K)-ee-j),R=Z-T,I=Z+T,q=u(j-v*ee),N=u(A*R),H=u(I*q),G=u(A*q),re=u(R*I);return new h(N,H,re,G)}subtract(y){return m(y),this.add(y.negate())}multiply(y){if(!i.isValidNot0(y))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:x}=S.cached(this,y,(_)=>Os(h,_));return Os(h,[v,x])[0]}multiplyUnsafe(y){if(!i.isValid(y))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(y===hi)return h.ZERO;if(this.is0()||y===xr)return this;return S.unsafe(this,y,(v)=>Os(h,v))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return S.unsafe(this,s.n).is0()}toAffine(y){let v=this,x=y,{X:_,Y:k,Z:O}=v,L=v.is0();if(x==null)x=L?AV:n.inv(O);let P=u(_*x),K=u(k*x),z=n.mul(O,x);if(L)return{x:hi,y:xr};if(z!==xr)throw Error("invZ was invalid");return{x:P,y:K}}clearCofactor(){if(a===xr)return this;return this.multiplyUnsafe(a)}toBytes(){let{x:y,y:v}=this.toAffine(),x=n.toBytes(v);return x[x.length-1]|=y&xr?128:0,x}toHex(){return Ua(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let S=new Ru(h,i.BITS);if(i.BITS>=8)h.BASE.precompute(8);return Object.freeze(h.prototype),Object.freeze(h),h}class lv{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){QS()}static fromHex(e){QS()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Ua(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}}var hi,xr,cv,AV;var Az=b(()=>{fi();rm();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */hi=BigInt(0),xr=BigInt(1),cv=BigInt(2),AV=BigInt(8)});function kV(e){return Gr(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...e})}function Iz(e){let t=kV(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let l=s===void 0?Fa:s,u=a?255:448,d=a?32:56,p=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?om**BigInt(254):om**BigInt(447),S=a?BigInt(8)*om**BigInt(251)-Va:BigInt(4)*om**BigInt(445)-Va,y=h+S+Va,v=(A)=>it(A,r),x=_(p);function _(A){return _u(v(A),d)}function k(A){let R=pi(Ye(A,d,"uCoordinate"));if(a)R[31]&=127;return v(pn(R))}function O(A){return pn(n(pi(Ye(A,d,"scalar"))))}function L(A,R){let I=ee(k(R),O(A));if(I===Ou)throw Error("invalid private or public key received");return _(I)}function P(A){return L(A,x)}let K=P,z=L;function W(A,R,I){let q=v(A*(R-I));return R=v(R-q),I=v(I+q),{x_2:R,x_3:I}}function ee(A,R){_o("u",A,Ou,r),_o("scalar",R,h,y);let I=R,q=A,N=Va,H=Ou,G=A,re=Va,ae=Ou;for(let Se=BigInt(u-1);Se>=Ou;Se--){let xe=I>>Se&Va;ae^=xe,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=xe;let ke=N+H,Ie=v(ke*ke),_e=N-H,Ue=v(_e*_e),De=Ie-Ue,Qe=G+re,bt=G-re,Tt=v(bt*ke),Dt=v(Qe*_e),lt=Tt+Dt,Or=Tt-Dt;G=v(lt*lt),re=v(q*v(Or*Or)),N=v(Ie*Ue),H=v(De*(Ie+v(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let me=i(H);return v(N*me)}let j={secretKey:d,publicKey:d,seed:d},T=(A)=>(A=A===void 0?l(d):A,Ye(A,j.seed,"seed"),A),Z={randomSecretKey:T};return Object.freeze(j),Object.freeze(Z),Object.freeze({keygen:Tu(T,K),getSharedSecret:z,getPublicKey:K,scalarMult:L,scalarMultBase:P,utils:Z,GuBytes:x.slice(),lengths:j})}var Ou,Va,om;var kz=b(()=>{fi();rm();Iu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ou=BigInt(0),Va=BigInt(1),om=BigInt(2)});function Oz(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=zs,a=e*e%i*e%i,l=Qr(a,Rz,i)*a%i,u=Qr(l,Ao,i)*e%i,d=Qr(u,$V,i)*u%i,p=Qr(d,t,i)*d%i,m=Qr(p,r,i)*p%i,h=Qr(m,o,i)*m%i,S=Qr(h,n,i)*h%i,y=Qr(S,n,i)*h%i,v=Qr(y,t,i)*d%i;return{pow_p_5_8:Qr(v,Rz,i)*e%i,b2:a}}function CV(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function mv(e,t){let r=zs,o=it(t*t*t,r),n=it(o*o*t,r),i=Oz(e*n).pow_p_5_8,s=it(e*o*i,r),a=it(t*s*s,r),l=s,u=it(s*uv,r),d=a===e,p=a===it(-e,r),m=a===it(-e*uv,r);if(d)s=l;if(p||m)s=u;if(Eo(s,r))s=it(-s,r);return{isValid:d||p,value:s}}function $z(e){let{d:t}=fv,r=zs,o=(x)=>gi.create(x),n=o(dv*e*e),i=o((n+Ao)*NV),s=BigInt(-1),a=o((s-t*n)*o(n+t)),{isValid:l,value:u}=mv(i,a),d=o(u*e);if(!Eo(d,r))d=o(-d);if(!l)u=d;if(!l)s=n;let p=o(s*(n-Ao)*DV-a),m=u*u,h=o((u+u)*a),S=o(p*zV),y=o(Ao-m),v=o(Ao+m);return new Cs(o(h*v),o(y*S),o(S*v),o(h*y))}var RV,Ao,Rz,TV,$V,OV,zs,fv,uv,Cs,gi,Cz,im,dv,zV,PV,NV,DV,Tz=(e)=>mv(Ao,e),LV,pv=(e)=>gi.create(pn(e)&LV),dr,ZV;var zz=b(()=>{Ta();Jr();Az();mz();Iu();kz();fi();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */RV=BigInt(0),Ao=BigInt(1),Rz=BigInt(2),TV=BigInt(3),$V=BigInt(5),OV=BigInt(8),zs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),fv=(()=>({p:zs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:OV,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();uv=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");Cs=Ez(fv,{uvRatio:mv}),gi=(()=>Cs.Fp)(),Cz=(()=>Cs.Fn)(),im=(()=>{let e=zs;return Iz({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=Oz(t);return it(Qr(r,TV,e)*o,e)},adjustScalarBytes:CV})})(),dv=uv,zV=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),PV=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),NV=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),DV=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),LV=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");dr=class dr extends lv{static BASE=(()=>new dr(Cs.BASE))();static ZERO=(()=>new dr(Cs.ZERO))();static Fp=(()=>gi)();static Fn=(()=>Cz)();constructor(e){super(e)}static fromAffine(e){return new dr(Cs.fromAffine(e))}assertSame(e){if(!(e instanceof dr))throw Error("RistrettoPoint expected")}init(e){return new dr(e)}static fromBytes(e){Mt(e,32);let{a:t,d:r}=fv,o=zs,n=(k)=>gi.create(k),i=pv(e);if(!H1(gi.toBytes(i),e)||Eo(i,o))throw Error("invalid ristretto255 encoding 1");let s=n(i*i),a=n(Ao+t*s),l=n(Ao-t*s),u=n(a*a),d=n(l*l),p=n(t*r*u-d),{isValid:m,value:h}=Tz(n(p*d)),S=n(h*l),y=n(h*S*p),v=n((i+i)*S);if(Eo(v,o))v=n(-v);let x=n(a*y),_=n(v*x);if(!m||Eo(_,o)||x===RV)throw Error("invalid ristretto255 encoding 2");return new dr(new Cs(v,x,Ao,_))}static fromHex(e){return dr.fromBytes(Wl(e))}toBytes(){let{X:e,Y:t,Z:r,T:o}=this.ep,n=zs,i=(y)=>gi.create(y),s=i(i(r+t)*i(r-t)),a=i(e*t),l=i(a*a),{value:u}=Tz(i(s*l)),d=i(u*s),p=i(u*a),m=i(d*p*o),h;if(Eo(o*m,n)){let y=i(t*dv),v=i(e*dv);e=y,t=v,h=i(d*PV)}else h=p;if(Eo(e*m,n))t=i(-t);let S=i((r-t)*h);if(Eo(S,n))S=i(-S);return gi.toBytes(S)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:o,Y:n}=e.ep,i=(l)=>gi.create(l),s=i(t*n)===i(r*o),a=i(r*n)===i(t*o);return s||a}is0(){return this.equals(dr.ZERO)}};Object.freeze(dr.BASE);Object.freeze(dr.ZERO);Object.freeze(dr.prototype);Object.freeze(dr);ZV=Object.freeze({Point:dr,hashToCurve(e,t){let r=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,o=iv(e,r,64,Sf);return ZV.deriveToCurve(o)},hashToScalar(e,t={DST:fz}){let r=iv(e,t.DST,64,Sf);return Cz.create(pn(r))},deriveToCurve(e){Mt(e,64);let t=pv(e.subarray(0,32)),r=$z(t),o=pv(e.subarray(32,64)),n=$z(o);return new dr(r.add(n))}})});async function Nz(e,t){if(jV)return await t();try{return await e()}catch(r){if(r instanceof ReferenceError||r instanceof DOMException&&r.name==="NotSupportedError")return await t();else throw r}}async function sm(e,t){return await Nz(async()=>{let r=hv(e)?e:await UV(e),o=await crypto.subtle.importKey("raw",MV(t),{name:"X25519"},Pz,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:o},r,256))},()=>{if(hv(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return im.scalarMult(e,t)})}async function Cu(e){return await Nz(async()=>sm(e,im.GuBytes),()=>{if(hv(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return im.scalarMultBase(e)})}async function UV(e){if(e.length!==32)throw Error("X25519 private key must be 32 bytes");let t=new Uint8Array([...BV,...e]);return crypto.subtle.importKey("pkcs8",t,{name:"X25519"},Pz,["deriveBits"])}function hv(e){return typeof CryptoKey<"u"&&e instanceof CryptoKey}function MV(e){return e}var Pz=!1,jV=!1,BV;var Dz=b(()=>{zz();BV=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32])});class gv{s;transcript=[];buf=new Uint8Array(0);constructor(e){this.s=e.getReader()}async readLine(){let e=[];while(!0){let t=this.buf.indexOf(10);if(t>=0)return e.push(this.buf.subarray(0,t)),this.transcript.push(this.buf.subarray(0,t+1)),this.buf=this.buf.subarray(t+1),FV(Ps(e));if(this.buf.length>0)e.push(this.buf),this.transcript.push(this.buf);let r=await this.s.read();if(r.done)return this.buf=Ps(e),null;this.buf=r.value}}close(){return this.s.releaseLock(),{rest:this.buf,transcript:Ps(this.transcript)}}}function FV(e){return e.forEach((t)=>{if(t<32||t>126)throw Error("invalid non-ASCII byte in header")}),new TextDecoder().decode(e)}function Ps(e){let t=e.reduce((n,i)=>n+i.length,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}function Wa(e,...t){return e.pipeThrough(new TransformStream({start(r){for(let o of t)r.enqueue(o)}}))}function am(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}async function yv(e){if(!(e instanceof ReadableStream))throw Error("readAll expects a ReadableStream<Uint8Array>");return new Uint8Array(await new Response(e).arrayBuffer())}async function Lz(e){if(!(e instanceof ReadableStream))throw Error("readAllString expects a ReadableStream<Uint8Array>");return await new Response(e).text()}async function Zz(e,t){let r=e.getReader(),o=[],n=0;while(n<t){let{done:l,value:u}=await r.read();if(l)throw Error("stream ended before reading "+t.toString()+" bytes");o.push(u),n+=u.length}r.releaseLock();let i=Ps(o),s=i.subarray(0,t),a=Wa(e,i.subarray(t));return{data:s,rest:a}}var bv=()=>{};class Un{args;body;constructor(e,t){this.args=e,this.body=t}}async function JV(e){let t=await e.readLine();if(t===null)throw Error("invalid stanza");let r=t.split(" ");if(r.length<2||r.shift()!=="->")return{next:t};for(let i of r)if(i.length===0)throw Error("invalid stanza");let o=[];for(;;){let i=await e.readLine();if(i===null)throw Error("invalid stanza");let s=Yt.decode(i);if(s.length>48)throw Error("invalid stanza");if(o.push(s),s.length<48)break}let n=Ps(o);return{s:new Un(r,n)}}async function jz(e){let t=new gv(e),r=await t.readLine();if(r!=="age-encryption.org/v1")throw Error("invalid version "+(r??"line"));let o=[];for(;;){let{s:n,next:i}=await JV(t);if(n!==void 0){o.push(n);continue}if(!i.startsWith("--- "))throw Error("invalid header");let s=Yt.decode(i.slice(4)),{rest:a,transcript:l}=t.close(),u=l.slice(0,l.length-1-i.length+3);return{stanzas:o,headerNoMAC:u,MAC:s,headerSize:l.length,rest:Wa(e,a)}}}function Sv(e){let t=[];t.push(`age-encryption.org/v1
|
|
4
4
|
`);for(let r of e){t.push("-> "+r.args.join(" ")+`
|
|
5
5
|
`);for(let o=0;o<r.body.length;o+=48){let n=o+48;if(n>r.body.length)n=r.body.length;t.push(Yt.encode(r.body.subarray(o,n))+`
|
|
6
6
|
`)}if(r.body.length%48===0)t.push(`
|
|
@@ -114,6 +114,7 @@ env:
|
|
|
114
114
|
- DISCORD_PUBLIC_KEY
|
|
115
115
|
- DISCORD_APPLICATION_ID
|
|
116
116
|
- ATPROTO_APP_PASSWORD
|
|
117
|
+
- RESEND_API_KEY
|
|
117
118
|
- MAIL_TO
|
|
118
119
|
- MAIL_API_KEY
|
|
119
120
|
- MAIL_FROM
|
|
@@ -169,7 +170,7 @@ done
|
|
|
169
170
|
description: Skip the predeploy backup, operator-confirmed, when the running runtime cannot go idle; its last verified backup stands
|
|
170
171
|
required: false
|
|
171
172
|
type: boolean
|
|
172
|
-
default: false`,Bv=" if: ${{ !inputs.skip_predeploy_backup }}";import{appendFileSync as
|
|
173
|
+
default: false`,Bv=" if: ${{ !inputs.skip_predeploy_backup }}";import{appendFileSync as oxe,readFileSync as u9}from"fs";function Uv(e,t){let r=[],o=new Set,n=t?.skipSections??new Set,i=!1,s=!1,a=!1;for(let l of e.split(/\r?\n/)){let u=l.trim();if(d9.test(u)){i=n.has(u),s=!1,a=!1;continue}if(i)continue;if(u.startsWith("#")){if(u.includes("@required"))s=!0;if(u.includes("@sensitive"))a=!0;continue}let d=u.match(/^([A-Z][A-Z0-9_]*)=/);if(!d?.[1]){s=!1,a=!1;continue}let p=d[1];if(!o.has(p))o.add(p),r.push({key:p,required:s,sensitive:a});s=!1,a=!1}return r}function Mv(e,t){return Uv(u9(e,"utf8"),t)}var d9;var nP=b(()=>{d9=/^# ---- .+ ----$/});import{existsSync as p9,readFileSync as f9}from"fs";import{homedir as m9}from"os";import{isAbsolute as h9,join as qv,resolve as g9}from"path";function Lr(e){let t={};for(let r of[qv(e,".env"),qv(e,".env.local")]){if(!p9(r))continue;let o=y9(f9(r,"utf8"));for(let[n,i]of Object.entries(o))t[n]=i}return t}function jt(e,t,r){return t[e]??r[e]}function vi(e,t){if(e.startsWith("~/"))return qv(process.env.HOME??m9(),e.slice(2));if(h9(e))return e;return g9(t,e)}function y9(e){let t={};for(let r of e.split(/\r?\n/)){let o=r.trim();if(o.length===0||o.startsWith("#"))continue;let n=r.match(/^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=\s*(.*)\s*$/),i=n?.[1],s=n?.[2];if(!i||s===void 0)continue;t[i]=b9(s)}return t}function b9(e){if(e.length>=2&&e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.length>=2&&e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1).replace(/\\n/g,`
|
|
173
174
|
`).replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\");return e}var Fv=()=>{};function sP(e,t,r){if(t===r)return!1;return t.includes(_9[e])}function aP(){return fm}function cP(e){if(e.includes('LABEL ai.rizom.brain.watchdog="true"')&&e.includes("http://127.0.0.1:8080/health/live")&&e.includes('ENTRYPOINT ["/usr/bin/tini", "--"]')&&e.includes("BUN_CHROME_PATH=/usr/bin/chromium-headless-shell")&&e.includes('CMD ["bun", "--no-orphans", "./node_modules/@rizom/brain/dist/brain.js", "start"]')){let i=fm.indexOf("# --- fleet:");return e===fm.slice(0,i)+`# --- fleet: install published brain at pinned version (ops deploy) ---
|
|
174
175
|
FROM runtime AS fleet
|
|
175
176
|
ARG BRAIN_VERSION
|
|
@@ -279,7 +280,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
279
280
|
`+w.slice(D,J),D=J+1;M=te}if(se+=`
|
|
280
281
|
`,w.length-D>V&&M>D)se+=w.slice(D,M)+`
|
|
281
282
|
`+w.slice(M+1);else se+=w.slice(D);return se.slice(1)}function On(w){let V="",g=0;for(let E=0;E<w.length;g>=65536?E+=2:E++){g=Qe(w,E);let D=A[g];if(!D&&ke(g)){if(V+=w[E],g>=65536)V+=w[E+1]}else V+=D||N(g)}return V}function Kl(w,V,g){let E="",D=w.tag;for(let J=0,M=g.length;J<M;J+=1){let te=g[J];if(w.replacer)te=w.replacer.call(g,String(J),te);if(U(w,V,te,!1,!1)||typeof te>"u"&&U(w,V,null,!1,!1)){if(E!=="")E+=","+(!w.condenseFlow?" ":"");E+=w.dump}}w.tag=D,w.dump="["+E+"]"}function Qo(w,V,g,E){let D="",J=w.tag;for(let M=0,te=g.length;M<te;M+=1){let se=g[M];if(w.replacer)se=w.replacer.call(g,String(M),se);if(U(w,V+1,se,!0,!0,!1,!0)||typeof se>"u"&&U(w,V+1,null,!0,!0,!1,!0)){if(!E||D!=="")D+=me(w,V);if(w.dump&&a===w.dump.charCodeAt(0))D+="-";else D+="- ";D+=w.dump}}w.tag=J,w.dump=D||"[]"}function Aa(w,V,g){let E="",D=w.tag,J=Object.keys(g);for(let M=0,te=J.length;M<te;M+=1){let se="";if(E!=="")se+=", ";if(w.condenseFlow)se+='"';let be=J[M],fe=g[be];if(w.replacer)fe=w.replacer.call(g,be,fe);if(!U(w,V,be,!1,!1))continue;if(w.dump.length>1024)se+="? ";if(se+=w.dump+(w.condenseFlow?'"':"")+":"+(w.condenseFlow?"":" "),!U(w,V,fe,!1,!1))continue;se+=w.dump,E+=se}w.tag=D,w.dump="{"+E+"}"}function Ia(w,V,g,E){let D="",J=w.tag,M=Object.keys(g);if(w.sortKeys===!0)M.sort();else if(typeof w.sortKeys==="function")M.sort(w.sortKeys);else if(w.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let te=0,se=M.length;te<se;te+=1){let be="";if(!E||D!=="")be+=me(w,V);let fe=M[te],Te=g[fe];if(w.replacer)Te=w.replacer.call(g,fe,Te);if(!U(w,V+1,fe,!0,!0,!0))continue;let Pe=w.tag!==null&&w.tag!=="?"||w.dump&&w.dump.length>1024;if(Pe)if(w.dump&&a===w.dump.charCodeAt(0))be+="?";else be+="? ";if(be+=w.dump,Pe)be+=me(w,V);if(!U(w,V+1,Te,!0,Pe))continue;if(w.dump&&a===w.dump.charCodeAt(0))be+=":";else be+=": ";be+=w.dump,D+=be}w.tag=J,w.dump=D||"{}"}function f(w,V,g){let E=g?w.explicitTypes:w.implicitTypes;for(let D=0,J=E.length;D<J;D+=1){let M=E[D];if((M.instanceOf||M.predicate)&&(!M.instanceOf||typeof V==="object"&&V instanceof M.instanceOf)&&(!M.predicate||M.predicate(V))){if(g)if(M.multi&&M.representName)w.tag=M.representName(V);else w.tag=M.tag;else w.tag="?";if(M.represent){let te=w.styleMap[M.tag]||M.defaultStyle,se;if(o.call(M.represent)==="[object Function]")se=M.represent(V,te);else if(n.call(M.represent,te))se=M.represent[te](V,te);else throw new t("!<"+M.tag+'> tag resolver accepts not "'+te+'" style');w.dump=se}return!0}}return!1}function U(w,V,g,E,D,J,M){if(w.tag=null,w.dump=g,!f(w,g,!1))f(w,g,!0);let te=o.call(w.dump),se=E;if(E)E=w.flowLevel<0||w.flowLevel>V;let be=te==="[object Object]"||te==="[object Array]",fe,Te;if(be)fe=w.duplicates.indexOf(g),Te=fe!==-1;if(w.tag!==null&&w.tag!=="?"||Te||w.indent!==2&&V>0)D=!1;if(Te&&w.usedDuplicates[fe])w.dump="*ref_"+fe;else{if(be&&Te&&!w.usedDuplicates[fe])w.usedDuplicates[fe]=!0;if(te==="[object Object]"){if(E&&Object.keys(w.dump).length!==0){if(Ia(w,V,w.dump,D),Te)w.dump="&ref_"+fe+w.dump}else if(Aa(w,V,w.dump),Te)w.dump="&ref_"+fe+" "+w.dump}else if(te==="[object Array]"){if(E&&w.dump.length!==0){if(w.noArrayIndent&&!M&&V>0)Qo(w,V-1,w.dump,D);else Qo(w,V,w.dump,D);if(Te)w.dump="&ref_"+fe+w.dump}else if(Kl(w,V,w.dump),Te)w.dump="&ref_"+fe+" "+w.dump}else if(te==="[object String]"){if(w.tag!=="?")uo(w,w.dump,V,J,se)}else if(te==="[object Undefined]")return!1;else{if(w.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+te)}if(w.tag!==null&&w.tag!=="?"){let Pe=encodeURI(w.tag[0]==="!"?w.tag.slice(1):w.tag).replace(/!/g,"%21");if(w.tag[0]==="!")Pe="!"+Pe;else if(Pe.slice(0,18)==="tag:yaml.org,2002:")Pe="!!"+Pe.slice(18);else Pe="!<"+Pe+">";w.dump=Pe+" "+w.dump}}return!0}function ne(w,V){let g=[],E=[];ie(w,g,E);let D=E.length;for(let J=0;J<D;J+=1)V.duplicates.push(g[E[J]]);V.usedDuplicates=Array(D)}function ie(w,V,g){if(w!==null&&typeof w==="object"){let E=V.indexOf(w);if(E!==-1){if(g.indexOf(E)===-1)g.push(E)}else if(V.push(w),Array.isArray(w))for(let D=0,J=w.length;D<J;D+=1)ie(w[D],V,g);else{let D=Object.keys(w);for(let J=0,M=D.length;J<M;J+=1)ie(w[D[J]],V,g)}}}function X(w,V){V=V||{};let g=new re(V);if(!g.noRefs)ne(w,g);let E=w;if(g.replacer)E=g.replacer.call({"":E},"",E);if(U(g,0,E,!0,!0))return g.dump+`
|
|
282
|
-
`;return""}return xI.dump=X,xI}function qG(){if(YD)return nr;YD=1;let e=UG(),t=MG();function r(o,n){return function(){throw Error("Function yaml."+o+" is removed in js-yaml 4. Use yaml."+n+" instead, which is now safe by default.")}}return nr.Type=gr(),nr.Schema=XD(),nr.FAILSAFE_SCHEMA=nL(),nr.JSON_SCHEMA=cL(),nr.CORE_SCHEMA=lL(),nr.DEFAULT_SCHEMA=_I(),nr.load=e.load,nr.loadAll=e.loadAll,nr.dump=t.dump,nr.YAMLException=Id(),nr.types={binary:pL(),float:aL(),map:rL(),null:oL(),pairs:mL(),set:hL(),timestamp:uL(),bool:iL(),int:sL(),merge:dL(),omap:fL(),seq:tL(),str:eL()},nr.safeLoad=r("safeLoad","load"),nr.safeLoadAll=r("safeLoadAll","loadAll"),nr.safeDump=r("safeDump","dump"),nr}var nr,Xh,Oi,RD,tI,TD,rI,$D,nI,OD,oI,CD,iI,zD,sI,PD,aI,ND,cI,DD,lI,LD,uI,ZD,dI,jD,pI,BD,fI,UD,mI,MD,hI,qD,gI,FD,yI,JD,bI,KD,SI,HD,vI,VD,wI,WD,GD,xI,QD,YD,FG,gL,Cc,JG,KG,HG,VG,EI,zc,WG,kd,GG,QG,YG,XG,eQ;var Pc=b(()=>{nr={},Xh={},Oi={};xI={};FG=qG(),gL=jG(FG),{Type:Cc,Schema:JG,FAILSAFE_SCHEMA:KG,JSON_SCHEMA:HG,CORE_SCHEMA:VG,DEFAULT_SCHEMA:EI,load:zc,loadAll:WG,dump:kd,YAMLException:GG,types:QG,safeLoad:YG,safeLoadAll:XG,safeDump:eQ}=gL});function Nc(e){return kd(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function yL(e){return zc(e)}function yr(e,t){if(!e.trim())return{ok:!1,error:"file is empty"};let r;try{r=zc(e)}catch(n){return{ok:!1,error:Ve(n,"YAML parse error")}}if(!tQ(r))return{ok:!1,error:"expected a YAML mapping (key: value pairs)"};if(!t)return{ok:!0,data:r};let o=t.safeParse(r);if(!o.success)return{ok:!1,error:`invalid field(s): ${o.error.issues.map((i)=>i.path.map(String).join(".")).join(", ")}`};return{ok:!0,data:o.data}}function tQ(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var Vn=b(()=>{Pc()});var AI,bL;var II=b(()=>{ue();AI=c.object({title:c.string().trim().min(1).max(500).optional(),introduction:c.string().trim().min(1).max(4000).optional(),topics:c.array(c.string().trim().min(1).max(500)).max(20).optional(),topicsHeading:c.string().trim().min(1).max(120).optional(),contactLabel:c.string().trim().min(1).max(80).optional(),contactNote:c.string().trim().min(1).max(240).optional(),mapCaption:c.string().trim().min(1).max(160).optional(),refusal:c.string().trim().min(1).max(500).optional(),faqHeading:c.string().trim().min(1).max(120).optional()}),bL=AI.omit({introduction:!0})});function Ws(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function vL(e){let t=Reflect.get(Vs,"types"),r=Ws(t)?t[e]:void 0;if(!(r instanceof Cc))throw Error(`Required YAML type is unavailable: ${e}`);return r}function oQ(e,t){let r=0,o=1;for(let n of e.split(":").reverse())r+=(t?Number.parseFloat(n):Number.parseInt(n,10))*o,o*=60;return r}function SL(e){let t=vL(e);return new Cc(`tag:yaml.org,2002:${e}`,{kind:"scalar",resolve:(r)=>typeof r==="string"&&(e==="int"?rQ:nQ).test(r)&&!r.endsWith("_"),construct:(r)=>{let o=r.replace(/_/g,""),n=o.startsWith("-")?-1:1,i=o.replace(/^[+-]/,"");if(i.includes(":"))return n*oQ(i,e==="float");if(e==="int"&&i==="0")return 0;if(e==="int"&&/^0[0-7]+$/.test(i))return n*Number.parseInt(i,8);return t.construct(o)},predicate:t.predicate??void 0,represent:t.represent??void 0,defaultStyle:t.defaultStyle??void 0})}var rQ,nQ,kI,iQ,sQ,aQ;var wL=b(()=>{Pc();rQ=/^[+-]?(?:0|0b[01_]*[01]|0x[\da-fA-F_]*[\da-fA-F]|0[0-7_]*[0-7]|[1-9](?:[\d_]*\d)?|[1-9][\d_]*(?::[0-5]?\d)+)$/,nQ=/^(?:[-+]?(?:0|[1-9][\d_]*)(?:\.[\d_]*)?(?:[eE][-+]?\d+)?|\.[\d_]+(?:[eE][-+]?\d+)?|[-+]?\d[\d_]*(?::[0-5]?\d)+\.[\d_]*|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$/;kI=vL("binary"),iQ=new Cc("tag:yaml.org,2002:binary",{kind:"scalar",resolve:(e)=>kI.resolve(e),construct:(e)=>{let t=kI.construct(e);if(!(t instanceof Uint8Array))throw Error("Invalid YAML binary result");return typeof Buffer>"u"?Array.from(t):Buffer.from(t)},predicate:(e)=>typeof Buffer<"u"&&Buffer.isBuffer(e),represent:kI.represent??void 0}),sQ=new Cc("tag:yaml.org,2002:str",{kind:"scalar",resolve:(e)=>typeof e==="string"&&e.includes(":"),construct:(e)=>e}),aQ=EI.extend({implicit:[SL("int"),SL("float"),sQ],explicit:[iQ]})});var xL=b(()=>{Pc();wL()});var _L,EL,AL,cQ;var RI=b(()=>{xL();ue();_L=c.object({audiences:c.array(c.string()).optional(),positioning:c.string().optional()}),EL=c.object({summary:c.string().optional(),traits:c.array(c.string()).optional(),principles:c.array(c.string()).optional(),preferredTerms:c.array(c.string()).optional(),avoid:c.array(c.string()).optional()}),AL=c.object({artDirection:c.string().optional(),palette:c.array(c.string()).optional(),composition:c.string().optional(),mood:c.string().optional(),preferred:c.array(c.string()).optional(),avoid:c.array(c.string()).optional()}),cQ=c.object({name:c.string().describe("Style guide name"),messaging:_L.optional(),voice:EL.optional(),visual:AL.optional()})});var kL=b(()=>{II();RI()});var Dc,MEe,TI="data-ask-sheet",lQ;var $I=b(()=>{ue();Dc=c.object({name:c.string().trim().min(1).max(200),url:c.string().url().optional()}),MEe=c.object({sources:c.array(c.object({id:c.string(),title:c.string(),brain:Dc.optional()}))}),lQ=`body *:not([${TI}], [${TI}] *) { -webkit-backdrop-filter: none !important; backdrop-filter: none !important; }`});import{createHash as uQ}from"crypto";function eg(e){return uQ("sha256").update(e).digest("hex")}var tg=()=>{};var Wn;var Rd=b(()=>{ue();tg();Wn=c.discriminatedUnion("kind",[c.object({kind:c.literal("user"),userId:c.string().min(1),canonicalId:c.string().min(1).optional()}),c.object({kind:c.literal("external"),externalActorId:c.string().min(1)}),c.object({kind:c.literal("agent"),agentId:c.string().min(1)}),c.object({kind:c.literal("service"),serviceId:c.string().min(1)})])});var dQ,GEe,Lc,pQ,fQ,RL,QEe,mQ,hQ,TL;var $L=b(()=>{ue();dQ=c.strictObject({messageCharacters:c.number().int().positive(),requestTimeoutSeconds:c.number().int().positive().max(2147483)}),GEe=c.strictObject({limits:dQ,maxCostMicroUsd:c.number().int().positive()}),Lc=c.number().int().nonnegative(),pQ=c.strictObject({modelCalls:Lc,inputTokens:Lc,cachedInputTokens:Lc,outputTokens:Lc,reasoningTokens:Lc,embeddingTokens:Lc}),fQ=c.discriminatedUnion("state",[c.strictObject({state:c.literal("known"),microUsd:c.number().int().nonnegative(),pricing:c.string().trim().min(1).max(120)}),c.strictObject({state:c.literal("unknown"),reason:c.enum(["missing-usage","unsupported-pricing"])})]),RL=c.strictObject({usage:pQ,cost:fQ}),QEe=c.strictObject({topics:c.array(c.string().trim().min(1).max(500)).max(20),introduction:c.string().trim().min(1).max(4000).optional(),refusal:c.string().trim().min(1).max(500).optional()}),mQ=c.enum(["in-scope","off-topic","abusive","injection","harmful"]),hQ=mQ.exclude(["in-scope"]),TL=c.discriminatedUnion("outcome",[c.strictObject({outcome:c.literal("answered")}),c.strictObject({outcome:c.literal("refused"),category:hQ}),c.strictObject({outcome:c.literal("unscreened")})])});function yQ(e){let t=gQ.safeParse(e);if(!t.success)return e;return{...t.data,cards:t.data.cards.filter((r)=>OI.safeParse(r).success)}}var OL,CL,zL,PL,NL,DL,Zc,LL,ZL,jL,BL,UL,OI,ML,qL,Td,gQ,FL;var jc=b(()=>{ue();$I();$L();OL=c.object({id:c.string(),toolCallId:c.string().optional(),toolName:c.string(),summary:c.string(),completionSummary:c.string().optional(),preview:c.string().optional(),args:c.unknown()}),CL=c.enum(["approval-requested","approval-responded","output-available","output-denied","output-error"]),zL=c.object({kind:c.literal("tool-approval"),id:c.string(),toolCallId:c.string().optional(),toolName:c.string(),input:c.record(c.string(),c.unknown()).optional(),summary:c.string(),completionSummary:c.string().optional(),preview:c.string().optional(),state:CL,output:c.unknown().optional(),error:c.string().optional()}),PL=c.object({entityType:c.string().optional(),entityId:c.string().optional(),attachmentType:c.string().optional()}),NL=c.object({mediaType:c.string().min(1),url:c.string().min(1),downloadUrl:c.string().min(1).optional(),previewUrl:c.string().min(1).optional(),filename:c.string().min(1).optional(),sizeBytes:c.number().nonnegative().optional(),source:PL.optional()}),DL=c.object({kind:c.literal("attachment"),id:c.string(),jobId:c.string().optional(),title:c.string(),description:c.string().optional(),attachment:NL}),Zc=c.object({id:c.string().min(1),title:c.string().min(1).optional(),source:c.string().min(1),url:c.string().min(1).optional(),entityType:c.string().min(1).optional(),entityId:c.string().min(1).optional(),excerpt:c.string().min(1).optional(),provenance:c.record(c.string(),c.unknown()).optional(),brain:Dc.optional()}),LL=c.object({kind:c.literal("sources"),id:c.string().min(1),title:c.string().min(1).optional(),sources:c.array(Zc).min(1)}),ZL=c.object({type:c.literal("prompt"),id:c.string().min(1),label:c.string().min(1),prompt:c.string().min(1),description:c.string().min(1).optional()}),jL=c.object({type:c.literal("event"),id:c.string().min(1),label:c.string().min(1),event:c.string().min(1),fromState:c.string().min(1).optional(),description:c.string().min(1).optional()}),BL=c.discriminatedUnion("type",[ZL,jL]),UL=c.object({kind:c.literal("actions"),id:c.string().min(1),title:c.string().min(1).optional(),defaultOpen:c.boolean().optional(),actions:c.array(BL).min(1)}),OI=c.discriminatedUnion("kind",[zL,DL,LL,UL]),ML=c.object({toolName:c.string(),args:c.record(c.string(),c.unknown()).optional(),jobId:c.string().optional(),data:c.unknown().optional(),error:c.object({message:c.string(),code:c.string().optional()}).optional()}),qL=c.object({faqId:c.string().min(1)}),Td=c.object({text:c.string(),error:c.string().optional(),toolResults:c.array(ML).optional(),cards:c.array(OI).optional(),pendingConfirmations:c.array(OL).optional(),usage:c.object({promptTokens:c.number(),completionTokens:c.number(),totalTokens:c.number()}),guestSettlement:RL.optional(),guestScreening:TL.optional(),askedBefore:qL.optional()}),gQ=c.looseObject({cards:c.array(c.unknown())});FL=c.preprocess((e)=>yQ(Yh(e)),Td)});function he(e){return Object.freeze({name:e.channel,schema:e.request,response:e.response,delivery:e.delivery})}function Gn(e,t){return Object.freeze({name:e,schema:t})}var sAe;var rg=b(()=>{ue();sAe=c.object({name:c.string(),schema:c.custom((e)=>typeof e==="object"&&e!==null&&("safeParse"in e))})});var ng,bQ,SQ,vQ,wQ,JL,xQ,_Q,EQ,AQ,IQ,kQ,KL,HL,VL,RQ,WL,TQ,GL,$Q,QL,OQ;var YL=b(()=>{ue();Rd();jc();rg();ng=c.object({state:c.string(),response:c.string(),sources:c.array(Zc)}),bQ=c.object({agent:c.string().trim().min(1).max(253),question:c.string().trim().min(1).max(4000)}),SQ=he({channel:"a2a:ask:request",request:bQ,response:ng,delivery:"request"}),vQ=c.object({agent:c.string().trim().min(1).max(253),message:c.string().trim().min(1).max(32000)}),wQ=he({channel:"a2a:turn:request",request:vQ,response:ng,delivery:"request"}),JL=c.object({entityType:c.string().optional(),entityId:c.string().optional(),actor:Wn.optional(),interfaceType:c.string().optional(),userPermissionLevel:c.enum(["admin","trusted","public"])}),xQ=c.object({agent:c.string().trim().min(1).max(253),instruction:c.string().trim().min(1).max(2000),selection:c.string().min(1).max(8000),...JL.shape}),_Q=he({channel:"a2a:call:request",request:xQ,response:ng,delivery:"request"}),EQ=c.object({agents:c.array(c.object({id:c.string(),label:c.string()}))}),AQ=he({channel:"a2a:call:agents",request:JL,response:EQ,delivery:"request"}),IQ=c.object({approvedAt:c.string(),approvedBy:c.string().optional()}),kQ=c.discriminatedUnion("op",[c.object({op:c.literal("get"),entityType:c.string().min(1),id:c.string().min(1)}),c.object({op:c.literal("list")})]),KL=c.object({entities:c.array(c.object({entityType:c.string().min(1),id:c.string().min(1),title:c.string()}))}),HL=c.object({signedAt:c.string().min(1),keyId:c.string().min(1),signature:c.string().min(1)}),VL=c.object({entityType:c.string().min(1),id:c.string().min(1),markdown:c.string(),contentHash:c.string().min(1),attestation:HL}),RQ=c.object({agent:c.string().min(1),entityType:c.string().min(1),id:c.string().min(1)}),WL=c.discriminatedUnion("status",[c.object({status:c.literal("found"),entity:VL}),c.object({status:c.literal("not-found")}),c.object({status:c.literal("refused"),code:c.string(),error:c.string()})]),TQ=he({channel:"a2a:shared-entity:get",request:RQ,response:WL,delivery:"request"}),GL=c.discriminatedUnion("status",[c.object({status:c.literal("found"),entities:KL.shape.entities}),c.object({status:c.literal("not-found")}),c.object({status:c.literal("refused"),code:c.string(),error:c.string()})]),$Q=he({channel:"a2a:shared-entity:list",request:c.object({agent:c.string().min(1)}),response:GL,delivery:"request"}),QL=c.object({domain:c.string().min(1),level:c.enum(["trusted","public"])}),OQ=Gn("a2a:peer-trust-changed",QL)});var CQ,XL,zQ,PQ;var eZ=b(()=>{ue();jc();CQ=c.object({type:c.literal("event"),event:c.string().min(1),fromState:c.string().min(1).optional()}),XL=c.object({conversationId:c.string().min(1),interfaceType:c.string().min(1),channelId:c.string().min(1).optional(),channelName:c.string().min(1),userPermissionLevel:c.enum(["admin","trusted","public"]),isAnchor:c.boolean(),action:CQ}),zQ=FL.nullable(),PQ=he({channel:"agent:action:request",request:XL,response:zQ,delivery:"request"})});var tZ,NQ,rZ,DQ;var nZ=b(()=>{ue();jc();tZ=c.object({question:c.string().trim().min(1)}),NQ=c.object({faqId:c.string().min(1),faqQuestion:c.string().min(1),answer:c.string().trim().min(1),sources:c.array(Zc).default([])}),rZ=c.object({hit:NQ.optional()}),DQ=he({channel:"guest:asked-before",request:tZ,response:rZ,delivery:"collect"})});var iZ,oZ,sZ,aZ,LQ,cZ,lZ,uZ,ZQ;var dZ=b(()=>{ue();iZ=c.enum(["studio","drive","file","git"]),oZ=c.enum(["public","shared","restricted"]),sZ=c.object({entityType:c.string().min(1),entityId:c.string().min(1),origin:iZ,actor:c.string().min(1).optional(),base:c.string().min(1).optional(),current:c.string().min(1),text:c.string(),targetVisibility:oZ,declaredVisibility:oZ.optional()}),aZ=c.object({conflictId:c.string().min(1),created:c.boolean()}),LQ=he({channel:"conflict:record",request:sZ,response:aZ,delivery:"request"}),cZ=c.enum(["apply","keep-current"]),lZ=c.object({conflictId:c.string().min(1),action:cZ,userId:c.string().min(1),permissionLevel:c.enum(["admin","trusted","public"])}),uZ=c.object({resolved:c.literal(!0)}),ZQ=he({channel:"conflict:resolve",request:lZ,response:uZ,delivery:"request"})});var jQ,pZ,fZ,kAe,BQ,UQ;var mZ=b(()=>{ue();jQ=c.enum(["admin","trusted","public"]),pZ=c.object({conversationId:c.string().min(1),message:c.string(),interfaceType:c.string().min(1),channelId:c.string().optional(),channelName:c.string().optional(),userPermissionLevel:jQ}),fZ=c.object({id:c.string().min(1),source:c.string().min(1),title:c.string().optional(),content:c.string().min(1),provenance:c.record(c.string(),c.unknown()).optional()}),kAe=c.object({items:c.array(fZ).default([])}),BQ=c.object({items:c.array(c.unknown()).default([]).transform((e)=>e.flatMap((t)=>{let r=fZ.safeParse(t);return r.success?[r.data]:[]}))}),UQ=he({channel:"agent:context:request",request:pZ,response:BQ,delivery:"collect"})});var MQ,qQ;var hZ=b(()=>{ue();MQ=c.strictObject({entityType:c.string().min(1),entityId:c.string().min(1)}),qQ=c.strictObject({startedAt:c.string().datetime(),retrieved:c.array(MQ).max(50)})});var gZ,FQ,yZ,JQ;var bZ=b(()=>{ue();Rd();gZ=c.object({actor:Wn}),FQ=c.object({userId:c.string().min(1),personId:c.string().min(1),canonicalId:c.string().min(1).optional(),displayName:c.string().min(1),permissionLevel:c.enum(["admin","trusted","public"])}),yZ=c.object({principal:FQ.nullable()}),JQ=he({channel:"auth:principal:resolve",request:gZ,response:yZ,delivery:"request"})});var SZ,KQ;var vZ=b(()=>{ue();SZ=c.object({type:c.string().regex(/^[a-z][a-z0-9-]*$/),subjectPrefix:c.string().max(32).default(""),subjectSuffix:c.string().max(255).default("")}),KQ=c.object({clientId:c.string().regex(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/).min(3).max(64),clientSecret:c.string().min(32).max(512),clientName:c.string().trim().min(1).max(200),redirectUris:c.array(c.url()).min(1).max(10),identityClaim:SZ.optional()})});var wZ=()=>{};var xZ=()=>{};var CI,HQ,_Z,VQ,WQ;var EZ=b(()=>{ue();CI=c.strictObject({name:c.string().min(1).optional(),address:c.email()}),HQ=c.strictObject({personId:c.string().min(1).max(200),displayName:c.string().trim().min(1).max(200),permissionLevel:c.enum(["admin","trusted","public"])}),_Z=c.strictObject({messageId:c.string().min(1),sourceRef:c.string().min(1),threadId:c.string().min(1).optional(),from:CI,replyTo:CI.optional(),to:c.array(CI),subject:c.string(),receivedAt:c.iso.datetime(),text:c.string(),html:c.string().min(1).optional(),headers:c.strictObject({listUnsubscribe:c.string().min(1).optional(),autoSubmitted:c.string().min(1).optional(),precedence:c.string().min(1).optional(),inReplyTo:c.string().min(1).optional(),references:c.array(c.string().min(1)).optional()}),sender:HQ.optional()}),VQ=c.strictObject({}),WQ=he({channel:"email:inbound",request:_Z,response:VQ,delivery:"request"})});var GQ,QQ,AZ,zI,YQ,IZ,XQ;var kZ=b(()=>{ue();GQ=c.strictObject({permissionLevel:c.enum(["admin","trusted","public"])}),QQ=c.custom((e)=>typeof AbortSignal<"u"&&e instanceof AbortSignal),AZ=c.strictObject({sourceRef:c.string().regex(/^imap:[a-f0-9]{64}$/),actor:GQ,signal:QQ.optional()}),zI=c.strictObject({name:c.string().trim().min(1).max(300).optional(),address:c.email().max(320)}),YQ=c.strictObject({messageId:c.string().trim().min(1).max(2000),from:zI,replyTo:zI.optional(),to:c.array(zI).max(100),subject:c.string().max(1000),receivedAt:c.iso.datetime(),text:c.string().max(1e5),inReplyTo:c.string().trim().min(1).max(2000).optional(),references:c.array(c.string().trim().min(1).max(2000)).max(100),truncated:c.boolean()}),IZ=c.discriminatedUnion("kind",[c.strictObject({kind:c.literal("available"),message:YQ}),c.strictObject({kind:c.literal("unavailable")})]),XQ=he({channel:"email:source-read",request:AZ,response:IZ,delivery:"request"})});var RZ=b(()=>{tg()});var eY;var TZ=b(()=>{ue();eY=c.object({url:c.string(),authToken:c.string().optional()})});var tY;var $Z=b(()=>{ue();tY=c.object({success:c.boolean(),entityId:c.string().optional(),error:c.string().optional()})});var OZ=()=>{};function og(e,t="handler_failed"){let r=t,o;try{if(e!==null&&typeof e==="object"){let n=$d.safeParse(Reflect.get(e,"code"));if(n.success)r=n.data,o=Od.shape.message.safeParse(Reflect.get(e,"publicMessage")).data;else{let i=Reflect.get(e,"name");if(i==="AbortError")r="cancelled";if(i==="TimeoutError")r="deadline_exceeded"}}}catch{}return new Ci(r,{cause:e,...o!==void 0?{publicMessage:o}:{}})}var $d,zZ=1024,Od,CZ,Ci;var PZ=b(()=>{ue();$d=c.enum(["no_handler","handler_failed","invalid_input","invalid_response","unauthenticated","permission_denied","not_found","conflict","cancelled","deadline_exceeded"]),Od=c.object({code:$d,message:c.string().max(zZ)}),CZ={no_handler:"No handler is available for this capability",handler_failed:"The operation failed",invalid_input:"Invalid input",invalid_response:"Invalid response",unauthenticated:"Authentication required",permission_denied:"Permission denied",not_found:"Not found",conflict:"The operation conflicts with the current state",cancelled:"The operation was cancelled",deadline_exceeded:"The execution deadline was exceeded"};Ci=class Ci extends Error{code;publicMessage;constructor(e,t={}){let r=$d.parse(e),o=Od.shape.message.parse(t.publicMessage??CZ[r]);super(t.message??o,{cause:t.cause});this.name="SdkError",this.code=r,this.publicMessage=o}toJSON(){let e=$d.safeParse(this.code),t=e.data??"handler_failed",r=e.success?Od.shape.message.safeParse(this.publicMessage).data:void 0;return{code:t,message:r??CZ[t]}}}});var ig,sg;var PI=b(()=>{ue();ig=c.lazy(()=>c.union([c.null(),c.boolean(),c.number().finite().refine((e)=>!Number.isInteger(e)||Number.isSafeInteger(e),{message:"integer exceeds the JSON-safe range"}),c.string(),c.array(ig),c.record(c.string(),ig)])),sg=c.record(c.string(),ig)});var rY;var NZ=b(()=>{ue();rY=c.enum(["user","assistant"])});var nY,To;var DZ=b(()=>{ue();nY=c.object({entityType:c.string().min(1),entityId:c.string().min(1),contentHash:c.string().min(1).optional()}),To=c.object({rootJobId:c.string().min(1),causationId:c.string().min(1),projectionId:c.string().min(1).optional(),projectionLineage:c.array(c.string().min(1)),sourceEntity:nY.optional(),derivationDepth:c.number().int().nonnegative()}).superRefine((e,t)=>{if(e.derivationDepth!==e.projectionLineage.length)t.addIssue({code:"custom",path:["derivationDepth"],message:"Derivation depth must equal projection lineage length"});let r=e.projectionLineage.at(-1);if(e.projectionId!==r)t.addIssue({code:"custom",path:["projectionId"],message:"Current projection must equal the final projection lineage entry"})})});var NI=10,LZ=82,DI,oY,iY,sY,aY,cY,lY;var ZZ=b(()=>{ue();DI=c.object({title:c.string().min(1).max(200),lines:c.array(c.string().min(1)).min(1).max(NI),actions:c.array(c.object({label:c.string().min(1).max(80),value:c.string().min(1).max(LZ)})).max(NI)}),oY=DI.extend({channelId:c.string().min(1),interfaceType:c.string().min(1),reactions:c.array(c.object({messageId:c.string().min(1),emoji:c.string().min(1)}))}),iY=c.object({messageId:c.string().min(1)}),sY=c.object({conversationId:c.string().min(1),noticeMessageId:c.string().min(1),value:c.string().min(1),by:c.string().min(1)}),aY=he({channel:"chat:space-notice",request:oY,response:iY,delivery:"request"}),cY=DI.nullable(),lY=he({channel:"chat:space-notice-action",request:sY,response:cY,delivery:"collect"})});var LI,ZI,uY,dY,pY,fY;var jZ=b(()=>{ue();rg();LI={progress:"job-progress"},ZI={completed:"publish:completed",failed:"publish:failed"},uY=c.object({entityType:c.string().min(1),entityId:c.string().min(1),result:c.object({id:c.string(),url:c.string().optional()})}),dY=c.object({entityType:c.string().min(1),entityId:c.string().min(1),error:c.string(),retryCount:c.number(),willRetry:c.boolean()}),pY=Gn(ZI.completed,uY),fY=Gn(ZI.failed,dY)});var jI=()=>{};var yIe;var BZ=b(()=>{ue();jI();yIe=c.object({public:c.boolean(),preview:c.boolean()})});var UZ,MZ,hY;var qZ=b(()=>{ue();UZ=c.object({entityType:c.string().min(1),entityId:c.string(),metadata:c.record(c.string(),c.unknown()).default({}),content:c.string().default("")}),MZ=c.object({relativePath:c.string(),leaf:c.object({start:c.number().int().nonnegative(),end:c.number().int().nonnegative()}).nullable(),owner:c.object({entityType:c.string(),id:c.string()}).optional(),writable:c.boolean().optional()}),hY=he({channel:"sync:path:request",request:UZ,response:MZ,delivery:"request"})});var gY,yY,bY,SY;var FZ=b(()=>{ue();gY=c.strictObject({}),yY=c.object({branch:c.string(),hasChanges:c.boolean(),ahead:c.number(),behind:c.number(),lastCommit:c.string().nullable(),remote:c.string().nullable()}),bY=c.object({syncPath:c.string(),isInitialized:c.boolean(),watchEnabled:c.boolean(),lastSync:c.string().nullable(),totalFiles:c.number(),byEntityType:c.record(c.string(),c.number()),git:yY.nullable(),managementUrl:c.string().optional()}),SY=he({channel:"sync:status:request",request:gY,response:bY,delivery:"request"})});var JZ=()=>{};var KZ,vY,wY;var HZ=b(()=>{ue();KZ=c.strictObject({waveId:c.string().trim().min(1),sourceTypes:c.array(c.string().trim().min(1)),changedTargetTypes:c.array(c.string().trim().min(1))}),vY=c.strictObject({}),wY=he({channel:"projection:wave-ready",request:KZ,response:vY,delivery:"collect"})});var xY,_Y,EY,AY;var VZ=b(()=>{ue();xY=c.strictObject({}),_Y=c.object({entityType:c.string().min(1),entityId:c.string().min(1),previousHash:c.string().min(1),contentHash:c.string().min(1)}),EY=c.object({restated:c.array(_Y)}),AY=he({channel:"stored-content:restate",request:xY,response:EY,delivery:"collect"})});var IY,kY,RY;var WZ=b(()=>{ue();IY=c.strictObject({}),kY=c.string(),RY=he({channel:"plugin:site-builder:head-scripts",request:IY,response:kY,delivery:"collect"})});function BI(e){return typeof e==="function"}var GZ=".site-build-manifest.json",TY,$Y,OY,CY;var QZ=b(()=>{ue();TY=`/${GZ}`,$Y=he({channel:"site:build:requested",request:c.object({reason:c.string().min(1)}),response:c.void(),delivery:"command"});OY=c.object({outputDir:c.string(),environment:c.enum(["preview","production"]),routesBuilt:c.number(),siteConfig:c.object({title:c.string().optional(),description:c.string().optional(),url:c.string().optional(),copyright:c.string().optional(),themeMode:c.enum(["light","dark"]).optional()}),generateEntityUrl:c.custom(BI),renderMarkdown:c.custom(BI),reportFailure:c.custom(BI)}),CY=he({channel:"site:build:staging",request:OY,response:c.void(),delivery:"command"})});var zY,PY,NY;var YZ=b(()=>{ue();zY=c.object({id:c.string().min(1),trigger:c.string().min(1),playbookId:c.string().min(1),once:c.boolean().default(!0),starterText:c.string().min(1),description:c.string().min(1).optional(),starterPrompt:c.string().min(1)}).strict(),PY=c.object({registered:c.boolean(),id:c.string(),ignored:c.boolean().optional(),reason:c.string().optional()}),NY=he({channel:"playbooks:register-lifecycle-starter",request:zY,response:PY,delivery:"request"})});var DY,LY,ZY;var XZ=b(()=>{ue();DY=c.object({id:c.string().min(1),markdown:c.string().min(1)}).strict(),LY=c.object({created:c.boolean()}),ZY=he({channel:"playbooks:seed",request:DY,response:LY,delivery:"request"})});var ej,ag,UI,tj,rj,jY,BY;var nj=b(()=>{ue();ej=["name","headline","industry","location","website","story"],ag=c.enum(ej),UI=c.object({name:c.string().optional(),headline:c.string().optional(),industry:c.string().optional(),location:c.string().optional(),website:c.string().optional(),story:c.string().optional()}),tj=c.enum(["fill","preserve","unchanged"]),rj=c.object({field:ag,current:c.string().nullable(),imported:c.string(),outcome:tj}),jY=he({channel:"@brains/profile:import-preview",request:c.object({fields:UI}),response:c.object({fields:c.array(rj),changed:c.boolean(),revision:c.string()}),delivery:"request"}),BY=he({channel:"@brains/profile:import-apply",request:c.object({fields:UI,revision:c.string()}),response:c.object({filled:c.array(ag),kept:c.array(ag)}),delivery:"request"})});function qY(e){return typeof e==="object"&&e!==null&&"name"in e&&typeof e.name==="string"&&"publish"in e&&typeof e.publish==="function"}var UY,MY,FY,JY,KY,HY,oj,VY;var ij=b(()=>{ue();UY=c.enum(["provider"]),MY=c.object({executionMode:UY.optional(),publishResultIdField:c.string().min(1).optional(),publishTimestampField:c.string().min(1).optional(),enabled:c.boolean().optional()}).strict();FY=c.custom(qY),JY=c.object({entityType:c.string(),provider:FY.optional(),config:MY.optional()}),KY=he({channel:"publish:register",request:JY,response:c.void(),delivery:"command"}),HY=c.union([c.string().min(1),c.object({location:c.enum(["metadata","frontmatter"]),field:c.string().min(1)})]),oj=c.object({entityType:c.string().min(1),attachmentType:c.string().min(1),mediaEntityType:c.enum(["image"]),targetEntityField:HY.optional(),requiredWhen:c.object({status:c.string().min(1).optional(),visibility:c.string().min(1).optional()}).optional(),autoGenerate:c.boolean().optional(),requiredForPublish:c.boolean().optional()}),VY=he({channel:"publish-assets:register",request:oj,response:c.void(),delivery:"command"})});var sj,aj,WY;var cj=b(()=>{ue();sj=c.object({entityType:c.string().min(1),id:c.string().min(1),userId:c.string().min(1),permissionLevel:c.enum(["admin","trusted","public"])}),aj=c.object({published:c.literal(!0),url:c.string().optional()}),WY=he({channel:"publish:request",request:sj,response:aj,delivery:"request"})});var MI,cg=200,lj=1e5,uj,dj,pj,GY,fj,mj,QY;var hj=b(()=>{ue();jc();MI=c.object({userId:c.string().min(1),personId:c.string().min(1),displayName:c.string(),permissionLevel:c.enum(["admin","trusted","public"]),isAnchor:c.boolean(),canonicalId:c.string().min(1).optional()}),uj=c.object({entityType:c.string().min(1),id:c.string().min(1),title:c.string(),content:c.string().max(lj)}),dj=c.object({asker:MI,interfaceType:c.string().min(1),channelName:c.string().min(1),question:c.string().min(1).max(8000),conversationId:c.string().min(1).max(cg).optional(),entry:uj.optional()}),pj=c.object({conversationId:c.string().min(1),response:Td}),GY=he({channel:"agent:ask",request:dj,response:pj,delivery:"request"}),fj=c.object({asker:MI,interfaceType:c.string().min(1),channelName:c.string().min(1),conversationId:c.string().min(1).max(cg),approvalId:c.string().min(1).max(cg),confirmed:c.boolean()}),mj=c.object({response:Td}),QY=he({channel:"agent:ask-confirm",request:fj,response:mj,delivery:"request"})});var YY,XY,eX,tX,rX,nX;var gj=b(()=>{ue();YY=c.object({entityType:c.string()}),XY=he({channel:"generate:execute",request:YY,response:c.void(),delivery:"command"}),eX=c.object({entityType:c.string(),entityId:c.string()}),tX=he({channel:"generate:report:success",request:eX,response:c.void(),delivery:"command"}),rX=c.object({entityType:c.string(),error:c.string()}),nX=he({channel:"generate:report:failure",request:rX,response:c.void(),delivery:"command"})});var yj=()=>{};var bj,Sj,vj,oX;var wj=b(()=>{ue();Rd();bj=c.record(c.string(),c.unknown()),Sj=c.object({entityType:c.string().min(1),source:c.object({entityType:c.string().min(1),entityIds:c.array(c.string().min(1)).min(1).max(51)}),prompt:c.string().trim().min(1).max(2000).optional(),approval:bj.optional(),actor:Wn,interfaceType:c.string().min(1),userPermissionLevel:c.enum(["admin","trusted","public"])}),vj=c.discriminatedUnion("status",[c.object({status:c.literal("confirm"),summary:c.string(),completionSummary:c.string().optional(),preview:c.string(),approval:bj}),c.object({status:c.literal("queued"),entityId:c.string(),jobId:c.string().optional()}),c.object({status:c.literal("refused"),error:c.string(),code:c.string().optional()})]),oX=he({channel:"generate:from-sources",request:Sj,response:vj,delivery:"request"})});var iX,xj,_j,Ej;var Aj=b(()=>{ue();iX=c.object({message:c.string().describe("Natural language response to the query"),summary:c.string().optional().describe("Brief summary if applicable"),topics:c.array(c.string()).optional().describe("Related topics mentioned"),sources:c.array(c.object({id:c.string(),type:c.string(),excerpt:c.string().optional(),relevance:c.number().min(0).max(1).optional()})).optional().describe("Source entities used to answer the query"),metadata:c.record(c.string(),c.unknown()).optional()}).describe("defaultQueryResponse"),xj=c.object({message:c.string()}).describe("simpleTextResponse"),_j=c.object({success:c.boolean(),entityId:c.string().optional(),message:c.string()}).describe("createEntityResponse"),Ej=c.object({success:c.boolean(),entityId:c.string(),changes:c.array(c.string()).optional(),message:c.string()}).describe("updateEntityResponse")});var Ij,kj,sX,Rj,Tj,aX;var $j=b(()=>{ue();Ij=c.discriminatedUnion("type",[c.strictObject({type:c.literal("email"),address:c.email()}),c.strictObject({type:c.literal("matrix"),address:c.string().regex(/^@[a-z0-9._=/+-]+:[A-Za-z0-9.-]+(:[0-9]+)?$/)})]),kj=c.strictObject({recipient:Ij.optional(),title:c.string().min(1),body:c.string().min(1),html:c.string().min(1).optional(),sensitivity:c.enum(["normal","secret"]).default("normal"),idempotencyKey:c.string().trim().min(1).max(200).optional(),replyTo:c.email().optional()}),sX=c.enum(["recipient-missing","transport-missing","delivery-failed"]),Rj=c.string().regex(/^[a-z0-9_:.-]{1,80}$/u),Tj=c.discriminatedUnion("status",[c.strictObject({status:c.literal("sent"),deliveryId:c.string().optional()}),c.strictObject({status:c.literal("failed"),failure:sX,transportCode:Rj.optional()})]),aX=he({channel:"notifications:send",request:kj,response:Tj,delivery:"request"})});var cX,Oj,lX;var Cj=b(()=>{ue();cX=c.strictObject({}),Oj=c.strictObject({titles:c.array(c.string().trim().min(1).max(500)).max(20)}),lX=he({channel:"topics:public-titles",request:cX,response:Oj,delivery:"request"})});var uX,qI,dX,pX,fX,mX,hX,gX;var zj=b(()=>{ue();uX=c.strictObject({}),qI=c.string().trim().min(1).max(100),dX=c.strictObject({types:c.array(qI).max(20)}),pX=he({channel:"collections:types",request:uX,response:dX,delivery:"collect"}),fX=c.strictObject({entityType:qI,ids:c.array(c.string().min(1).max(500)).min(1).max(200),visibilityScope:c.enum(["public","shared","restricted"])}),mX=c.strictObject({entityType:qI,id:c.string().min(1).max(500)}),hX=c.strictObject({collections:c.array(c.strictObject({id:c.string().min(1).max(500),members:c.array(mX).max(1000)})).max(200)}),gX=he({channel:"collections:members",request:fX,response:hX,delivery:"collect"})});var yX,bX,SX,vX,wX;var Pj=b(()=>{ue();yX=c.string().trim().regex(/^[a-z][a-z0-9-]*$/).max(100),bX=c.strictObject({entityType:yX,entityId:c.string().min(1).max(300),visibilityScope:c.enum(["public","shared","restricted"])}),SX=c.strictObject({name:c.string().min(1).max(100),label:c.string().min(1).max(100)}),vX=c.strictObject({title:c.string().max(500),typeLabel:c.string().min(1).max(100),markdown:c.string(),fields:c.array(SX).max(40)}).nullable(),wX=he({channel:"studio:entry-context",request:bX,response:vX,delivery:"request"})});var xX,_X,EX;var Nj=b(()=>{ue();xX=c.strictObject({}),_X=c.strictObject({types:c.array(c.string().trim().min(1))}),EX=he({channel:"topics:source-types",request:xX,response:_X,delivery:"request"})});var Dj,Lj,AX;var Zj=b(()=>{ue();Dj=c.strictObject({id:c.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/),title:c.string().trim().min(1).max(200),body:c.string().trim().min(1).max(20000)}),Lj=c.strictObject({noteId:c.string(),created:c.boolean()}),AX=he({channel:"note:capture",request:Dj,response:Lj,delivery:"request"})});var Bc,Cd,IX,kX,RX,TX,$X,OX;var jj=b(()=>{ue();PI();Bc=c.string().regex(/^[a-z][a-z0-9-]{0,63}$/),Cd=c.string().min(32).max(512),IX=c.strictObject({provider:Bc,brainState:Cd}),kX=c.strictObject({authorizationUrl:c.url({protocol:/^https?$/})}),RX=c.strictObject({provider:Bc,grant:Cd}),TX=c.strictObject({provider:Bc,credential:sg}),$X=c.enum(["provider_denied","authorization_incomplete","credential_exchange_failed"]),OX=c.union([c.strictObject({provider:Bc,state:Cd,grant:Cd}),c.strictObject({provider:Bc,state:Cd,error:$X})])});var CX,zX,PX,NX;var Bj=b(()=>{ue();CX=c.object({permissionLevel:c.enum(["public","trusted","admin"])}),zX=c.object({id:c.string().min(1),title:c.string().min(1),sub:c.string().optional(),href:c.string().min(1),primary:c.boolean().optional(),keywords:c.array(c.string()).optional()}),PX=c.array(zX),NX=he({channel:"console:jump-destinations",request:CX,response:PX,delivery:"collect"})});var lg,FI,qke;var Uj=b(()=>{ue();lg=c.enum(["github","instagram","linkedin","podcast","email","website"]),FI=c.object({platform:lg.describe("Social media platform"),url:c.string().describe("Profile or contact URL"),label:c.string().optional().describe("Optional display label")}),qke=c.email()});function zi(e){if(!e.type.includes(":"))throw Error(`Job contract type "${e.type}" must name its owner, as "owner:job"`);return Object.freeze({type:e.type,input:e.input})}var Mj,qj,Fj,DX,LX,Jj,ZX;var Kj=b(()=>{ue();Mj=c.enum(["1:1","16:9","9:16","4:3","3:4"]),qj=c.object({prompt:c.string(),title:c.string().optional(),aspectRatio:Mj.optional(),targetEntityType:c.string().optional(),targetEntityId:c.string().optional(),entityTitle:c.string().optional(),entityContent:c.string().optional()}),Fj=c.object({imageId:c.string().min(1)}),DX=zi({type:"image:image-describe",input:Fj}),LX=zi({type:"image:image-generate",input:qj}),Jj=c.object({sourceEntityType:c.string().min(1),sourceEntityId:c.string().min(1),attachmentType:c.string().min(1),imageId:c.string().min(1),dedupKey:c.string().min(1).optional(),replace:c.boolean().optional(),targetEntityType:c.string().min(1).optional(),targetEntityId:c.string().min(1).optional(),targetImageField:c.enum(["coverImageId","ogImageId"]).optional()}),ZX=zi({type:"image:image-render-source",input:Jj})});var Hj,jX,Vj,BX;var Wj=b(()=>{ue();Hj=c.object({sourceEntityType:c.string().min(1),sourceEntityId:c.string().min(1),attachmentType:c.string().min(1),documentId:c.string().min(1),title:c.string().min(1).optional(),filename:c.string().min(1).optional(),visibility:c.enum(["public","shared","restricted"]).optional()}),jX=zi({type:"document:generate",input:Hj}),Vj=c.object({documentId:c.string().min(1)}),BX=zi({type:"document:describe",input:Vj})});var UX;var Gj=b(()=>{ue();UX=c.enum(["none","low","medium","high","xhigh","max"])});var MX,Qj,qX;var Yj=b(()=>{ue();MX=c.object({}),Qj=c.object({userId:c.string().min(1),password:c.string().min(1)}),qX=he({channel:"matrix:bot-credentials",request:MX,response:Qj,delivery:"request"})});var JI;var Xj=b(()=>{JI=["core","media","automation","web","chat","site","publishing","federation","matrix","team"]});var iRe;var eB=b(()=>{ue();iRe=c.object({series:c.array(c.string()).optional(),publishedAt:c.string().optional()})});var wt=b(()=>{II();kL();$I();YL();eZ();jc();nZ();dZ();mZ();hZ();Rd();bZ();vZ();wZ();xZ();EZ();kZ();RZ();TZ();$Z();OZ();PZ();PI();NZ();DZ();ZZ();jZ();rg();BZ();jI();qZ();FZ();JZ();HZ();VZ();RI();WZ();QZ();YZ();XZ();nj();ij();cj();hj();gj();yj();wj();Aj();$j();Cj();zj();Pj();Nj();Zj();jj();Bj();Uj();Kj();Wj();Gj();Yj();Xj();eB()});var HX,VX,Ct,br,Gs,WX,Qs="capability-bundles-v1",KI,GX,QX,YX,XX,tB,ug,Ys,hn,eee,tee,ree,nee,oee,HI,iee,see,dg;var $o=b(()=>{wt();wt();ue();HX=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,VX=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Ct=c.string().regex(HX,"expected exact pinned version"),br=c.string().regex(VX,"expected lowercase handle slug"),Gs=c.string().min(1),WX=c.string().startsWith("age1").min(1),KI=c.enum(JI),GX=["professional","team","organization"],QX=c.enum(GX),YX=["person","team","organization"],XX=c.enum(YX),tB=c.array(KI).min(1),ug=c.array(c.string().min(1)),Ys=c.strictObject({brainVersion:Ct,bundleContract:c.literal(Qs),bundles:tB,add:ug.optional(),remove:ug.optional(),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),openaiApiKey:Gs,gitSyncToken:Gs,contentRepoAdminToken:Gs,agePublicKey:WX}).superRefine((e,t)=>{if(new Set(e.bundles).size!==e.bundles.length)t.addIssue({code:c.ZodIssueCode.custom,path:["bundles"],message:"canonical bundles must be unique"})}),hn=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),bundlesOverride:tB.optional(),addOverride:ug.optional(),removeOverride:ug.optional(),openaiApiKeyOverride:Gs.optional(),gitSyncTokenOverride:Gs.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:c.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"});if(e.bundlesOverride&&new Set(e.bundlesOverride).size!==e.bundlesOverride.length)t.addIssue({code:c.ZodIssueCode.custom,path:["bundlesOverride"],message:"canonical bundle overrides must be unique"})}),eee=c.strictObject({platform:lg,url:c.string().min(1),label:c.string().min(1).optional()}),tee=c.strictObject({name:c.string().min(1).optional(),description:c.string().min(1).optional(),website:c.string().min(1).optional(),email:c.string().min(1).optional(),story:c.string().min(1).optional(),socialLinks:c.array(eee).optional()}),ree=c.strictObject({delivery:c.literal("email"),email:c.string().email()}),nee=c.strictObject({enabled:c.boolean().optional(),endpoint:c.string().url().refine((e)=>new URL(e).protocol==="wss:",{message:"Jetstream endpoint must use wss"}).optional(),replayWindowSeconds:c.number().int().min(60).optional(),denyDids:c.array(c.string().startsWith("did:plc:")).optional(),denyDomains:c.array(c.string().min(1)).optional(),skillKeywords:c.array(c.string().min(1)).optional(),queueLimit:c.number().int().min(1).max(1e4).optional(),concurrency:c.number().int().min(1).max(32).optional(),perDidCooldownSeconds:c.number().int().nonnegative().optional(),fetchBudgetPerMinute:c.number().int().min(1).optional(),newAgentsPerHour:c.number().int().min(1).optional(),pendingCandidateCeiling:c.number().int().min(1).optional(),staleCandidateRetentionDays:c.number().int().min(1).optional(),requestTimeoutMs:c.number().int().min(100).optional(),maxResponseBytes:c.number().int().min(1024).optional(),maxRedirects:c.number().int().nonnegative().optional(),retryAttempts:c.number().int().min(1).optional(),heartbeatIntervalHours:c.number().min(1).optional()}),oee=c.strictObject({identifier:c.string().min(1),accountDid:c.string().min(1).optional(),lexiconAuthority:c.boolean().optional(),jetstream:nee.optional()}),HI=c.strictObject({package:c.string().min(1),version:Ct.optional(),theme:c.string().min(1).optional(),themeVersion:Ct.optional()}).superRefine((e,t)=>{let r=e.package.startsWith("@rizom/");if(r&&e.version===void 0)t.addIssue({code:c.ZodIssueCode.custom,path:["version"],message:"external @rizom site packages require an exact version pin"});if(!r&&e.version!==void 0)t.addIssue({code:c.ZodIssueCode.custom,path:["version"],message:"version is valid only for external @rizom site packages"});let o=e.theme?.startsWith("@rizom/")===!0;if(o&&e.themeVersion===void 0)t.addIssue({code:c.ZodIssueCode.custom,path:["themeVersion"],message:"external @rizom themes require an exact version pin"});if(!o&&e.themeVersion!==void 0)t.addIssue({code:c.ZodIssueCode.custom,path:["themeVersion"],message:"themeVersion is valid only for external @rizom themes"})}),iee=c.strictObject({onboarding:c.boolean().optional()}),see=c.record(c.string().min(1),c.record(c.string(),c.unknown())),dg=c.strictObject({handle:br,discord:c.strictObject({enabled:c.boolean(),anchorUserId:c.string().min(1).optional()}),openaiApiKeyOverride:Gs.optional(),gitSyncTokenOverride:Gs.optional(),domainOverride:c.string().min(1).optional(),cloudflareZoneId:c.string().min(1).optional(),contentRepoOverride:c.string().min(1).optional(),profileKind:QX.optional(),anchorKind:XX.optional(),plugins:see.optional(),spaces:c.array(c.string().min(1)).optional(),embeddingEnabled:c.boolean().optional(),embeddingModel:c.string().optional(),topicExtractionEnabled:c.boolean().optional(),skillDerivationEnabled:c.boolean().optional(),swotDerivationEnabled:c.boolean().optional(),addOverride:c.array(c.string().min(1)).optional(),removeOverride:c.array(c.string().min(1)).optional(),siteOverride:HI.optional(),setup:ree.optional(),atproto:oee.optional(),playbooks:iee.optional(),anchorProfile:tee.optional()})});import{access as aee}from"fs/promises";async function Ir(e){try{return await aee(e),!0}catch{return!1}}function Uc(e){return e.replaceAll("\\","/")}var Xs=()=>{};import{readdir as cee,readFile as lee}from"fs/promises";import{basename as VI,join as zd,relative as uee}from"path";async function xt(e,t={}){let[r,o,n]=await Promise.all([WI(zd(e,"pilot.yaml"),Ys),pee(e),fee(e)]),i=mee(o,n),s=n.map((l)=>({id:l.id,members:[...l.data.members].sort(),...Oc({brainVersionOverride:l.data.brainVersionOverride,bundlesOverride:l.data.bundlesOverride,addOverride:l.data.addOverride,removeOverride:l.data.removeOverride,openaiApiKeyOverride:l.data.openaiApiKeyOverride,gitSyncTokenOverride:l.data.gitSyncTokenOverride})})).sort((l,u)=>l.id.localeCompare(u.id)),a=await Promise.all(o.map(async(l)=>{let u=i.get(l.data.handle);if(!u)throw new ea(`User ${l.data.handle} must belong to exactly one cohort`);let d={...dee(l.data,u,r),snapshotStatus:await yee(e,l.data.handle)},p=await t.resolveStatus?.(d);return{...d,serverStatus:p?.serverStatus??"unknown",deployStatus:p?.deployStatus??"unknown",dnsStatus:p?.dnsStatus??"unknown",mcpStatus:p?.mcpStatus??"unknown"}}));return a.sort((l,u)=>l.handle.localeCompare(u.handle)),{pilot:r,cohorts:s,users:a}}function dee(e,t,r){let o=t.data.bundlesOverride===void 0;return{handle:e.handle,cohort:t.id,brainVersion:t.data.brainVersionOverride??r.brainVersion,bundleContract:r.bundleContract,bundles:[...t.data.bundlesOverride??r.bundles],add:rB(t.data.addOverride??(o?r.add:void 0),e.addOverride),remove:rB(t.data.removeOverride??(o?r.remove:void 0),e.removeOverride),domain:e.domainOverride??`${e.handle}${r.domainSuffix}`,...Oc({cloudflareZoneId:e.cloudflareZoneId}),contentRepo:e.contentRepoOverride??`${r.contentRepoPrefix}${e.handle}-content`,...Oc({profileKind:e.profileKind,anchorKind:e.anchorKind,embeddingEnabled:e.embeddingEnabled,embeddingModel:e.embeddingModel,spaces:e.spaces,plugins:e.plugins,topicExtractionEnabled:e.topicExtractionEnabled,skillDerivationEnabled:e.skillDerivationEnabled,swotDerivationEnabled:e.swotDerivationEnabled,siteOverride:e.siteOverride&&{...e.siteOverride}}),discordEnabled:e.discord.enabled,...Oc({discordAnchorUserId:e.discord.anchorUserId}),effectiveOpenaiApiKey:e.openaiApiKeyOverride??t.data.openaiApiKeyOverride??r.openaiApiKey,effectiveGitSyncToken:e.gitSyncTokenOverride??t.data.gitSyncTokenOverride??r.gitSyncToken,...Oc({setup:e.setup,atproto:e.atproto,playbooks:e.playbooks}),anchorProfile:hee(e.handle,e.anchorProfile)}}function rB(e,t){return bee([...e??[],...t??[]])}async function pee(e){let t=zd(e,"users"),r=(await nB(t)).filter((n)=>!VI(n).endsWith(".secrets.yaml"));return(await Promise.all(r.map(async(n)=>{let i=oB(VI(n)),s=await WI(n,dg);if(s.handle!==i){let a=Uc(uee(e,n));throw new ea(`${a} must declare handle: ${i}`)}return{id:i,data:s}}))).sort((n,i)=>n.id.localeCompare(i.id))}async function fee(e){let t=zd(e,"cohorts"),r=await nB(t);return(await Promise.all(r.map(async(n)=>({id:oB(VI(n)),data:await WI(n,hn)})))).sort((n,i)=>n.id.localeCompare(i.id))}function mee(e,t){let r=new Map(e.map((n)=>[n.data.handle,n])),o=new Map;for(let n of t)for(let i of n.data.members){if(!r.has(i))throw new ea(`Cohort ${n.id} references unknown user ${i}`);if(o.has(i))throw new ea(`User ${i} must belong to exactly one cohort`);o.set(i,n)}for(let n of e)if(!o.has(n.data.handle))throw new ea(`User ${n.data.handle} must belong to exactly one cohort`);return o}function hee(e,t){return{name:t?.name??gee(e),...t?.description?{description:t.description}:{},...t?.website?{website:t.website}:{},...t?.email?{email:t.email}:{},...t?.story?{story:t.story}:{},...t?.socialLinks?{socialLinks:t.socialLinks.map((r)=>({platform:r.platform,url:r.url,...r.label?{label:r.label}:{}}))}:{}}}function gee(e){return e.split("-").filter((t)=>t.length>0).map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async function yee(e,t){let r=zd(e,"users",t,"brain.yaml");return await Ir(r)?"present":"missing"}async function nB(e){return(await cee(e,{withFileTypes:!0})).filter((r)=>r.isFile()&&r.name.endsWith(".yaml")).map((r)=>zd(e,r.name)).sort((r,o)=>r.localeCompare(o))}async function WI(e,t){let r=await lee(e,"utf8"),o=yr(r,t);if(!o.ok)throw new ea(`${Uc(e)}: ${o.error}`);return o.data}function bee(e){return[...new Set(e)]}function oB(e){return e.replace(/\.ya?ml$/,"")}var ea;var gn=b(()=>{Vn();$o();Xs();ea=class ea extends Error{}});import{mkdir as Eee,writeFile as Aee}from"fs/promises";import{join as cB}from"path";async function Pi(e,t={}){let o=(t.registry??await xt(e,t)).users.map((i)=>{let s=i.discordEnabled?"on":"off";return[i.handle,i.cohort,i.bundles.join(","),i.add.join(","),i.remove.join(","),i.brainVersion,i.domain,i.contentRepo,s,i.serverStatus,i.deployStatus,i.dnsStatus,i.mcpStatus]}),n=["<!-- generated by brains-ops; do not edit -->","",Iee,kee,...o.map((i)=>`| ${i.join(" | ")} |`),""].join(`
|
|
283
|
+
`;return""}return xI.dump=X,xI}function qG(){if(YD)return nr;YD=1;let e=UG(),t=MG();function r(o,n){return function(){throw Error("Function yaml."+o+" is removed in js-yaml 4. Use yaml."+n+" instead, which is now safe by default.")}}return nr.Type=gr(),nr.Schema=XD(),nr.FAILSAFE_SCHEMA=nL(),nr.JSON_SCHEMA=cL(),nr.CORE_SCHEMA=lL(),nr.DEFAULT_SCHEMA=_I(),nr.load=e.load,nr.loadAll=e.loadAll,nr.dump=t.dump,nr.YAMLException=Id(),nr.types={binary:pL(),float:aL(),map:rL(),null:oL(),pairs:mL(),set:hL(),timestamp:uL(),bool:iL(),int:sL(),merge:dL(),omap:fL(),seq:tL(),str:eL()},nr.safeLoad=r("safeLoad","load"),nr.safeLoadAll=r("safeLoadAll","loadAll"),nr.safeDump=r("safeDump","dump"),nr}var nr,Xh,Oi,RD,tI,TD,rI,$D,nI,OD,oI,CD,iI,zD,sI,PD,aI,ND,cI,DD,lI,LD,uI,ZD,dI,jD,pI,BD,fI,UD,mI,MD,hI,qD,gI,FD,yI,JD,bI,KD,SI,HD,vI,VD,wI,WD,GD,xI,QD,YD,FG,gL,Cc,JG,KG,HG,VG,EI,zc,WG,kd,GG,QG,YG,XG,eQ;var Pc=b(()=>{nr={},Xh={},Oi={};xI={};FG=qG(),gL=jG(FG),{Type:Cc,Schema:JG,FAILSAFE_SCHEMA:KG,JSON_SCHEMA:HG,CORE_SCHEMA:VG,DEFAULT_SCHEMA:EI,load:zc,loadAll:WG,dump:kd,YAMLException:GG,types:QG,safeLoad:YG,safeLoadAll:XG,safeDump:eQ}=gL});function Nc(e){return kd(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function yL(e){return zc(e)}function yr(e,t){if(!e.trim())return{ok:!1,error:"file is empty"};let r;try{r=zc(e)}catch(n){return{ok:!1,error:Ve(n,"YAML parse error")}}if(!tQ(r))return{ok:!1,error:"expected a YAML mapping (key: value pairs)"};if(!t)return{ok:!0,data:r};let o=t.safeParse(r);if(!o.success)return{ok:!1,error:`invalid field(s): ${o.error.issues.map((i)=>i.path.map(String).join(".")).join(", ")}`};return{ok:!0,data:o.data}}function tQ(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var Vn=b(()=>{Pc()});var AI,bL;var II=b(()=>{ue();AI=c.object({title:c.string().trim().min(1).max(500).optional(),introduction:c.string().trim().min(1).max(4000).optional(),topics:c.array(c.string().trim().min(1).max(500)).max(20).optional(),topicsHeading:c.string().trim().min(1).max(120).optional(),contactLabel:c.string().trim().min(1).max(80).optional(),contactNote:c.string().trim().min(1).max(240).optional(),mapCaption:c.string().trim().min(1).max(160).optional(),refusal:c.string().trim().min(1).max(500).optional(),faqHeading:c.string().trim().min(1).max(120).optional()}),bL=AI.omit({introduction:!0})});function Ws(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function vL(e){let t=Reflect.get(Vs,"types"),r=Ws(t)?t[e]:void 0;if(!(r instanceof Cc))throw Error(`Required YAML type is unavailable: ${e}`);return r}function oQ(e,t){let r=0,o=1;for(let n of e.split(":").reverse())r+=(t?Number.parseFloat(n):Number.parseInt(n,10))*o,o*=60;return r}function SL(e){let t=vL(e);return new Cc(`tag:yaml.org,2002:${e}`,{kind:"scalar",resolve:(r)=>typeof r==="string"&&(e==="int"?rQ:nQ).test(r)&&!r.endsWith("_"),construct:(r)=>{let o=r.replace(/_/g,""),n=o.startsWith("-")?-1:1,i=o.replace(/^[+-]/,"");if(i.includes(":"))return n*oQ(i,e==="float");if(e==="int"&&i==="0")return 0;if(e==="int"&&/^0[0-7]+$/.test(i))return n*Number.parseInt(i,8);return t.construct(o)},predicate:t.predicate??void 0,represent:t.represent??void 0,defaultStyle:t.defaultStyle??void 0})}var rQ,nQ,kI,iQ,sQ,aQ;var wL=b(()=>{Pc();rQ=/^[+-]?(?:0|0b[01_]*[01]|0x[\da-fA-F_]*[\da-fA-F]|0[0-7_]*[0-7]|[1-9](?:[\d_]*\d)?|[1-9][\d_]*(?::[0-5]?\d)+)$/,nQ=/^(?:[-+]?(?:0|[1-9][\d_]*)(?:\.[\d_]*)?(?:[eE][-+]?\d+)?|\.[\d_]+(?:[eE][-+]?\d+)?|[-+]?\d[\d_]*(?::[0-5]?\d)+\.[\d_]*|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$/;kI=vL("binary"),iQ=new Cc("tag:yaml.org,2002:binary",{kind:"scalar",resolve:(e)=>kI.resolve(e),construct:(e)=>{let t=kI.construct(e);if(!(t instanceof Uint8Array))throw Error("Invalid YAML binary result");return typeof Buffer>"u"?Array.from(t):Buffer.from(t)},predicate:(e)=>typeof Buffer<"u"&&Buffer.isBuffer(e),represent:kI.represent??void 0}),sQ=new Cc("tag:yaml.org,2002:str",{kind:"scalar",resolve:(e)=>typeof e==="string"&&e.includes(":"),construct:(e)=>e}),aQ=EI.extend({implicit:[SL("int"),SL("float"),sQ],explicit:[iQ]})});var xL=b(()=>{Pc();wL()});var _L,EL,AL,cQ;var RI=b(()=>{xL();ue();_L=c.object({audiences:c.array(c.string()).optional(),positioning:c.string().optional()}),EL=c.object({summary:c.string().optional(),traits:c.array(c.string()).optional(),principles:c.array(c.string()).optional(),preferredTerms:c.array(c.string()).optional(),avoid:c.array(c.string()).optional()}),AL=c.object({artDirection:c.string().optional(),palette:c.array(c.string()).optional(),composition:c.string().optional(),mood:c.string().optional(),preferred:c.array(c.string()).optional(),avoid:c.array(c.string()).optional()}),cQ=c.object({name:c.string().describe("Style guide name"),messaging:_L.optional(),voice:EL.optional(),visual:AL.optional()})});var kL=b(()=>{II();RI()});var Dc,qEe,TI="data-ask-sheet",lQ;var $I=b(()=>{ue();Dc=c.object({name:c.string().trim().min(1).max(200),url:c.string().url().optional()}),qEe=c.object({sources:c.array(c.object({id:c.string(),title:c.string(),brain:Dc.optional()}))}),lQ=`body *:not([${TI}], [${TI}] *) { -webkit-backdrop-filter: none !important; backdrop-filter: none !important; }`});import{createHash as uQ}from"crypto";function eg(e){return uQ("sha256").update(e).digest("hex")}var tg=()=>{};var Wn;var Rd=b(()=>{ue();tg();Wn=c.discriminatedUnion("kind",[c.object({kind:c.literal("user"),userId:c.string().min(1),canonicalId:c.string().min(1).optional()}),c.object({kind:c.literal("external"),externalActorId:c.string().min(1)}),c.object({kind:c.literal("agent"),agentId:c.string().min(1)}),c.object({kind:c.literal("service"),serviceId:c.string().min(1)})])});var dQ,QEe,Lc,pQ,fQ,RL,YEe,mQ,hQ,TL;var $L=b(()=>{ue();dQ=c.strictObject({messageCharacters:c.number().int().positive(),requestTimeoutSeconds:c.number().int().positive().max(2147483)}),QEe=c.strictObject({limits:dQ,maxCostMicroUsd:c.number().int().positive()}),Lc=c.number().int().nonnegative(),pQ=c.strictObject({modelCalls:Lc,inputTokens:Lc,cachedInputTokens:Lc,outputTokens:Lc,reasoningTokens:Lc,embeddingTokens:Lc}),fQ=c.discriminatedUnion("state",[c.strictObject({state:c.literal("known"),microUsd:c.number().int().nonnegative(),pricing:c.string().trim().min(1).max(120)}),c.strictObject({state:c.literal("unknown"),reason:c.enum(["missing-usage","unsupported-pricing"])})]),RL=c.strictObject({usage:pQ,cost:fQ}),YEe=c.strictObject({topics:c.array(c.string().trim().min(1).max(500)).max(20),introduction:c.string().trim().min(1).max(4000).optional(),refusal:c.string().trim().min(1).max(500).optional()}),mQ=c.enum(["in-scope","off-topic","abusive","injection","harmful"]),hQ=mQ.exclude(["in-scope"]),TL=c.discriminatedUnion("outcome",[c.strictObject({outcome:c.literal("answered")}),c.strictObject({outcome:c.literal("refused"),category:hQ}),c.strictObject({outcome:c.literal("unscreened")})])});function yQ(e){let t=gQ.safeParse(e);if(!t.success)return e;return{...t.data,cards:t.data.cards.filter((r)=>OI.safeParse(r).success)}}var OL,CL,zL,PL,NL,DL,Zc,LL,ZL,jL,BL,UL,OI,ML,qL,Td,gQ,FL;var jc=b(()=>{ue();$I();$L();OL=c.object({id:c.string(),toolCallId:c.string().optional(),toolName:c.string(),summary:c.string(),completionSummary:c.string().optional(),preview:c.string().optional(),args:c.unknown()}),CL=c.enum(["approval-requested","approval-responded","output-available","output-denied","output-error"]),zL=c.object({kind:c.literal("tool-approval"),id:c.string(),toolCallId:c.string().optional(),toolName:c.string(),input:c.record(c.string(),c.unknown()).optional(),summary:c.string(),completionSummary:c.string().optional(),preview:c.string().optional(),state:CL,output:c.unknown().optional(),error:c.string().optional()}),PL=c.object({entityType:c.string().optional(),entityId:c.string().optional(),attachmentType:c.string().optional()}),NL=c.object({mediaType:c.string().min(1),url:c.string().min(1),downloadUrl:c.string().min(1).optional(),previewUrl:c.string().min(1).optional(),filename:c.string().min(1).optional(),sizeBytes:c.number().nonnegative().optional(),source:PL.optional()}),DL=c.object({kind:c.literal("attachment"),id:c.string(),jobId:c.string().optional(),title:c.string(),description:c.string().optional(),attachment:NL}),Zc=c.object({id:c.string().min(1),title:c.string().min(1).optional(),source:c.string().min(1),url:c.string().min(1).optional(),entityType:c.string().min(1).optional(),entityId:c.string().min(1).optional(),excerpt:c.string().min(1).optional(),provenance:c.record(c.string(),c.unknown()).optional(),brain:Dc.optional()}),LL=c.object({kind:c.literal("sources"),id:c.string().min(1),title:c.string().min(1).optional(),sources:c.array(Zc).min(1)}),ZL=c.object({type:c.literal("prompt"),id:c.string().min(1),label:c.string().min(1),prompt:c.string().min(1),description:c.string().min(1).optional()}),jL=c.object({type:c.literal("event"),id:c.string().min(1),label:c.string().min(1),event:c.string().min(1),fromState:c.string().min(1).optional(),description:c.string().min(1).optional()}),BL=c.discriminatedUnion("type",[ZL,jL]),UL=c.object({kind:c.literal("actions"),id:c.string().min(1),title:c.string().min(1).optional(),defaultOpen:c.boolean().optional(),actions:c.array(BL).min(1)}),OI=c.discriminatedUnion("kind",[zL,DL,LL,UL]),ML=c.object({toolName:c.string(),args:c.record(c.string(),c.unknown()).optional(),jobId:c.string().optional(),data:c.unknown().optional(),error:c.object({message:c.string(),code:c.string().optional()}).optional()}),qL=c.object({faqId:c.string().min(1)}),Td=c.object({text:c.string(),error:c.string().optional(),toolResults:c.array(ML).optional(),cards:c.array(OI).optional(),pendingConfirmations:c.array(OL).optional(),usage:c.object({promptTokens:c.number(),completionTokens:c.number(),totalTokens:c.number()}),guestSettlement:RL.optional(),guestScreening:TL.optional(),askedBefore:qL.optional()}),gQ=c.looseObject({cards:c.array(c.unknown())});FL=c.preprocess((e)=>yQ(Yh(e)),Td)});function he(e){return Object.freeze({name:e.channel,schema:e.request,response:e.response,delivery:e.delivery})}function Gn(e,t){return Object.freeze({name:e,schema:t})}var aAe;var rg=b(()=>{ue();aAe=c.object({name:c.string(),schema:c.custom((e)=>typeof e==="object"&&e!==null&&("safeParse"in e))})});var ng,bQ,SQ,vQ,wQ,JL,xQ,_Q,EQ,AQ,IQ,kQ,KL,HL,VL,RQ,WL,TQ,GL,$Q,QL,OQ;var YL=b(()=>{ue();Rd();jc();rg();ng=c.object({state:c.string(),response:c.string(),sources:c.array(Zc)}),bQ=c.object({agent:c.string().trim().min(1).max(253),question:c.string().trim().min(1).max(4000)}),SQ=he({channel:"a2a:ask:request",request:bQ,response:ng,delivery:"request"}),vQ=c.object({agent:c.string().trim().min(1).max(253),message:c.string().trim().min(1).max(32000)}),wQ=he({channel:"a2a:turn:request",request:vQ,response:ng,delivery:"request"}),JL=c.object({entityType:c.string().optional(),entityId:c.string().optional(),actor:Wn.optional(),interfaceType:c.string().optional(),userPermissionLevel:c.enum(["admin","trusted","public"])}),xQ=c.object({agent:c.string().trim().min(1).max(253),instruction:c.string().trim().min(1).max(2000),selection:c.string().min(1).max(8000),...JL.shape}),_Q=he({channel:"a2a:call:request",request:xQ,response:ng,delivery:"request"}),EQ=c.object({agents:c.array(c.object({id:c.string(),label:c.string()}))}),AQ=he({channel:"a2a:call:agents",request:JL,response:EQ,delivery:"request"}),IQ=c.object({approvedAt:c.string(),approvedBy:c.string().optional()}),kQ=c.discriminatedUnion("op",[c.object({op:c.literal("get"),entityType:c.string().min(1),id:c.string().min(1)}),c.object({op:c.literal("list")})]),KL=c.object({entities:c.array(c.object({entityType:c.string().min(1),id:c.string().min(1),title:c.string()}))}),HL=c.object({signedAt:c.string().min(1),keyId:c.string().min(1),signature:c.string().min(1)}),VL=c.object({entityType:c.string().min(1),id:c.string().min(1),markdown:c.string(),contentHash:c.string().min(1),attestation:HL}),RQ=c.object({agent:c.string().min(1),entityType:c.string().min(1),id:c.string().min(1)}),WL=c.discriminatedUnion("status",[c.object({status:c.literal("found"),entity:VL}),c.object({status:c.literal("not-found")}),c.object({status:c.literal("refused"),code:c.string(),error:c.string()})]),TQ=he({channel:"a2a:shared-entity:get",request:RQ,response:WL,delivery:"request"}),GL=c.discriminatedUnion("status",[c.object({status:c.literal("found"),entities:KL.shape.entities}),c.object({status:c.literal("not-found")}),c.object({status:c.literal("refused"),code:c.string(),error:c.string()})]),$Q=he({channel:"a2a:shared-entity:list",request:c.object({agent:c.string().min(1)}),response:GL,delivery:"request"}),QL=c.object({domain:c.string().min(1),level:c.enum(["trusted","public"])}),OQ=Gn("a2a:peer-trust-changed",QL)});var CQ,XL,zQ,PQ;var eZ=b(()=>{ue();jc();CQ=c.object({type:c.literal("event"),event:c.string().min(1),fromState:c.string().min(1).optional()}),XL=c.object({conversationId:c.string().min(1),interfaceType:c.string().min(1),channelId:c.string().min(1).optional(),channelName:c.string().min(1),userPermissionLevel:c.enum(["admin","trusted","public"]),isAnchor:c.boolean(),action:CQ}),zQ=FL.nullable(),PQ=he({channel:"agent:action:request",request:XL,response:zQ,delivery:"request"})});var tZ,NQ,rZ,DQ;var nZ=b(()=>{ue();jc();tZ=c.object({question:c.string().trim().min(1)}),NQ=c.object({faqId:c.string().min(1),faqQuestion:c.string().min(1),answer:c.string().trim().min(1),sources:c.array(Zc).default([])}),rZ=c.object({hit:NQ.optional()}),DQ=he({channel:"guest:asked-before",request:tZ,response:rZ,delivery:"collect"})});var iZ,oZ,sZ,aZ,LQ,cZ,lZ,uZ,ZQ;var dZ=b(()=>{ue();iZ=c.enum(["studio","drive","file","git"]),oZ=c.enum(["public","shared","restricted"]),sZ=c.object({entityType:c.string().min(1),entityId:c.string().min(1),origin:iZ,actor:c.string().min(1).optional(),base:c.string().min(1).optional(),current:c.string().min(1),text:c.string(),targetVisibility:oZ,declaredVisibility:oZ.optional()}),aZ=c.object({conflictId:c.string().min(1),created:c.boolean()}),LQ=he({channel:"conflict:record",request:sZ,response:aZ,delivery:"request"}),cZ=c.enum(["apply","keep-current"]),lZ=c.object({conflictId:c.string().min(1),action:cZ,userId:c.string().min(1),permissionLevel:c.enum(["admin","trusted","public"])}),uZ=c.object({resolved:c.literal(!0)}),ZQ=he({channel:"conflict:resolve",request:lZ,response:uZ,delivery:"request"})});var jQ,pZ,fZ,RAe,BQ,UQ;var mZ=b(()=>{ue();jQ=c.enum(["admin","trusted","public"]),pZ=c.object({conversationId:c.string().min(1),message:c.string(),interfaceType:c.string().min(1),channelId:c.string().optional(),channelName:c.string().optional(),userPermissionLevel:jQ}),fZ=c.object({id:c.string().min(1),source:c.string().min(1),title:c.string().optional(),content:c.string().min(1),provenance:c.record(c.string(),c.unknown()).optional()}),RAe=c.object({items:c.array(fZ).default([])}),BQ=c.object({items:c.array(c.unknown()).default([]).transform((e)=>e.flatMap((t)=>{let r=fZ.safeParse(t);return r.success?[r.data]:[]}))}),UQ=he({channel:"agent:context:request",request:pZ,response:BQ,delivery:"collect"})});var MQ,qQ;var hZ=b(()=>{ue();MQ=c.strictObject({entityType:c.string().min(1),entityId:c.string().min(1)}),qQ=c.strictObject({startedAt:c.string().datetime(),retrieved:c.array(MQ).max(50)})});var gZ,FQ,yZ,JQ;var bZ=b(()=>{ue();Rd();gZ=c.object({actor:Wn}),FQ=c.object({userId:c.string().min(1),personId:c.string().min(1),canonicalId:c.string().min(1).optional(),displayName:c.string().min(1),permissionLevel:c.enum(["admin","trusted","public"])}),yZ=c.object({principal:FQ.nullable()}),JQ=he({channel:"auth:principal:resolve",request:gZ,response:yZ,delivery:"request"})});var SZ,KQ;var vZ=b(()=>{ue();SZ=c.object({type:c.string().regex(/^[a-z][a-z0-9-]*$/),subjectPrefix:c.string().max(32).default(""),subjectSuffix:c.string().max(255).default("")}),KQ=c.object({clientId:c.string().regex(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/).min(3).max(64),clientSecret:c.string().min(32).max(512),clientName:c.string().trim().min(1).max(200),redirectUris:c.array(c.url()).min(1).max(10),identityClaim:SZ.optional()})});var wZ=()=>{};var xZ=()=>{};var CI,HQ,_Z,VQ,WQ;var EZ=b(()=>{ue();CI=c.strictObject({name:c.string().min(1).optional(),address:c.email()}),HQ=c.strictObject({personId:c.string().min(1).max(200),displayName:c.string().trim().min(1).max(200),permissionLevel:c.enum(["admin","trusted","public"])}),_Z=c.strictObject({messageId:c.string().min(1),sourceRef:c.string().min(1),threadId:c.string().min(1).optional(),from:CI,replyTo:CI.optional(),to:c.array(CI),subject:c.string(),receivedAt:c.iso.datetime(),text:c.string(),html:c.string().min(1).optional(),headers:c.strictObject({listUnsubscribe:c.string().min(1).optional(),autoSubmitted:c.string().min(1).optional(),precedence:c.string().min(1).optional(),inReplyTo:c.string().min(1).optional(),references:c.array(c.string().min(1)).optional()}),sender:HQ.optional()}),VQ=c.strictObject({}),WQ=he({channel:"email:inbound",request:_Z,response:VQ,delivery:"request"})});var GQ,QQ,AZ,zI,YQ,IZ,XQ;var kZ=b(()=>{ue();GQ=c.strictObject({permissionLevel:c.enum(["admin","trusted","public"])}),QQ=c.custom((e)=>typeof AbortSignal<"u"&&e instanceof AbortSignal),AZ=c.strictObject({sourceRef:c.string().regex(/^imap:[a-f0-9]{64}$/),actor:GQ,signal:QQ.optional()}),zI=c.strictObject({name:c.string().trim().min(1).max(300).optional(),address:c.email().max(320)}),YQ=c.strictObject({messageId:c.string().trim().min(1).max(2000),from:zI,replyTo:zI.optional(),to:c.array(zI).max(100),subject:c.string().max(1000),receivedAt:c.iso.datetime(),text:c.string().max(1e5),inReplyTo:c.string().trim().min(1).max(2000).optional(),references:c.array(c.string().trim().min(1).max(2000)).max(100),truncated:c.boolean()}),IZ=c.discriminatedUnion("kind",[c.strictObject({kind:c.literal("available"),message:YQ}),c.strictObject({kind:c.literal("unavailable")})]),XQ=he({channel:"email:source-read",request:AZ,response:IZ,delivery:"request"})});var RZ=b(()=>{tg()});var eY;var TZ=b(()=>{ue();eY=c.object({url:c.string(),authToken:c.string().optional()})});var tY;var $Z=b(()=>{ue();tY=c.object({success:c.boolean(),entityId:c.string().optional(),error:c.string().optional()})});var OZ=()=>{};function og(e,t="handler_failed"){let r=t,o;try{if(e!==null&&typeof e==="object"){let n=$d.safeParse(Reflect.get(e,"code"));if(n.success)r=n.data,o=Od.shape.message.safeParse(Reflect.get(e,"publicMessage")).data;else{let i=Reflect.get(e,"name");if(i==="AbortError")r="cancelled";if(i==="TimeoutError")r="deadline_exceeded"}}}catch{}return new Ci(r,{cause:e,...o!==void 0?{publicMessage:o}:{}})}var $d,zZ=1024,Od,CZ,Ci;var PZ=b(()=>{ue();$d=c.enum(["no_handler","handler_failed","invalid_input","invalid_response","unauthenticated","permission_denied","not_found","conflict","cancelled","deadline_exceeded"]),Od=c.object({code:$d,message:c.string().max(zZ)}),CZ={no_handler:"No handler is available for this capability",handler_failed:"The operation failed",invalid_input:"Invalid input",invalid_response:"Invalid response",unauthenticated:"Authentication required",permission_denied:"Permission denied",not_found:"Not found",conflict:"The operation conflicts with the current state",cancelled:"The operation was cancelled",deadline_exceeded:"The execution deadline was exceeded"};Ci=class Ci extends Error{code;publicMessage;constructor(e,t={}){let r=$d.parse(e),o=Od.shape.message.parse(t.publicMessage??CZ[r]);super(t.message??o,{cause:t.cause});this.name="SdkError",this.code=r,this.publicMessage=o}toJSON(){let e=$d.safeParse(this.code),t=e.data??"handler_failed",r=e.success?Od.shape.message.safeParse(this.publicMessage).data:void 0;return{code:t,message:r??CZ[t]}}}});var ig,sg;var PI=b(()=>{ue();ig=c.lazy(()=>c.union([c.null(),c.boolean(),c.number().finite().refine((e)=>!Number.isInteger(e)||Number.isSafeInteger(e),{message:"integer exceeds the JSON-safe range"}),c.string(),c.array(ig),c.record(c.string(),ig)])),sg=c.record(c.string(),ig)});var rY;var NZ=b(()=>{ue();rY=c.enum(["user","assistant"])});var nY,To;var DZ=b(()=>{ue();nY=c.object({entityType:c.string().min(1),entityId:c.string().min(1),contentHash:c.string().min(1).optional()}),To=c.object({rootJobId:c.string().min(1),causationId:c.string().min(1),projectionId:c.string().min(1).optional(),projectionLineage:c.array(c.string().min(1)),sourceEntity:nY.optional(),derivationDepth:c.number().int().nonnegative()}).superRefine((e,t)=>{if(e.derivationDepth!==e.projectionLineage.length)t.addIssue({code:"custom",path:["derivationDepth"],message:"Derivation depth must equal projection lineage length"});let r=e.projectionLineage.at(-1);if(e.projectionId!==r)t.addIssue({code:"custom",path:["projectionId"],message:"Current projection must equal the final projection lineage entry"})})});var NI=10,LZ=82,DI,oY,iY,sY,aY,cY,lY;var ZZ=b(()=>{ue();DI=c.object({title:c.string().min(1).max(200),lines:c.array(c.string().min(1)).min(1).max(NI),actions:c.array(c.object({label:c.string().min(1).max(80),value:c.string().min(1).max(LZ)})).max(NI)}),oY=DI.extend({channelId:c.string().min(1),interfaceType:c.string().min(1),reactions:c.array(c.object({messageId:c.string().min(1),emoji:c.string().min(1)}))}),iY=c.object({messageId:c.string().min(1)}),sY=c.object({conversationId:c.string().min(1),noticeMessageId:c.string().min(1),value:c.string().min(1),by:c.string().min(1)}),aY=he({channel:"chat:space-notice",request:oY,response:iY,delivery:"request"}),cY=DI.nullable(),lY=he({channel:"chat:space-notice-action",request:sY,response:cY,delivery:"collect"})});var LI,ZI,uY,dY,pY,fY;var jZ=b(()=>{ue();rg();LI={progress:"job-progress"},ZI={completed:"publish:completed",failed:"publish:failed"},uY=c.object({entityType:c.string().min(1),entityId:c.string().min(1),result:c.object({id:c.string(),url:c.string().optional()})}),dY=c.object({entityType:c.string().min(1),entityId:c.string().min(1),error:c.string(),retryCount:c.number(),willRetry:c.boolean()}),pY=Gn(ZI.completed,uY),fY=Gn(ZI.failed,dY)});var jI=()=>{};var bIe;var BZ=b(()=>{ue();jI();bIe=c.object({public:c.boolean(),preview:c.boolean()})});var UZ,MZ,hY;var qZ=b(()=>{ue();UZ=c.object({entityType:c.string().min(1),entityId:c.string(),metadata:c.record(c.string(),c.unknown()).default({}),content:c.string().default("")}),MZ=c.object({relativePath:c.string(),leaf:c.object({start:c.number().int().nonnegative(),end:c.number().int().nonnegative()}).nullable(),owner:c.object({entityType:c.string(),id:c.string()}).optional(),writable:c.boolean().optional()}),hY=he({channel:"sync:path:request",request:UZ,response:MZ,delivery:"request"})});var gY,yY,bY,SY;var FZ=b(()=>{ue();gY=c.strictObject({}),yY=c.object({branch:c.string(),hasChanges:c.boolean(),ahead:c.number(),behind:c.number(),lastCommit:c.string().nullable(),remote:c.string().nullable()}),bY=c.object({syncPath:c.string(),isInitialized:c.boolean(),watchEnabled:c.boolean(),lastSync:c.string().nullable(),totalFiles:c.number(),byEntityType:c.record(c.string(),c.number()),git:yY.nullable(),managementUrl:c.string().optional()}),SY=he({channel:"sync:status:request",request:gY,response:bY,delivery:"request"})});var JZ=()=>{};var KZ,vY,wY;var HZ=b(()=>{ue();KZ=c.strictObject({waveId:c.string().trim().min(1),sourceTypes:c.array(c.string().trim().min(1)),changedTargetTypes:c.array(c.string().trim().min(1))}),vY=c.strictObject({}),wY=he({channel:"projection:wave-ready",request:KZ,response:vY,delivery:"collect"})});var xY,_Y,EY,AY;var VZ=b(()=>{ue();xY=c.strictObject({}),_Y=c.object({entityType:c.string().min(1),entityId:c.string().min(1),previousHash:c.string().min(1),contentHash:c.string().min(1)}),EY=c.object({restated:c.array(_Y)}),AY=he({channel:"stored-content:restate",request:xY,response:EY,delivery:"collect"})});var IY,kY,RY;var WZ=b(()=>{ue();IY=c.strictObject({}),kY=c.string(),RY=he({channel:"plugin:site-builder:head-scripts",request:IY,response:kY,delivery:"collect"})});function BI(e){return typeof e==="function"}var GZ=".site-build-manifest.json",TY,$Y,OY,CY;var QZ=b(()=>{ue();TY=`/${GZ}`,$Y=he({channel:"site:build:requested",request:c.object({reason:c.string().min(1)}),response:c.void(),delivery:"command"});OY=c.object({outputDir:c.string(),environment:c.enum(["preview","production"]),routesBuilt:c.number(),siteConfig:c.object({title:c.string().optional(),description:c.string().optional(),url:c.string().optional(),copyright:c.string().optional(),themeMode:c.enum(["light","dark"]).optional()}),generateEntityUrl:c.custom(BI),renderMarkdown:c.custom(BI),reportFailure:c.custom(BI)}),CY=he({channel:"site:build:staging",request:OY,response:c.void(),delivery:"command"})});var zY,PY,NY;var YZ=b(()=>{ue();zY=c.object({id:c.string().min(1),trigger:c.string().min(1),playbookId:c.string().min(1),once:c.boolean().default(!0),starterText:c.string().min(1),description:c.string().min(1).optional(),starterPrompt:c.string().min(1)}).strict(),PY=c.object({registered:c.boolean(),id:c.string(),ignored:c.boolean().optional(),reason:c.string().optional()}),NY=he({channel:"playbooks:register-lifecycle-starter",request:zY,response:PY,delivery:"request"})});var DY,LY,ZY;var XZ=b(()=>{ue();DY=c.object({id:c.string().min(1),markdown:c.string().min(1)}).strict(),LY=c.object({created:c.boolean()}),ZY=he({channel:"playbooks:seed",request:DY,response:LY,delivery:"request"})});var ej,ag,UI,tj,rj,jY,BY;var nj=b(()=>{ue();ej=["name","headline","industry","location","website","story"],ag=c.enum(ej),UI=c.object({name:c.string().optional(),headline:c.string().optional(),industry:c.string().optional(),location:c.string().optional(),website:c.string().optional(),story:c.string().optional()}),tj=c.enum(["fill","preserve","unchanged"]),rj=c.object({field:ag,current:c.string().nullable(),imported:c.string(),outcome:tj}),jY=he({channel:"@brains/profile:import-preview",request:c.object({fields:UI}),response:c.object({fields:c.array(rj),changed:c.boolean(),revision:c.string()}),delivery:"request"}),BY=he({channel:"@brains/profile:import-apply",request:c.object({fields:UI,revision:c.string()}),response:c.object({filled:c.array(ag),kept:c.array(ag)}),delivery:"request"})});function qY(e){return typeof e==="object"&&e!==null&&"name"in e&&typeof e.name==="string"&&"publish"in e&&typeof e.publish==="function"}var UY,MY,FY,JY,KY,HY,oj,VY;var ij=b(()=>{ue();UY=c.enum(["provider"]),MY=c.object({executionMode:UY.optional(),publishResultIdField:c.string().min(1).optional(),publishTimestampField:c.string().min(1).optional(),enabled:c.boolean().optional()}).strict();FY=c.custom(qY),JY=c.object({entityType:c.string(),provider:FY.optional(),config:MY.optional()}),KY=he({channel:"publish:register",request:JY,response:c.void(),delivery:"command"}),HY=c.union([c.string().min(1),c.object({location:c.enum(["metadata","frontmatter"]),field:c.string().min(1)})]),oj=c.object({entityType:c.string().min(1),attachmentType:c.string().min(1),mediaEntityType:c.enum(["image"]),targetEntityField:HY.optional(),requiredWhen:c.object({status:c.string().min(1).optional(),visibility:c.string().min(1).optional()}).optional(),autoGenerate:c.boolean().optional(),requiredForPublish:c.boolean().optional()}),VY=he({channel:"publish-assets:register",request:oj,response:c.void(),delivery:"command"})});var sj,aj,WY;var cj=b(()=>{ue();sj=c.object({entityType:c.string().min(1),id:c.string().min(1),userId:c.string().min(1),permissionLevel:c.enum(["admin","trusted","public"])}),aj=c.object({published:c.literal(!0),url:c.string().optional()}),WY=he({channel:"publish:request",request:sj,response:aj,delivery:"request"})});var MI,cg=200,lj=1e5,uj,dj,pj,GY,fj,mj,QY;var hj=b(()=>{ue();jc();MI=c.object({userId:c.string().min(1),personId:c.string().min(1),displayName:c.string(),permissionLevel:c.enum(["admin","trusted","public"]),isAnchor:c.boolean(),canonicalId:c.string().min(1).optional()}),uj=c.object({entityType:c.string().min(1),id:c.string().min(1),title:c.string(),content:c.string().max(lj)}),dj=c.object({asker:MI,interfaceType:c.string().min(1),channelName:c.string().min(1),question:c.string().min(1).max(8000),conversationId:c.string().min(1).max(cg).optional(),entry:uj.optional()}),pj=c.object({conversationId:c.string().min(1),response:Td}),GY=he({channel:"agent:ask",request:dj,response:pj,delivery:"request"}),fj=c.object({asker:MI,interfaceType:c.string().min(1),channelName:c.string().min(1),conversationId:c.string().min(1).max(cg),approvalId:c.string().min(1).max(cg),confirmed:c.boolean()}),mj=c.object({response:Td}),QY=he({channel:"agent:ask-confirm",request:fj,response:mj,delivery:"request"})});var YY,XY,eX,tX,rX,nX;var gj=b(()=>{ue();YY=c.object({entityType:c.string()}),XY=he({channel:"generate:execute",request:YY,response:c.void(),delivery:"command"}),eX=c.object({entityType:c.string(),entityId:c.string()}),tX=he({channel:"generate:report:success",request:eX,response:c.void(),delivery:"command"}),rX=c.object({entityType:c.string(),error:c.string()}),nX=he({channel:"generate:report:failure",request:rX,response:c.void(),delivery:"command"})});var yj=()=>{};var bj,Sj,vj,oX;var wj=b(()=>{ue();Rd();bj=c.record(c.string(),c.unknown()),Sj=c.object({entityType:c.string().min(1),source:c.object({entityType:c.string().min(1),entityIds:c.array(c.string().min(1)).min(1).max(51)}),prompt:c.string().trim().min(1).max(2000).optional(),approval:bj.optional(),actor:Wn,interfaceType:c.string().min(1),userPermissionLevel:c.enum(["admin","trusted","public"])}),vj=c.discriminatedUnion("status",[c.object({status:c.literal("confirm"),summary:c.string(),completionSummary:c.string().optional(),preview:c.string(),approval:bj}),c.object({status:c.literal("queued"),entityId:c.string(),jobId:c.string().optional()}),c.object({status:c.literal("refused"),error:c.string(),code:c.string().optional()})]),oX=he({channel:"generate:from-sources",request:Sj,response:vj,delivery:"request"})});var iX,xj,_j,Ej;var Aj=b(()=>{ue();iX=c.object({message:c.string().describe("Natural language response to the query"),summary:c.string().optional().describe("Brief summary if applicable"),topics:c.array(c.string()).optional().describe("Related topics mentioned"),sources:c.array(c.object({id:c.string(),type:c.string(),excerpt:c.string().optional(),relevance:c.number().min(0).max(1).optional()})).optional().describe("Source entities used to answer the query"),metadata:c.record(c.string(),c.unknown()).optional()}).describe("defaultQueryResponse"),xj=c.object({message:c.string()}).describe("simpleTextResponse"),_j=c.object({success:c.boolean(),entityId:c.string().optional(),message:c.string()}).describe("createEntityResponse"),Ej=c.object({success:c.boolean(),entityId:c.string(),changes:c.array(c.string()).optional(),message:c.string()}).describe("updateEntityResponse")});var Ij,kj,sX,Rj,Tj,aX;var $j=b(()=>{ue();Ij=c.discriminatedUnion("type",[c.strictObject({type:c.literal("email"),address:c.email()}),c.strictObject({type:c.literal("matrix"),address:c.string().regex(/^@[a-z0-9._=/+-]+:[A-Za-z0-9.-]+(:[0-9]+)?$/)})]),kj=c.strictObject({recipient:Ij.optional(),title:c.string().min(1),body:c.string().min(1),html:c.string().min(1).optional(),sensitivity:c.enum(["normal","secret"]).default("normal"),idempotencyKey:c.string().trim().min(1).max(200).optional(),replyTo:c.email().optional()}),sX=c.enum(["recipient-missing","transport-missing","delivery-failed"]),Rj=c.string().regex(/^[a-z0-9_:.-]{1,80}$/u),Tj=c.discriminatedUnion("status",[c.strictObject({status:c.literal("sent"),deliveryId:c.string().optional()}),c.strictObject({status:c.literal("failed"),failure:sX,transportCode:Rj.optional()})]),aX=he({channel:"notifications:send",request:kj,response:Tj,delivery:"request"})});var cX,Oj,lX;var Cj=b(()=>{ue();cX=c.strictObject({}),Oj=c.strictObject({titles:c.array(c.string().trim().min(1).max(500)).max(20)}),lX=he({channel:"topics:public-titles",request:cX,response:Oj,delivery:"request"})});var uX,qI,dX,pX,fX,mX,hX,gX;var zj=b(()=>{ue();uX=c.strictObject({}),qI=c.string().trim().min(1).max(100),dX=c.strictObject({types:c.array(qI).max(20)}),pX=he({channel:"collections:types",request:uX,response:dX,delivery:"collect"}),fX=c.strictObject({entityType:qI,ids:c.array(c.string().min(1).max(500)).min(1).max(200),visibilityScope:c.enum(["public","shared","restricted"])}),mX=c.strictObject({entityType:qI,id:c.string().min(1).max(500)}),hX=c.strictObject({collections:c.array(c.strictObject({id:c.string().min(1).max(500),members:c.array(mX).max(1000)})).max(200)}),gX=he({channel:"collections:members",request:fX,response:hX,delivery:"collect"})});var yX,bX,SX,vX,wX;var Pj=b(()=>{ue();yX=c.string().trim().regex(/^[a-z][a-z0-9-]*$/).max(100),bX=c.strictObject({entityType:yX,entityId:c.string().min(1).max(300),visibilityScope:c.enum(["public","shared","restricted"])}),SX=c.strictObject({name:c.string().min(1).max(100),label:c.string().min(1).max(100)}),vX=c.strictObject({title:c.string().max(500),typeLabel:c.string().min(1).max(100),markdown:c.string(),fields:c.array(SX).max(40)}).nullable(),wX=he({channel:"studio:entry-context",request:bX,response:vX,delivery:"request"})});var xX,_X,EX;var Nj=b(()=>{ue();xX=c.strictObject({}),_X=c.strictObject({types:c.array(c.string().trim().min(1))}),EX=he({channel:"topics:source-types",request:xX,response:_X,delivery:"request"})});var Dj,Lj,AX;var Zj=b(()=>{ue();Dj=c.strictObject({id:c.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/),title:c.string().trim().min(1).max(200),body:c.string().trim().min(1).max(20000)}),Lj=c.strictObject({noteId:c.string(),created:c.boolean()}),AX=he({channel:"note:capture",request:Dj,response:Lj,delivery:"request"})});var Bc,Cd,IX,kX,RX,TX,$X,OX;var jj=b(()=>{ue();PI();Bc=c.string().regex(/^[a-z][a-z0-9-]{0,63}$/),Cd=c.string().min(32).max(512),IX=c.strictObject({provider:Bc,brainState:Cd}),kX=c.strictObject({authorizationUrl:c.url({protocol:/^https?$/})}),RX=c.strictObject({provider:Bc,grant:Cd}),TX=c.strictObject({provider:Bc,credential:sg}),$X=c.enum(["provider_denied","authorization_incomplete","credential_exchange_failed"]),OX=c.union([c.strictObject({provider:Bc,state:Cd,grant:Cd}),c.strictObject({provider:Bc,state:Cd,error:$X})])});var CX,zX,PX,NX;var Bj=b(()=>{ue();CX=c.object({permissionLevel:c.enum(["public","trusted","admin"])}),zX=c.object({id:c.string().min(1),title:c.string().min(1),sub:c.string().optional(),href:c.string().min(1),primary:c.boolean().optional(),keywords:c.array(c.string()).optional()}),PX=c.array(zX),NX=he({channel:"console:jump-destinations",request:CX,response:PX,delivery:"collect"})});var lg,FI,Fke;var Uj=b(()=>{ue();lg=c.enum(["github","instagram","linkedin","podcast","email","website"]),FI=c.object({platform:lg.describe("Social media platform"),url:c.string().describe("Profile or contact URL"),label:c.string().optional().describe("Optional display label")}),Fke=c.email()});function zi(e){if(!e.type.includes(":"))throw Error(`Job contract type "${e.type}" must name its owner, as "owner:job"`);return Object.freeze({type:e.type,input:e.input})}var Mj,qj,Fj,DX,LX,Jj,ZX;var Kj=b(()=>{ue();Mj=c.enum(["1:1","16:9","9:16","4:3","3:4"]),qj=c.object({prompt:c.string(),title:c.string().optional(),aspectRatio:Mj.optional(),targetEntityType:c.string().optional(),targetEntityId:c.string().optional(),entityTitle:c.string().optional(),entityContent:c.string().optional()}),Fj=c.object({imageId:c.string().min(1)}),DX=zi({type:"image:image-describe",input:Fj}),LX=zi({type:"image:image-generate",input:qj}),Jj=c.object({sourceEntityType:c.string().min(1),sourceEntityId:c.string().min(1),attachmentType:c.string().min(1),imageId:c.string().min(1),dedupKey:c.string().min(1).optional(),replace:c.boolean().optional(),targetEntityType:c.string().min(1).optional(),targetEntityId:c.string().min(1).optional(),targetImageField:c.enum(["coverImageId","ogImageId"]).optional()}),ZX=zi({type:"image:image-render-source",input:Jj})});var Hj,jX,Vj,BX;var Wj=b(()=>{ue();Hj=c.object({sourceEntityType:c.string().min(1),sourceEntityId:c.string().min(1),attachmentType:c.string().min(1),documentId:c.string().min(1),title:c.string().min(1).optional(),filename:c.string().min(1).optional(),visibility:c.enum(["public","shared","restricted"]).optional()}),jX=zi({type:"document:generate",input:Hj}),Vj=c.object({documentId:c.string().min(1)}),BX=zi({type:"document:describe",input:Vj})});var UX;var Gj=b(()=>{ue();UX=c.enum(["none","low","medium","high","xhigh","max"])});var MX,Qj,qX;var Yj=b(()=>{ue();MX=c.object({}),Qj=c.object({userId:c.string().min(1),password:c.string().min(1)}),qX=he({channel:"matrix:bot-credentials",request:MX,response:Qj,delivery:"request"})});var JI;var Xj=b(()=>{JI=["core","media","automation","web","chat","site","publishing","federation","matrix","team"]});var sRe;var eB=b(()=>{ue();sRe=c.object({series:c.array(c.string()).optional(),publishedAt:c.string().optional()})});var wt=b(()=>{II();kL();$I();YL();eZ();jc();nZ();dZ();mZ();hZ();Rd();bZ();vZ();wZ();xZ();EZ();kZ();RZ();TZ();$Z();OZ();PZ();PI();NZ();DZ();ZZ();jZ();rg();BZ();jI();qZ();FZ();JZ();HZ();VZ();RI();WZ();QZ();YZ();XZ();nj();ij();cj();hj();gj();yj();wj();Aj();$j();Cj();zj();Pj();Nj();Zj();jj();Bj();Uj();Kj();Wj();Gj();Yj();Xj();eB()});var HX,VX,Ct,br,Gs,WX,Qs="capability-bundles-v1",KI,GX,QX,YX,XX,tB,ug,Ys,hn,eee,tee,ree,nee,oee,HI,iee,see,dg;var $o=b(()=>{wt();wt();ue();HX=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,VX=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Ct=c.string().regex(HX,"expected exact pinned version"),br=c.string().regex(VX,"expected lowercase handle slug"),Gs=c.string().min(1),WX=c.string().startsWith("age1").min(1),KI=c.enum(JI),GX=["professional","team","organization"],QX=c.enum(GX),YX=["person","team","organization"],XX=c.enum(YX),tB=c.array(KI).min(1),ug=c.array(c.string().min(1)),Ys=c.strictObject({brainVersion:Ct,bundleContract:c.literal(Qs),bundles:tB,add:ug.optional(),remove:ug.optional(),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),openaiApiKey:Gs,gitSyncToken:Gs,contentRepoAdminToken:Gs,agePublicKey:WX}).superRefine((e,t)=>{if(new Set(e.bundles).size!==e.bundles.length)t.addIssue({code:c.ZodIssueCode.custom,path:["bundles"],message:"canonical bundles must be unique"})}),hn=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),bundlesOverride:tB.optional(),addOverride:ug.optional(),removeOverride:ug.optional(),openaiApiKeyOverride:Gs.optional(),gitSyncTokenOverride:Gs.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:c.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"});if(e.bundlesOverride&&new Set(e.bundlesOverride).size!==e.bundlesOverride.length)t.addIssue({code:c.ZodIssueCode.custom,path:["bundlesOverride"],message:"canonical bundle overrides must be unique"})}),eee=c.strictObject({platform:lg,url:c.string().min(1),label:c.string().min(1).optional()}),tee=c.strictObject({name:c.string().min(1).optional(),description:c.string().min(1).optional(),website:c.string().min(1).optional(),email:c.string().min(1).optional(),story:c.string().min(1).optional(),socialLinks:c.array(eee).optional()}),ree=c.strictObject({delivery:c.literal("email"),email:c.string().email()}),nee=c.strictObject({enabled:c.boolean().optional(),endpoint:c.string().url().refine((e)=>new URL(e).protocol==="wss:",{message:"Jetstream endpoint must use wss"}).optional(),replayWindowSeconds:c.number().int().min(60).optional(),denyDids:c.array(c.string().startsWith("did:plc:")).optional(),denyDomains:c.array(c.string().min(1)).optional(),skillKeywords:c.array(c.string().min(1)).optional(),queueLimit:c.number().int().min(1).max(1e4).optional(),concurrency:c.number().int().min(1).max(32).optional(),perDidCooldownSeconds:c.number().int().nonnegative().optional(),fetchBudgetPerMinute:c.number().int().min(1).optional(),newAgentsPerHour:c.number().int().min(1).optional(),pendingCandidateCeiling:c.number().int().min(1).optional(),staleCandidateRetentionDays:c.number().int().min(1).optional(),requestTimeoutMs:c.number().int().min(100).optional(),maxResponseBytes:c.number().int().min(1024).optional(),maxRedirects:c.number().int().nonnegative().optional(),retryAttempts:c.number().int().min(1).optional(),heartbeatIntervalHours:c.number().min(1).optional()}),oee=c.strictObject({identifier:c.string().min(1),accountDid:c.string().min(1).optional(),lexiconAuthority:c.boolean().optional(),jetstream:nee.optional()}),HI=c.strictObject({package:c.string().min(1),version:Ct.optional(),theme:c.string().min(1).optional(),themeVersion:Ct.optional()}).superRefine((e,t)=>{let r=e.package.startsWith("@rizom/");if(r&&e.version===void 0)t.addIssue({code:c.ZodIssueCode.custom,path:["version"],message:"external @rizom site packages require an exact version pin"});if(!r&&e.version!==void 0)t.addIssue({code:c.ZodIssueCode.custom,path:["version"],message:"version is valid only for external @rizom site packages"});let o=e.theme?.startsWith("@rizom/")===!0;if(o&&e.themeVersion===void 0)t.addIssue({code:c.ZodIssueCode.custom,path:["themeVersion"],message:"external @rizom themes require an exact version pin"});if(!o&&e.themeVersion!==void 0)t.addIssue({code:c.ZodIssueCode.custom,path:["themeVersion"],message:"themeVersion is valid only for external @rizom themes"})}),iee=c.strictObject({onboarding:c.boolean().optional()}),see=c.record(c.string().min(1),c.record(c.string(),c.unknown())),dg=c.strictObject({handle:br,discord:c.strictObject({enabled:c.boolean(),anchorUserId:c.string().min(1).optional()}),openaiApiKeyOverride:Gs.optional(),gitSyncTokenOverride:Gs.optional(),domainOverride:c.string().min(1).optional(),cloudflareZoneId:c.string().min(1).optional(),contentRepoOverride:c.string().min(1).optional(),profileKind:QX.optional(),anchorKind:XX.optional(),plugins:see.optional(),spaces:c.array(c.string().min(1)).optional(),embeddingEnabled:c.boolean().optional(),embeddingModel:c.string().optional(),topicExtractionEnabled:c.boolean().optional(),skillDerivationEnabled:c.boolean().optional(),swotDerivationEnabled:c.boolean().optional(),addOverride:c.array(c.string().min(1)).optional(),removeOverride:c.array(c.string().min(1)).optional(),siteOverride:HI.optional(),setup:ree.optional(),atproto:oee.optional(),playbooks:iee.optional(),anchorProfile:tee.optional()})});import{access as aee}from"fs/promises";async function Ir(e){try{return await aee(e),!0}catch{return!1}}function Uc(e){return e.replaceAll("\\","/")}var Xs=()=>{};import{readdir as cee,readFile as lee}from"fs/promises";import{basename as VI,join as zd,relative as uee}from"path";async function xt(e,t={}){let[r,o,n]=await Promise.all([WI(zd(e,"pilot.yaml"),Ys),pee(e),fee(e)]),i=mee(o,n),s=n.map((l)=>({id:l.id,members:[...l.data.members].sort(),...Oc({brainVersionOverride:l.data.brainVersionOverride,bundlesOverride:l.data.bundlesOverride,addOverride:l.data.addOverride,removeOverride:l.data.removeOverride,openaiApiKeyOverride:l.data.openaiApiKeyOverride,gitSyncTokenOverride:l.data.gitSyncTokenOverride})})).sort((l,u)=>l.id.localeCompare(u.id)),a=await Promise.all(o.map(async(l)=>{let u=i.get(l.data.handle);if(!u)throw new ea(`User ${l.data.handle} must belong to exactly one cohort`);let d={...dee(l.data,u,r),snapshotStatus:await yee(e,l.data.handle)},p=await t.resolveStatus?.(d);return{...d,serverStatus:p?.serverStatus??"unknown",deployStatus:p?.deployStatus??"unknown",dnsStatus:p?.dnsStatus??"unknown",mcpStatus:p?.mcpStatus??"unknown"}}));return a.sort((l,u)=>l.handle.localeCompare(u.handle)),{pilot:r,cohorts:s,users:a}}function dee(e,t,r){let o=t.data.bundlesOverride===void 0;return{handle:e.handle,cohort:t.id,brainVersion:t.data.brainVersionOverride??r.brainVersion,bundleContract:r.bundleContract,bundles:[...t.data.bundlesOverride??r.bundles],add:rB(t.data.addOverride??(o?r.add:void 0),e.addOverride),remove:rB(t.data.removeOverride??(o?r.remove:void 0),e.removeOverride),domain:e.domainOverride??`${e.handle}${r.domainSuffix}`,...Oc({cloudflareZoneId:e.cloudflareZoneId}),contentRepo:e.contentRepoOverride??`${r.contentRepoPrefix}${e.handle}-content`,...Oc({profileKind:e.profileKind,anchorKind:e.anchorKind,embeddingEnabled:e.embeddingEnabled,embeddingModel:e.embeddingModel,spaces:e.spaces,plugins:e.plugins,topicExtractionEnabled:e.topicExtractionEnabled,skillDerivationEnabled:e.skillDerivationEnabled,swotDerivationEnabled:e.swotDerivationEnabled,siteOverride:e.siteOverride&&{...e.siteOverride}}),discordEnabled:e.discord.enabled,...Oc({discordAnchorUserId:e.discord.anchorUserId}),effectiveOpenaiApiKey:e.openaiApiKeyOverride??t.data.openaiApiKeyOverride??r.openaiApiKey,effectiveGitSyncToken:e.gitSyncTokenOverride??t.data.gitSyncTokenOverride??r.gitSyncToken,...Oc({setup:e.setup,atproto:e.atproto,playbooks:e.playbooks}),anchorProfile:hee(e.handle,e.anchorProfile)}}function rB(e,t){return bee([...e??[],...t??[]])}async function pee(e){let t=zd(e,"users"),r=(await nB(t)).filter((n)=>!VI(n).endsWith(".secrets.yaml"));return(await Promise.all(r.map(async(n)=>{let i=oB(VI(n)),s=await WI(n,dg);if(s.handle!==i){let a=Uc(uee(e,n));throw new ea(`${a} must declare handle: ${i}`)}return{id:i,data:s}}))).sort((n,i)=>n.id.localeCompare(i.id))}async function fee(e){let t=zd(e,"cohorts"),r=await nB(t);return(await Promise.all(r.map(async(n)=>({id:oB(VI(n)),data:await WI(n,hn)})))).sort((n,i)=>n.id.localeCompare(i.id))}function mee(e,t){let r=new Map(e.map((n)=>[n.data.handle,n])),o=new Map;for(let n of t)for(let i of n.data.members){if(!r.has(i))throw new ea(`Cohort ${n.id} references unknown user ${i}`);if(o.has(i))throw new ea(`User ${i} must belong to exactly one cohort`);o.set(i,n)}for(let n of e)if(!o.has(n.data.handle))throw new ea(`User ${n.data.handle} must belong to exactly one cohort`);return o}function hee(e,t){return{name:t?.name??gee(e),...t?.description?{description:t.description}:{},...t?.website?{website:t.website}:{},...t?.email?{email:t.email}:{},...t?.story?{story:t.story}:{},...t?.socialLinks?{socialLinks:t.socialLinks.map((r)=>({platform:r.platform,url:r.url,...r.label?{label:r.label}:{}}))}:{}}}function gee(e){return e.split("-").filter((t)=>t.length>0).map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async function yee(e,t){let r=zd(e,"users",t,"brain.yaml");return await Ir(r)?"present":"missing"}async function nB(e){return(await cee(e,{withFileTypes:!0})).filter((r)=>r.isFile()&&r.name.endsWith(".yaml")).map((r)=>zd(e,r.name)).sort((r,o)=>r.localeCompare(o))}async function WI(e,t){let r=await lee(e,"utf8"),o=yr(r,t);if(!o.ok)throw new ea(`${Uc(e)}: ${o.error}`);return o.data}function bee(e){return[...new Set(e)]}function oB(e){return e.replace(/\.ya?ml$/,"")}var ea;var gn=b(()=>{Vn();$o();Xs();ea=class ea extends Error{}});import{mkdir as Eee,writeFile as Aee}from"fs/promises";import{join as cB}from"path";async function Pi(e,t={}){let o=(t.registry??await xt(e,t)).users.map((i)=>{let s=i.discordEnabled?"on":"off";return[i.handle,i.cohort,i.bundles.join(","),i.add.join(","),i.remove.join(","),i.brainVersion,i.domain,i.contentRepo,s,i.serverStatus,i.deployStatus,i.dnsStatus,i.mcpStatus]}),n=["<!-- generated by brains-ops; do not edit -->","",Iee,kee,...o.map((i)=>`| ${i.join(" | ")} |`),""].join(`
|
|
283
284
|
`);await Eee(cB(e,"views"),{recursive:!0}),await Aee(cB(e,"views","users.md"),n)}var Iee="| handle | cohort | bundles | add | remove | brainVersion | domain | contentRepo | discord | serverStatus | deployStatus | dnsStatus | mcpStatus |",kee="| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |";var Pd=b(()=>{gn()});var pB=b(()=>{Mn()});function Nd(e){if(e===null||typeof e!=="object"||Array.isArray(e))return!1;let t=Wee(e);return t===Object.prototype||t===null}function Gee(e){return e instanceof Error&&"code"in e&&typeof e.code==="string"}function fg(e){return Gee(e)&&e.code==="ENOENT"}var Wee;var Dd=b(()=>{Wee=Object.getPrototypeOf});import{lstat as ek,mkdir as fB,readFile as mB,unlink as Qee,writeFile as hB}from"fs/promises";import{join as yn}from"path";import{isDeepStrictEqual as Yee}from"util";function SB(e){return yn("deploy","runtime",Xee.parse(e.tag))}function vB(e){let t={"@rizom/brain":Ct.parse(e.brainVersion)};for(let r of[...e.sitePackages].sort()){let o=r.lastIndexOf("@"),n=yB.parse(r.slice(0,o)),i=Ct.parse(r.slice(o+1));if(t[n]!==void 0&&t[n]!==i)throw Error(`Conflicting runtime dependency pin: ${r}`);t[n]=i}return bB.parse({name:"rover-pilot-runtime",private:!0,packageManager:"bun@1.4.0",dependencies:t,overrides:{"postcss-selector-parser":"7.1.6"}})}async function tk(e){try{return await ek(e),!0}catch(t){if(fg(t))return!1;throw t}}async function gB(e){if(!(await ek(e)).isFile())throw Error(`Runtime lock input must be a regular file: ${e}`)}async function wB(e){if(!(await ek(e)).isDirectory())throw Error(`Runtime lock input must be a directory: ${e}`)}async function xB(e){for(let t of["deploy",yn("deploy","runtime")]){let r=yn(e,t);if(await tk(r))await wB(r)}}async function XI(e,t){let r=yn(e,"package.json"),o=yn(e,"bun.lock");await gB(r),await gB(o);let n=bB.parse(JSON.parse(await mB(r,"utf8")));if(!Yee(n,vB(t)))throw Error(`Runtime dependency manifest does not match ${t.tag}`);if(!(await mB(o,"utf8")).trim())throw Error(`Empty runtime dependency lock: ${o}`)}async function _B(e,t){await xB(e);let r=yn(e,SB(t));if(await wB(r),await tk(yn(r,".incomplete")))throw Error(`Incomplete runtime dependency lock: ${r}`);await XI(r,t)}async function EB(e,t,r=tr){if(Bun.version!=="1.4.0")throw Error("Runtime dependency locks must be generated with Bun 1.4.0");let o=vB(t);await xB(e);let n=yn(e,SB(t));if(await tk(n))return await _B(e,t),"existing";await fB(yn(e,"deploy","runtime"),{recursive:!0}),await fB(n);let i=yn(n,".incomplete");return await hB(i,`Runtime dependency resolution has not completed.
|
|
284
285
|
`,{flag:"wx"}),await hB(yn(n,"package.json"),`${JSON.stringify(o,null,2)}
|
|
285
286
|
`,{flag:"wx"}),await r(process.execPath,["install","--lockfile-only","--ignore-scripts"],{cwd:n}),await XI(n,t),await r(process.execPath,["install","--frozen-lockfile","--ignore-scripts","--dry-run"],{cwd:n}),await XI(n,t),await Qee(i),"created"}var Xee,yB,bB;var rk=b(()=>{Dd();ue();$o();Mn();Xee=c.string().regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$/),yB=c.string().regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/),bB=c.strictObject({name:c.literal("rover-pilot-runtime"),private:c.literal(!0),packageManager:c.literal("bun@1.4.0"),dependencies:c.record(yB,Ct),overrides:c.strictObject({"postcss-selector-parser":c.literal("7.1.6")})})});function mg(e,t=[]){let r=`brain-${e}`,o=[...new Set(t)].sort();if(o.length===0)return r;let n=`${r}--${o.map((a)=>a.replace(/^@/,"").replace("/","-").replace(/@(?=[^@]*$)/,"-")).join("--")}`,s=`--s${eg(JSON.stringify([e,...o])).slice(0,12)}`;return`${n.length+s.length<=ete?n:r}${s}`}function nk(e){if(!e)return[];return[AB(e.package,e.version),AB(e.theme,e.themeVersion)].filter((t)=>t!==void 0)}function AB(e,t){if(!e?.startsWith("@rizom/"))return;if(t===void 0)throw Error(`Package ${e} has no explicit version pin`);return`${e}@${t}`}function tte(e){let t=new Map;for(let r of e){let o=[...new Set(nk(r.siteOverride))].sort(),n=mg(r.brainVersion,o),i=t.get(n);if(i&&(i.brainVersion!==r.brainVersion||!Bun.deepEquals(i.sitePackages,o)))throw Error(`Image tag collision for distinct runtime requirements: ${n}`);t.set(n,{tag:n,brainVersion:r.brainVersion,sitePackages:o})}return[...t.values()].sort((r,o)=>r.tag.localeCompare(o.tag))}function rte(e,t){let r=new Map;for(let o of[...e,...t]){let n=o.lastIndexOf("@"),i=n>0?o.slice(0,n):o,s=r.get(i);if(s&&s!==o)throw Error(`Fleet shared images have conflicting pins for ${i}: ${s} and ${o}`);r.set(i,o)}return[...r.values()].sort()}async function IB(e){let t=e.brainVersionInput?.trim()??"";if(t){let o=rte([],(e.sitePackagesInput??"").split(/\s+/).filter(Boolean)),n=mg(t,o);if(!e.allowTagOverwrite&&await e.imageExists(n))throw Error(`Image tag ${n} already exists; published tags are immutable. Pick a new version, or pass overwrite=true only when replacing a tag whose containers were never deployed.`);return[{tag:n,brainVersion:t,sitePackages:o}]}let r=[];for(let o of tte(e.users))if(!await e.imageExists(o.tag))r.push(o);else await e.verifyImage(o);return r}var ete=128;var ok=b(()=>{pB();rk();gn();Mn();tg()});function ik(e,t){let r=e.indexOf("/");if(r===-1)return{org:t,name:e};return{org:e.slice(0,r),name:e.slice(r+1)}}function $B(e,t){let{org:r,name:o}=ik(e,t);return`${r}/${o}`}import{mkdtemp as ste,mkdir as ate,readFile as cte,rm as lte,writeFile as ute}from"fs/promises";import{tmpdir as dte}from"os";import{dirname as pte,join as zB}from"path";async function PB(e,t,r,o,n={}){if(o.length===0)return;let i=n.env??process.env,s=Lr(e),a=OB(i,s,r.effectiveGitSyncToken),l=n.contentRepoAdminTokenSelector?OB(i,s,n.contentRepoAdminTokenSelector):void 0,u=ik(r.contentRepo,t),d=n.contentRepoRemoteResolver?.(r,t,a)??gte(u,a);if(!d)return;let p=await ste(zB(dte(),`brains-ops-content-sync-${r.handle}-`)),m=n.runCommand??tr,h=n.fetchImpl??fetch;try{if(!n.contentRepoRemoteResolver){if(!l)throw Error(`${n.contentRepoAdminTokenSelector??"CONTENT_REPO_ADMIN_TOKEN"} is required to check or create content repos`);await yte(u,l,h)}await m("git",["clone",d,p]),await bte(p,m),await m("git",["config","user.name","brains-ops[bot]"],{cwd:p}),await m("git",["config","user.email","41898282+github-actions[bot]@users.noreply.github.com"],{cwd:p});let S=!1;for(let y of o)if(await mte(p,y))S=!0;if(!S)return;await m("git",["add","."],{cwd:p}),await m("git",["commit","-m",`chore(content): seed ${r.handle} anchor profile`],{cwd:p}),await m("git",["push","origin","HEAD:main"],{cwd:p})}finally{await lte(p,{recursive:!0,force:!0})}}async function mte(e,t){let r=zB(e,t.path),o=await cte(r,"utf8").catch(()=>{return});if(o===t.content)return!1;if(o!==void 0&&!hte(o))return!1;return await ate(pte(r),{recursive:!0}),await ute(r,t.content),!0}function hte(e){return fte.some((t)=>e.includes(t))}function OB(e,t,r){return jt(r,e,t)}function gte(e,t){if(!t)return;return`https://x-access-token:${encodeURIComponent(t)}@github.com/${e.org}/${e.name}.git`}async function yte(e,t,r){let{org:o,name:n}=e,s=`https://api.github.com/repos/${`${encodeURIComponent(o)}/${encodeURIComponent(n)}`}`,a={Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"User-Agent":"brains-ops","X-GitHub-Api-Version":"2022-11-28"},l=await r(s,{headers:a});if(l.ok)return;if(l.status!==404)throw Error(`Failed to check GitHub repo ${o}/${n}: ${l.status} ${await CB(l)}`);let u=await r(`https://api.github.com/orgs/${encodeURIComponent(o)}/repos`,{method:"POST",headers:a,body:JSON.stringify({name:n,private:!0,auto_init:!1})});if(u.ok){console.log(`Created missing content repo ${o}/${n}`);return}if(u.status===422){if((await r(s,{headers:a})).ok)return}throw Error(`Failed to create GitHub repo ${o}/${n}: ${u.status} ${await CB(u)}`)}async function CB(e){let t=await e.text();return t.trim().length===0?e.statusText:t}async function bte(e,t){try{await t("git",["checkout","-B","main","origin/main"],{cwd:e})}catch{await t("git",["checkout","-B","main"],{cwd:e})}}var fte;var NB=b(()=>{wi();Mn();fte=["name: Your Name Here","Delete this and write your own"]});function sk(e,t,r={}){let o={...e};for(let n of Object.keys(t)){let i=t[n];if(i===null&&r.nulls!=="preserve")delete o[n];else if(Nd(o[n])&&Nd(i))o[n]=sk(o[n],i,r);else o[n]=i}return o}var DB=b(()=>{Dd()});function hg(e){return async(t)=>({brainYaml:Ste(t,e),envFile:xte(t,e),contentRepoFiles:vte(t)})}function Ste(e,t){let r={...e.setup?.delivery==="email"?{"auth-service":{setupEmail:e.setup.email},notifications:{defaultRecipient:{type:"email",address:e.setup.email}},email:{transport:"resend",apiKey:"${MAIL_API_KEY}",from:"${MAIL_FROM}"}}:{},...e.playbooks?.onboarding?{onboarding:{enabled:!0}}:{},...e.topicExtractionEnabled!==void 0?{topics:{enableAutoExtraction:e.topicExtractionEnabled}}:{},...e.skillDerivationEnabled!==void 0?{agents:{enableSkillDerivation:e.skillDerivationEnabled}}:{},...e.swotDerivationEnabled!==void 0?{assessment:{enableSwotDerivation:e.swotDerivationEnabled}}:{},"directory-sync":{git:{repo:LB(e,t),authToken:"${GIT_SYNC_TOKEN}"}},...e.atproto?{atproto:{...e.atproto,appPassword:"${ATPROTO_APP_PASSWORD}"}}:{}};return Nc({brain:"brain",bundleContract:e.bundleContract,kind:e.profileKind??"professional",domain:e.domain,bundles:e.bundles,...e.anchorKind?{anchor:e.anchorKind}:{},...e.embeddingEnabled!==void 0?{embedding:{enabled:e.embeddingEnabled}}:{},...e.embeddingModel?{embeddingModel:e.embeddingModel}:{},...e.add.length>0?{add:e.add}:{},...e.remove.length>0?{remove:e.remove}:{},...e.siteOverride?{site:{package:e.siteOverride.package,...e.siteOverride.theme?{theme:e.siteOverride.theme}:{}}}:{},...e.spaces&&e.spaces.length>0?{spaces:e.spaces}:{},anchors:e.discordEnabled&&e.discordAnchorUserId?[`discord:${e.discordAnchorUserId}`]:[],plugins:sk(r,e.plugins??{},{nulls:"preserve"})})}function LB(e,t){return $B(e.contentRepo,t)}function vte(e){return[{path:"anchor-profile/anchor-profile.md",content:wte(e)}]}function wte(e){let t={name:e.anchorProfile.name,...e.anchorProfile.description?{description:e.anchorProfile.description}:{},...e.anchorProfile.website?{website:e.anchorProfile.website}:{},...e.anchorProfile.email?{email:e.anchorProfile.email}:{},...e.anchorProfile.socialLinks?{socialLinks:e.anchorProfile.socialLinks}:{}},r=e.anchorProfile.story??"This profile was initialized by brains-ops. Edit it in your content repo.";return`---
|
|
@@ -288,19 +289,19 @@ ${Nc(t).trimEnd()}
|
|
|
288
289
|
|
|
289
290
|
${r}
|
|
290
291
|
`}function xte(e,t){let r=nk(e.siteOverride);return[`BRAIN_VERSION=${e.brainVersion}`,...r.length>0?[`IMAGE_TAG=${mg(e.brainVersion,r)}`]:[],`CONTENT_REPO=${LB(e,t)}`,""].join(`
|
|
291
|
-
`)}var ak=b(()=>{DB();ok();Vn()});import{mkdir as _te,writeFile as Ete}from"fs/promises";import{dirname as Ate,join as ZB}from"path";import{isDeepStrictEqual as Ite}from"util";async function qc(e,t,r,o,n={}){let i=hg(t.pilot.githubOrg);for(let s of r){let a={};if(o){let m=await o(s);if(m!==void 0)a=m}let l=await i(s),u=a.brainYaml??l.brainYaml,d=a.envFile??l.envFile,p=a.contentRepoFiles??l.contentRepoFiles??[];if(d)await ck(e,s.handle,".env",d);if(u)await ck(e,s.handle,"brain.yaml",u);await PB(e,t.pilot.githubOrg,s,p,{contentRepoAdminTokenSelector:t.pilot.contentRepoAdminToken,...n});for(let m of p)await ck(e,s.handle,ZB("content",m.path),m.content)}}async function ck(e,t,r,o){let n=ZB(e,"users",t,r),i=Bun.file(n);if(r==="brain.yaml"&&await i.exists()){let s=yr(await i.text()),a=yr(o);if(s.ok&&a.ok&&Ite(s.data,a.data))return}await _te(Ate(n),{recursive:!0}),await Ete(n,o)}async function gg(e,t){let r=await xt(e),o=r.users.find((n)=>n.handle===t);if(!o)throw Error(`Unknown user handle: ${t}`);return{registry:r,user:o}}async function jB(e,t){let r=await xt(e),o=r.cohorts.find((n)=>n.id===t);if(!o)throw Error(`Unknown cohort: ${t}`);return{registry:r,users:r.users.filter((n)=>n.cohort===o.id)}}async function BB(e){let t=await xt(e);return{registry:t,users:t.users}}var Zd=b(()=>{Vn();NB();ak();gn()});function HB(e){return Object.keys(e)}import{readFileSync as Bd}from"fs";import{rm as Mte,writeFile as QB}from"fs/promises";import{join as uk,relative as VB}from"path";async function XB(e,t,r={}){let{registry:o,user:n}=await gg(e,t),i=r.env??process.env,s=r.logger??console.log,a=Lr(e),l=uk(e,"users",`${t}.secrets.yaml.age`),u=uk(e,"users",`${t}.secrets.yaml`),d=Uc(VB(e,l)),p=Uc(VB(e,u)),m=
|
|
292
|
-
`;
|
|
293
|
-
`);await QB(e,r,{flag:"wx"})}var YB;var fk=b(()=>{yi();wi();Vn();ue();Lv();Zd();Xs();YB=c.strictObject({gitSyncToken:c.string().min(1).optional(),discordBotToken:c.string().min(1).optional(),discordPublicKey:c.string().min(1).optional(),discordApplicationId:c.string().min(1).optional(),openaiApiKey:c.string().min(1).optional(),atprotoAppPassword:c.string().min(1).optional(),certificatePem:c.string().min(1).optional(),privateKeyPem:c.string().min(1).optional()})});var iU=()=>{};function sU(e){return`${e.slice(0,1).toUpperCase()}${e.slice(1)}`}var vg=b(()=>{iU()});var mU={};Lt(mU,{upgradePilotRepo:()
|
|
294
|
-
`)}}Xr.defaultYaml={explicit:!1,version:"1.2"};Xr.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
292
|
+
`)}var ak=b(()=>{DB();ok();Vn()});import{mkdir as _te,writeFile as Ete}from"fs/promises";import{dirname as Ate,join as ZB}from"path";import{isDeepStrictEqual as Ite}from"util";async function qc(e,t,r,o,n={}){let i=hg(t.pilot.githubOrg);for(let s of r){let a={};if(o){let m=await o(s);if(m!==void 0)a=m}let l=await i(s),u=a.brainYaml??l.brainYaml,d=a.envFile??l.envFile,p=a.contentRepoFiles??l.contentRepoFiles??[];if(d)await ck(e,s.handle,".env",d);if(u)await ck(e,s.handle,"brain.yaml",u);await PB(e,t.pilot.githubOrg,s,p,{contentRepoAdminTokenSelector:t.pilot.contentRepoAdminToken,...n});for(let m of p)await ck(e,s.handle,ZB("content",m.path),m.content)}}async function ck(e,t,r,o){let n=ZB(e,"users",t,r),i=Bun.file(n);if(r==="brain.yaml"&&await i.exists()){let s=yr(await i.text()),a=yr(o);if(s.ok&&a.ok&&Ite(s.data,a.data))return}await _te(Ate(n),{recursive:!0}),await Ete(n,o)}async function gg(e,t){let r=await xt(e),o=r.users.find((n)=>n.handle===t);if(!o)throw Error(`Unknown user handle: ${t}`);return{registry:r,user:o}}async function jB(e,t){let r=await xt(e),o=r.cohorts.find((n)=>n.id===t);if(!o)throw Error(`Unknown cohort: ${t}`);return{registry:r,users:r.users.filter((n)=>n.cohort===o.id)}}async function BB(e){let t=await xt(e);return{registry:t,users:t.users}}var Zd=b(()=>{Vn();NB();ak();gn()});function HB(e){return Object.keys(e)}import{readFileSync as Bd}from"fs";import{rm as Mte,writeFile as QB}from"fs/promises";import{join as uk,relative as VB}from"path";async function XB(e,t,r={}){let{registry:o,user:n}=await gg(e,t),i=r.env??process.env,s=r.logger??console.log,a=Lr(e),l=uk(e,"users",`${t}.secrets.yaml.age`),u=uk(e,"users",`${t}.secrets.yaml`),d=Uc(VB(e,l)),p=Uc(VB(e,u)),m=Kte(u),h=await Hte(l,e,i,a),S=await Ir(u),y={sharedOpenaiApiKeySelector:o.pilot.openaiApiKey,sharedGitSyncTokenSelector:o.pilot.gitSyncToken,effectiveOpenaiApiKeySelector:n.effectiveOpenaiApiKey,effectiveGitSyncTokenSelector:n.effectiveGitSyncToken,discordEnabled:n.discordEnabled},v;try{v=qte(e,i,a,m,h,y)}catch(P){if(!r.dryRun&&m===void 0&&P instanceof Error){let K=Wte(y);if(K.length>0)throw await Gte(u,K),Error(`Missing required secrets for ${t}. Created ${p}; fill it in and rerun secrets:encrypt. ${P.message}`,{cause:P})}throw P}let x=`${Nc(v).trimEnd()}
|
|
293
|
+
`;Vte(x,v);let _=HB(v);if(r.dryRun){if(s(`Dry run: would encrypt ${_.length} secrets to ${d}.`),s(_.length>0?`Keys: ${_.join(", ")}`:"Keys: (none \u2014 shared defaults only)"),S)s(`Would remove plaintext file ${p}.`);return{encryptedPath:d,plaintextPath:p,deletedPlaintext:S,encryptedKeys:_,dryRun:!0}}let k=new zu;k.addRecipient(o.pilot.agePublicKey);let O=await k.encrypt(x),L=bi.encode(O);if(await QB(l,L),await Mte(u,{force:!0}),s(`Encrypted ${_.length} secrets to ${d}.`),S)s(`Removed plaintext file ${p}.`);return{encryptedPath:d,plaintextPath:p,deletedPlaintext:S,encryptedKeys:_}}function qte(e,t,r,o,n,i){let s=WB(e,t,r,o,n,"openaiApiKey",i.effectiveOpenaiApiKeySelector,i.sharedOpenaiApiKeySelector),a=WB(e,t,r,o,n,"gitSyncToken",i.effectiveGitSyncTokenSelector,i.sharedGitSyncTokenSelector),l=i.discordEnabled?bg(e,t,r,o,n,"discordBotToken","DISCORD_BOT_TOKEN"):void 0,u=i.discordEnabled?bg(e,t,r,o,n,"discordPublicKey","DISCORD_PUBLIC_KEY"):void 0,d=i.discordEnabled?bg(e,t,r,o,n,"discordApplicationId","DISCORD_APPLICATION_ID"):void 0,p=Sg(e,t,r,o,n,"atprotoAppPassword","ATPROTO_APP_PASSWORD"),m=Fte(o,n,"resendApiKey"),h=GB(Sg(e,t,r,o,n,"certificatePem","CERTIFICATE_PEM")),S=GB(Sg(e,t,r,o,n,"privateKeyPem","PRIVATE_KEY_PEM"));return YB.parse({...s?{openaiApiKey:s}:{},...a?{gitSyncToken:a}:{},...l?{discordBotToken:l}:{},...u?{discordPublicKey:u}:{},...d?{discordApplicationId:d}:{},...p?{atprotoAppPassword:p}:{},...m?{resendApiKey:m}:{},...h?{certificatePem:h}:{},...S?{privateKeyPem:S}:{}})}function WB(e,t,r,o,n,i,s,a){if(s===a)return;return bg(e,t,r,o,n,i,s)}function bg(e,t,r,o,n,i,s){let a=Sg(e,t,r,o,n,i,s);if(a===void 0||a.trim().length===0)throw Error(`Missing required secret value for ${String(i)}. Set it in users/<handle>.secrets.yaml or fall back to ${s}/${s}_FILE before running secrets:encrypt.`);return a}function GB(e){return e?.replace(/\r\n?|\n/g,"\\n")}function Sg(e,t,r,o,n,i,s){return Jte(o,n,i,s,t,r,e)}function Fte(e,t,r){return[e?.[r],t?.[r]].find((o)=>o!==void 0&&o.trim().length>0)}function Jte(e,t,r,o,n,i,s){let a=e?.[r];if(a!==void 0&&a.trim().length>0)return a;let l=jt(`${o}_FILE`,n,i);if(l&&l.trim().length>0)return Bd(vi(l,s),"utf8");let u=jt(o,n,i);if(u!==void 0&&u.trim().length>0)return u;let d=t?.[r];if(d!==void 0&&d.trim().length>0)return d;return}function Kte(e){let t;try{t=Bd(e,"utf8")}catch{return}try{return pk(t)}catch(r){throw Error(`Unable to parse plaintext secrets file ${e}: ${Ve(r)}`,{cause:r})}}async function Hte(e,t,r,o){if(!await Ir(e))return;let n=dk(t,r,o);if(!n)return;let i;try{let s=Bd(e,"utf8"),a=bi.decode(s),l=new Pu;l.addIdentity(n),i=await l.decrypt(a,"text")}catch{return}try{return pk(i)}catch(s){throw Error(`Unable to parse decrypted secrets from ${e}: ${Ve(s)}`,{cause:s})}}function dk(e,t,r){let o=jt("AGE_SECRET_KEY_FILE",t,r);if(o&&o.trim().length>0)return Du(Bd(vi(o,e),"utf8"));let n=jt("AGE_SECRET_KEY",t,r);if(n&&n.trim().length>0)return Du(n);try{return Du(Bd(uk(e,".brains-ops","age","identity.txt"),"utf8"))}catch{return}}function pk(e){let t=yL(e),r={};if(t!==null&&typeof t==="object"&&!Array.isArray(t)){for(let[o,n]of Object.entries(t))if(typeof n==="string")r[o]=n}return YB.partial().parse(r)}function Vte(e,t){let r={...t},o={...pk(e)},n=new Set([...Object.keys(r),...Object.keys(o)]);for(let i of n)if(r[i]!==o[i])throw Error(`secrets:encrypt round-trip verification failed for ${i}; refusing to write a corrupted encrypted payload`)}function Wte(e){return[...e.effectiveOpenaiApiKeySelector!==e.sharedOpenaiApiKeySelector?["openaiApiKey"]:[],...e.effectiveGitSyncTokenSelector!==e.sharedGitSyncTokenSelector?["gitSyncToken"]:[],...e.discordEnabled?["discordBotToken","discordPublicKey","discordApplicationId"]:[]]}async function Gte(e,t){let r=["# local per-user secret staging file","# fill values, run `bunx brains-ops secrets:encrypt . <handle>`, then the plaintext file will be removed",...t.map((o)=>`${o}: `),""].join(`
|
|
294
|
+
`);await QB(e,r,{flag:"wx"})}var YB;var fk=b(()=>{yi();wi();Vn();ue();Lv();Zd();Xs();YB=c.strictObject({gitSyncToken:c.string().min(1).optional(),discordBotToken:c.string().min(1).optional(),discordPublicKey:c.string().min(1).optional(),discordApplicationId:c.string().min(1).optional(),openaiApiKey:c.string().min(1).optional(),atprotoAppPassword:c.string().min(1).optional(),resendApiKey:c.string().min(1).optional(),certificatePem:c.string().min(1).optional(),privateKeyPem:c.string().min(1).optional()})});var iU=()=>{};function sU(e){return`${e.slice(0,1).toUpperCase()}${e.slice(1)}`}var vg=b(()=>{iU()});var mU={};Lt(mU,{upgradePilotRepo:()=>Ore});import{readFile as kre}from"fs/promises";import{join as Rre}from"path";async function fU(e){let t=Rre(e,"package.json"),o=Tre.parse(JSON.parse(await kre(t,"utf8"))).devDependencies?.["@rizom/ops"];if(!o)throw Error(`${t} does not pin @rizom/ops as a devDependency`);return o}async function $re(e,t){let o=await Bun.spawn(e,{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(o!==0)throw Error(`${e.join(" ")} failed with exit ${o}`)}async function Ore(e,t={}){let r=t.exec??$re,o=await fU(e),n=t.version??"latest";await r(["bun","add","--dev","--exact",`@rizom/ops@${n}`],e);let i=await fU(e);return await r(["bun","x","brains-ops","init","."],e),{from:o,to:i}}var Tre;var hU=b(()=>{ue();Tre=c.object({devDependencies:c.record(c.string(),c.string()).optional()})});var qe=ye(function(jre){var gk=Symbol.for("yaml.alias"),gU=Symbol.for("yaml.document"),xg=Symbol.for("yaml.map"),yU=Symbol.for("yaml.pair"),yk=Symbol.for("yaml.scalar"),_g=Symbol.for("yaml.seq"),Oo=Symbol.for("yaml.node.type"),Cre=(e)=>!!e&&typeof e==="object"&&e[Oo]===gk,zre=(e)=>!!e&&typeof e==="object"&&e[Oo]===gU,Pre=(e)=>!!e&&typeof e==="object"&&e[Oo]===xg,Nre=(e)=>!!e&&typeof e==="object"&&e[Oo]===yU,bU=(e)=>!!e&&typeof e==="object"&&e[Oo]===yk,Dre=(e)=>!!e&&typeof e==="object"&&e[Oo]===_g;function SU(e){if(e&&typeof e==="object")switch(e[Oo]){case xg:case _g:return!0}return!1}function Lre(e){if(e&&typeof e==="object")switch(e[Oo]){case gk:case xg:case yk:case _g:return!0}return!1}var Zre=(e)=>(bU(e)||SU(e))&&!!e.anchor;jre.ALIAS=gk;jre.DOC=gU;jre.MAP=xg;jre.NODE_TYPE=Oo;jre.PAIR=yU;jre.SCALAR=yk;jre.SEQ=_g;jre.hasAnchor=Zre;jre.isAlias=Cre;jre.isCollection=SU;jre.isDocument=zre;jre.isMap=Pre;jre.isNode=Lre;jre.isPair=Nre;jre.isScalar=bU;jre.isSeq=Dre});var Ud=ye(function(rne){var zt=qe(),kr=Symbol("break visit"),vU=Symbol("skip children"),Yn=Symbol("remove node");function Eg(e,t){let r=wU(t);if(zt.isDocument(e)){if(Jc(null,e.contents,r,Object.freeze([e]))===Yn)e.contents=null}else Jc(null,e,r,Object.freeze([]))}Eg.BREAK=kr;Eg.SKIP=vU;Eg.REMOVE=Yn;function Jc(e,t,r,o){let n=xU(e,t,r,o);if(zt.isNode(n)||zt.isPair(n))return _U(e,o,n),Jc(e,n,r,o);if(typeof n!=="symbol"){if(zt.isCollection(t)){o=Object.freeze(o.concat(t));for(let i=0;i<t.items.length;++i){let s=Jc(i,t.items[i],r,o);if(typeof s==="number")i=s-1;else if(s===kr)return kr;else if(s===Yn)t.items.splice(i,1),i-=1}}else if(zt.isPair(t)){o=Object.freeze(o.concat(t));let i=Jc("key",t.key,r,o);if(i===kr)return kr;else if(i===Yn)t.key=null;let s=Jc("value",t.value,r,o);if(s===kr)return kr;else if(s===Yn)t.value=null}}return n}async function Ag(e,t){let r=wU(t);if(zt.isDocument(e)){if(await Kc(null,e.contents,r,Object.freeze([e]))===Yn)e.contents=null}else await Kc(null,e,r,Object.freeze([]))}Ag.BREAK=kr;Ag.SKIP=vU;Ag.REMOVE=Yn;async function Kc(e,t,r,o){let n=await xU(e,t,r,o);if(zt.isNode(n)||zt.isPair(n))return _U(e,o,n),Kc(e,n,r,o);if(typeof n!=="symbol"){if(zt.isCollection(t)){o=Object.freeze(o.concat(t));for(let i=0;i<t.items.length;++i){let s=await Kc(i,t.items[i],r,o);if(typeof s==="number")i=s-1;else if(s===kr)return kr;else if(s===Yn)t.items.splice(i,1),i-=1}}else if(zt.isPair(t)){o=Object.freeze(o.concat(t));let i=await Kc("key",t.key,r,o);if(i===kr)return kr;else if(i===Yn)t.key=null;let s=await Kc("value",t.value,r,o);if(s===kr)return kr;else if(s===Yn)t.value=null}}return n}function wU(e){if(typeof e==="object"&&(e.Collection||e.Node||e.Value))return Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e);return e}function xU(e,t,r,o){if(typeof r==="function")return r(e,t,o);if(zt.isMap(t))return r.Map?.(e,t,o);if(zt.isSeq(t))return r.Seq?.(e,t,o);if(zt.isPair(t))return r.Pair?.(e,t,o);if(zt.isScalar(t))return r.Scalar?.(e,t,o);if(zt.isAlias(t))return r.Alias?.(e,t,o);return}function _U(e,t,r){let o=t[t.length-1];if(zt.isCollection(o))o.items[e]=r;else if(zt.isPair(o))if(e==="key")o.key=r;else o.value=r;else if(zt.isDocument(o))o.contents=r;else{let n=zt.isAlias(o)?"alias":"scalar";throw Error(`Cannot replace node with ${n} parent`)}}rne.visit=Eg;rne.visitAsync=Ag});var bk=ye(function(cne){var EU=qe(),ine=Ud(),sne={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ane=(e)=>e.replace(/[!,[\]{}]/g,(t)=>sne[t]);class Xr{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Xr.defaultYaml,e),this.tags=Object.assign({},Xr.defaultTags,t)}clone(){let e=new Xr(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new Xr(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Xr.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Xr.defaultTags);break}return e}add(e,t){if(this.atNextDocument)this.yaml={explicit:Xr.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Xr.defaultTags),this.atNextDocument=!1;let r=e.trim().split(/[ \t]+/),o=r.shift();switch(o){case"%TAG":{if(r.length!==2){if(t(0,"%TAG directive should contain exactly two parts"),r.length<2)return!1}let[n,i]=r;return this.tags[n]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[n]=r;if(n==="1.1"||n==="1.2")return this.yaml.version=n,!0;else{let i=/^\d+\.\d+$/.test(n);return t(6,`Unsupported YAML version ${n}`,i),!1}}default:return t(0,`Unknown directive ${o}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let i=e.slice(2,-1);if(i==="!"||i==="!!")return t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null;if(e[e.length-1]!==">")t("Verbatim tags must end with a >");return i}let[,r,o]=e.match(/^(.*!)([^!]*)$/s);if(!o)t(`The ${e} tag has no suffix`);let n=this.tags[r];if(n)try{return n+decodeURIComponent(o)}catch(i){return t(String(i)),null}if(r==="!")return e;return t(`Could not resolve tag: ${e}`),null}tagString(e){for(let[t,r]of Object.entries(this.tags))if(e.startsWith(r))return t+ane(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(e&&r.length>0&&EU.isNode(e.contents)){let n={};ine.visit(e.contents,(i,s)=>{if(EU.isNode(s)&&s.tag)n[s.tag]=!0}),o=Object.keys(n)}else o=[];for(let[n,i]of r){if(n==="!!"&&i==="tag:yaml.org,2002:")continue;if(!e||o.some((s)=>s.startsWith(i)))t.push(`%TAG ${n} ${i}`)}return t.join(`
|
|
295
|
+
`)}}Xr.defaultYaml={explicit:!1,version:"1.2"};Xr.defaultTags={"!!":"tag:yaml.org,2002:"};cne.Directives=Xr});var Ig=ye(function(fne){var AU=qe(),une=Ud();function dne(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(r)}return!0}function IU(e){let t=new Set;return une.visit(e,{Value(r,o){if(o.anchor)t.add(o.anchor)}}),t}function kU(e,t){for(let r=1;;++r){let o=`${e}${r}`;if(!t.has(o))return o}}function pne(e,t){let r=[],o=new Map,n=null;return{onAnchor:(i)=>{r.push(i),n??(n=IU(e));let s=kU(t,n);return n.add(s),s},setAnchors:()=>{for(let i of r){let s=o.get(i);if(typeof s==="object"&&s.anchor&&(AU.isScalar(s.node)||AU.isCollection(s.node)))s.node.anchor=s.anchor;else{let a=Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:o}}fne.anchorIsValid=dne;fne.anchorNames=IU;fne.createNodeAnchors=pne;fne.findNewAnchor=kU});var Sk=ye(function(bne){function Md(e,t,r,o){if(o&&typeof o==="object")if(Array.isArray(o))for(let n=0,i=o.length;n<i;++n){let s=o[n],a=Md(e,o,String(n),s);if(a===void 0)delete o[n];else if(a!==s)o[n]=a}else if(o instanceof Map)for(let n of Array.from(o.keys())){let i=o.get(n),s=Md(e,o,n,i);if(s===void 0)o.delete(n);else if(s!==i)o.set(n,s)}else if(o instanceof Set)for(let n of Array.from(o)){let i=Md(e,o,n,n);if(i===void 0)o.delete(n);else if(i!==n)o.delete(n),o.add(i)}else for(let[n,i]of Object.entries(o)){let s=Md(e,o,n,i);if(s===void 0)delete o[n];else if(s!==i)o[n]=s}return e.call(t,r,o)}bne.applyReviver=Md});var Ni=ye(function(wne){var vne=qe();function RU(e,t,r){if(Array.isArray(e))return e.map((o,n)=>RU(o,String(n),r));if(e&&typeof e.toJSON==="function"){if(!r||!vne.hasAnchor(e))return e.toJSON(t,r);let o={aliasCount:0,count:1,res:void 0};r.anchors.set(e,o),r.onCreate=(i)=>{o.res=i,delete r.onCreate};let n=e.toJSON(t,r);if(r.onCreate)r.onCreate(n);return n}if(typeof e==="bigint"&&!r?.keep)return Number(e);return e}wne.toJS=RU});var kg=ye(function(Ane){var _ne=Sk(),TU=qe(),Ene=Ni();class $U{constructor(e){Object.defineProperty(this,TU.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)e.range=this.range.slice();return e}toJS(e,{mapAsMap:t,maxAliasCount:r,onAnchor:o,reviver:n}={}){if(!TU.isDocument(e))throw TypeError("A document argument is required");let i={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof r==="number"?r:100},s=Ene.toJS(this,"",i);if(typeof o==="function")for(let{count:a,res:l}of i.anchors.values())o(l,a);return typeof n==="function"?_ne.applyReviver(n,{"":s},"",s):s}}Ane.NodeBase=$U});var qd=ye(function(One){var kne=Ig(),Rne=Ud(),Hc=qe(),Tne=kg(),$ne=Ni();class OU extends Tne.NodeBase{constructor(e){super(Hc.ALIAS);this.source=e,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError("Alias resolution is disabled");let r;if(t?.aliasResolveCache)r=t.aliasResolveCache;else if(r=[],Rne.visit(e,{Node:(n,i)=>{if(Hc.isAlias(i)||Hc.hasAnchor(i))r.push(i)}}),t)t.aliasResolveCache=r;let o=void 0;for(let n of r){if(n===this)break;if(n.anchor===this.source)o=n}return o}toJSON(e,t){if(!t)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:n}=t,i=this.resolve(o,t);if(!i){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(a)}let s=r.get(i);if(!s)$ne.toJS(i,null,t),s=r.get(i);if(s?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(n>=0){if(s.count+=1,s.aliasCount===0)s.aliasCount=Rg(o,i,r);if(s.count*s.aliasCount>n)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return s.res}toString(e,t,r){let o=`*${this.source}`;if(e){if(kne.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let n=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(n)}if(e.implicitKey)return`${o} `}return o}}function Rg(e,t,r){if(Hc.isAlias(t)){let o=t.resolve(e),n=r&&o&&r.get(o);return n?n.count*n.aliasCount:0}else if(Hc.isCollection(t)){let o=0;for(let n of t.items){let i=Rg(e,n,r);if(i>o)o=i}return o}else if(Hc.isPair(t)){let o=Rg(e,t.key,r),n=Rg(e,t.value,r);return Math.max(o,n)}return 1}One.Alias=OU});var It=ye(function(Lne){var zne=qe(),Pne=kg(),Nne=Ni(),Dne=(e)=>!e||typeof e!=="function"&&typeof e!=="object";class ta extends Pne.NodeBase{constructor(e){super(zne.SCALAR);this.value=e}toJSON(e,t){return t?.keep?this.value:Nne.toJS(this.value,e,t)}toString(){return String(this.value)}}ta.BLOCK_FOLDED="BLOCK_FOLDED";ta.BLOCK_LITERAL="BLOCK_LITERAL";ta.PLAIN="PLAIN";ta.QUOTE_DOUBLE="QUOTE_DOUBLE";ta.QUOTE_SINGLE="QUOTE_SINGLE";Lne.Scalar=ta;Lne.isScalarValue=Dne});var Fd=ye(function(Fne){var Bne=qd(),ra=qe(),CU=It(),Une="tag:yaml.org,2002:";function Mne(e,t,r){if(t){let o=r.filter((i)=>i.tag===t),n=o.find((i)=>!i.format)??o[0];if(!n)throw Error(`Tag ${t} not found`);return n}return r.find((o)=>o.identify?.(e)&&!o.format)}function qne(e,t,r){if(ra.isDocument(e))e=e.contents;if(ra.isNode(e))return e;if(ra.isPair(e)){let p=r.schema[ra.MAP].createNode?.(r.schema,null,r);return p.items.push(e),p}if(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)e=e.valueOf();let{aliasDuplicateObjects:o,onAnchor:n,onTagObj:i,schema:s,sourceObjects:a}=r,l=void 0;if(o&&e&&typeof e==="object")if(l=a.get(e),l)return l.anchor??(l.anchor=n(e)),new Bne.Alias(l.anchor);else l={anchor:null,node:null},a.set(e,l);if(t?.startsWith("!!"))t=Une+t.slice(2);let u=Mne(e,t,s.tags);if(!u){if(e&&typeof e.toJSON==="function")e=e.toJSON();if(!e||typeof e!=="object"){let p=new CU.Scalar(e);if(l)l.node=p;return p}u=e instanceof Map?s[ra.MAP]:(Symbol.iterator in Object(e))?s[ra.SEQ]:s[ra.MAP]}if(i)i(u),delete r.onTagObj;let d=u?.createNode?u.createNode(r.schema,e,r):typeof u?.nodeClass?.from==="function"?u.nodeClass.from(r.schema,e,r):new CU.Scalar(e);if(t)d.tag=t;else if(!u.default)d.tag=u.tag;if(l)l.node=d;return d}Fne.createNode=qne});var Tg=ye(function(Vne){var Kne=Fd(),Xn=qe(),Hne=kg();function vk(e,t,r){let o=r;for(let n=t.length-1;n>=0;--n){let i=t[n];if(typeof i==="number"&&Number.isInteger(i)&&i>=0){let s=[];s[i]=o,o=s}else o=new Map([[i,o]])}return Kne.createNode(o,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var zU=(e)=>e==null||typeof e==="object"&&!!e[Symbol.iterator]().next().done;class PU extends Hne.NodeBase{constructor(e,t){super(e);Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(e)t.schema=e;if(t.items=t.items.map((r)=>Xn.isNode(r)||Xn.isPair(r)?r.clone(e):r),this.range)t.range=this.range.slice();return t}addIn(e,t){if(zU(e))this.add(t);else{let[r,...o]=e,n=this.get(r,!0);if(Xn.isCollection(n))n.addIn(o,t);else if(n===void 0&&this.schema)this.set(r,vk(this.schema,o,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let o=this.get(t,!0);if(Xn.isCollection(o))return o.deleteIn(r);else throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...o]=e,n=this.get(r,!0);if(o.length===0)return!t&&Xn.isScalar(n)?n.value:n;else return Xn.isCollection(n)?n.getIn(o,t):void 0}hasAllNullValues(e){return this.items.every((t)=>{if(!Xn.isPair(t))return!1;let r=t.value;return r==null||e&&Xn.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let o=this.get(t,!0);return Xn.isCollection(o)?o.hasIn(r):!1}setIn(e,t){let[r,...o]=e;if(o.length===0)this.set(r,t);else{let n=this.get(r,!0);if(Xn.isCollection(n))n.setIn(o,t);else if(n===void 0&&this.schema)this.set(r,vk(this.schema,o,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}}Vne.Collection=PU;Vne.collectionFromPath=vk;Vne.isEmptyPath=zU});var Jd=ye(function(eoe){var Yne=(e)=>e.replace(/^(?!$)(?: $)?/gm,"#");function wk(e,t){if(/^\n+$/.test(e))return e.substring(1);return t?e.replace(/^(?! *$)/gm,t):e}var Xne=(e,t,r)=>e.endsWith(`
|
|
295
296
|
`)?wk(r,t):r.includes(`
|
|
296
297
|
`)?`
|
|
297
|
-
`+wk(r,t):(e.endsWith(" ")?"":" ")+r;
|
|
298
|
+
`+wk(r,t):(e.endsWith(" ")?"":" ")+r;eoe.indentComment=wk;eoe.lineComment=Xne;eoe.stringifyComment=Yne});var DU=ye(function(ioe){function ooe(e,t,r="flow",{indentAtStart:o,lineWidth:n=80,minContentWidth:i=20,onFold:s,onOverflow:a}={}){if(!n||n<0)return e;if(n<i)i=0;let l=Math.max(1+i,1+n-t.length);if(e.length<=l)return e;let u=[],d={},p=n-t.length;if(typeof o==="number")if(o>n-Math.max(2,i))u.push(0);else p=n-o;let m=void 0,h=void 0,S=!1,y=-1,v=-1,x=-1;if(r==="block"){if(y=NU(e,y,t.length),y!==-1)p=y+l}for(let k;k=e[y+=1];){if(r==="quoted"&&k==="\\"){switch(v=y,e[y+1]){case"x":y+=3;break;case"u":y+=5;break;case"U":y+=9;break;default:y+=1}x=y}if(k===`
|
|
298
299
|
`){if(r==="block")y=NU(e,y,t.length);p=y+t.length+l,m=void 0}else{if(k===" "&&h&&h!==" "&&h!==`
|
|
299
300
|
`&&h!=="\t"){let O=e[y+1];if(O&&O!==" "&&O!==`
|
|
300
301
|
`&&O!=="\t")m=y}if(y>=p)if(m)u.push(m),p=m+l,m=void 0;else if(r==="quoted"){while(h===" "||h==="\t")h=k,k=e[y+=1],S=!0;let O=y>x+1?y-2:v-1;if(d[O])return e;u.push(O),d[O]=!0,p=O+l,m=void 0}else S=!0}h=k}if(S&&a)a();if(u.length===0)return e;if(s)s();let _=e.slice(0,u[0]);for(let k=0;k<u.length;++k){let O=u[k],L=u[k+1]||e.length;if(O===0)_=`
|
|
301
302
|
${t}${e.slice(0,L)}`;else{if(r==="quoted"&&d[O])_+=`${e[O]}\\`;_+=`
|
|
302
303
|
${t}${e.slice(O+1,L)}`}}return _}function NU(e,t,r){let o=t,n=t+1,i=e[n];while(i===" "||i==="\t")if(t<n+r)i=e[++t];else{do i=e[++t];while(i&&i!==`
|
|
303
|
-
`);o=t,n=t+1,i=e[n]}return o}
|
|
304
|
+
`);o=t,n=t+1,i=e[n]}return o}ioe.FOLD_BLOCK="block";ioe.FOLD_FLOW="flow";ioe.FOLD_QUOTED="quoted";ioe.foldFlowLines=ooe});var Hd=ye(function(foe){var bn=It(),Di=DU(),Og=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Cg=(e)=>/^(%|---|\.\.\.)/m.test(e);function uoe(e,t,r){if(!t||t<0)return!1;let o=t-r,n=e.length;if(n<=o)return!1;for(let i=0,s=0;i<n;++i)if(e[i]===`
|
|
304
305
|
`){if(i-s>o)return!0;if(s=i+1,n-s<=o)return!1}return!0}function Kd(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:o}=t,n=t.options.doubleQuotedMinMultiLineLength,i=t.indent||(Cg(e)?" ":""),s="",a=0;for(let l=0,u=r[l];u;u=r[++l]){if(u===" "&&r[l+1]==="\\"&&r[l+2]==="n")s+=r.slice(a,l)+"\\ ",l+=1,a=l,u="\\";if(u==="\\")switch(r[l+1]){case"u":{s+=r.slice(a,l);let d=r.substr(l+2,4);switch(d){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:if(d.substr(0,2)==="00")s+="\\x"+d.substr(2);else s+=r.substr(l,6)}l+=5,a=l+1}break;case"n":if(o||r[l+2]==='"'||r.length<n)l+=1;else{s+=r.slice(a,l)+`
|
|
305
306
|
|
|
306
307
|
`;while(r[l+2]==="\\"&&r[l+3]==="n"&&r[l+4]!=='"')s+=`
|
|
@@ -309,7 +310,7 @@ ${t}${e.slice(O+1,L)}`}}return _}function NU(e,t,r){let o=t,n=t+1,i=e[n];while(i
|
|
|
309
310
|
${r}`)+"'";return t.implicitKey?o:Di.foldFlowLines(o,r,Di.FOLD_FLOW,Og(t,!1))}function Vc(e,t){let{singleQuote:r}=t.options,o;if(r===!1)o=Kd;else{let n=e.includes('"'),i=e.includes("'");if(n&&!i)o=xk;else if(i&&!n)o=Kd;else o=r?xk:Kd}return o(e,t)}var _k;try{_k=new RegExp(`(^|(?<!
|
|
310
311
|
))
|
|
311
312
|
+(?!
|
|
312
|
-
|$)`,"g")}catch{_k=/\n+(?!\n|$)/g}function $g({comment:e,type:t,value:r},o,n,i){let{blockQuote:s,commentString:a,lineWidth:l}=o.options;if(!s||/\n[\t ]+$/.test(r))return Vc(r,o);let u=o.indent||(o.forceBlockIndent||Cg(r)?" ":""),d=s==="literal"?!0:s==="folded"||t===bn.Scalar.BLOCK_FOLDED?!1:t===bn.Scalar.BLOCK_LITERAL?!0:!
|
|
313
|
+
|$)`,"g")}catch{_k=/\n+(?!\n|$)/g}function $g({comment:e,type:t,value:r},o,n,i){let{blockQuote:s,commentString:a,lineWidth:l}=o.options;if(!s||/\n[\t ]+$/.test(r))return Vc(r,o);let u=o.indent||(o.forceBlockIndent||Cg(r)?" ":""),d=s==="literal"?!0:s==="folded"||t===bn.Scalar.BLOCK_FOLDED?!1:t===bn.Scalar.BLOCK_LITERAL?!0:!uoe(r,l,u.length);if(!r)return d?`|
|
|
313
314
|
`:`>
|
|
314
315
|
`;let p,m;for(m=r.length;m>0;--m){let L=r[m-1];if(L!==`
|
|
315
316
|
`&&L!=="\t"&&L!==" ")break}let h=r.substring(m),S=h.indexOf(`
|
|
@@ -318,12 +319,12 @@ ${r}`)+"'";return t.implicitKey?o:Di.foldFlowLines(o,r,Di.FOLD_FLOW,Og(t,!1))}fu
|
|
|
318
319
|
`)x=v;else break}let _=r.substring(0,x<v?x+1:v);if(_)r=r.substring(_.length),_=_.replace(/\n+/g,`$&${u}`);let O=(y?u?"2":"1":"")+p;if(e){if(O+=" "+a(e.replace(/ ?[\r\n]+/g," ")),n)n()}if(!d){let L=r.replace(/\n+/g,`
|
|
319
320
|
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),P=!1,K=Og(o,!0);if(s!=="folded"&&t!==bn.Scalar.BLOCK_FOLDED)K.onOverflow=()=>{P=!0};let z=Di.foldFlowLines(`${_}${L}${h}`,u,Di.FOLD_BLOCK,K);if(!P)return`>${O}
|
|
320
321
|
${u}${z}`}return r=r.replace(/\n+/g,`$&${u}`),`|${O}
|
|
321
|
-
${u}${_}${r}${h}`}function
|
|
322
|
+
${u}${_}${r}${h}`}function doe(e,t,r,o){let{type:n,value:i}=e,{actualString:s,implicitKey:a,indent:l,indentStep:u,inFlow:d}=t;if(a&&i.includes(`
|
|
322
323
|
`)||d&&/[[\]{},]/.test(i))return Vc(i,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||d||!i.includes(`
|
|
323
324
|
`)?Vc(i,t):$g(e,t,r,o);if(!a&&!d&&n!==bn.Scalar.PLAIN&&i.includes(`
|
|
324
325
|
`))return $g(e,t,r,o);if(Cg(i)){if(l==="")return t.forceBlockIndent=!0,$g(e,t,r,o);else if(a&&l===u)return Vc(i,t)}let p=i.replace(/\n+/g,`$&
|
|
325
|
-
${l}`);if(s){let m=(y)=>y.default&&y.tag!=="tag:yaml.org,2002:str"&&y.test?.test(p),{compat:h,tags:S}=t.doc.schema;if(S.some(m)||h?.some(m))return Vc(i,t)}return a?p:Di.foldFlowLines(p,l,Di.FOLD_FLOW,Og(t,!1))}function
|
|
326
|
-
${t.indent}${a}`}
|
|
326
|
+
${l}`);if(s){let m=(y)=>y.default&&y.tag!=="tag:yaml.org,2002:str"&&y.test?.test(p),{compat:h,tags:S}=t.doc.schema;if(S.some(m)||h?.some(m))return Vc(i,t)}return a?p:Di.foldFlowLines(p,l,Di.FOLD_FLOW,Og(t,!1))}function poe(e,t,r,o){let{implicitKey:n,inFlow:i}=t,s=typeof e.value==="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;if(a!==bn.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value))a=bn.Scalar.QUOTE_DOUBLE}let l=(d)=>{switch(d){case bn.Scalar.BLOCK_FOLDED:case bn.Scalar.BLOCK_LITERAL:return n||i?Vc(s.value,t):$g(s,t,r,o);case bn.Scalar.QUOTE_DOUBLE:return Kd(s.value,t);case bn.Scalar.QUOTE_SINGLE:return xk(s.value,t);case bn.Scalar.PLAIN:return doe(s,t,r,o);default:return null}},u=l(a);if(u===null){let{defaultKeyType:d,defaultStringType:p}=t.options,m=n&&d||p;if(u=l(m),u===null)throw Error(`Unsupported default string type ${m}`)}return u}foe.stringifyString=poe});var Vd=ye(function(xoe){var hoe=Ig(),Li=qe(),goe=Jd(),yoe=Hd();function boe(e,t){let r=Object.assign({blockQuote:!0,commentString:goe.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),o;switch(r.collectionStyle){case"block":o=!1;break;case"flow":o=!0;break;default:o=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent==="number"?" ".repeat(r.indent):" ",inFlow:o,options:r}}function Soe(e,t){if(t.tag){let n=e.filter((i)=>i.tag===t.tag);if(n.length>0)return n.find((i)=>i.format===t.format)??n[0]}let r=void 0,o;if(Li.isScalar(t)){o=t.value;let n=e.filter((i)=>i.identify?.(o));if(n.length>1){let i=n.filter((s)=>s.test);if(i.length>0)n=i}r=n.find((i)=>i.format===t.format)??n.find((i)=>!i.format)}else o=t,r=e.find((n)=>n.nodeClass&&o instanceof n.nodeClass);if(!r){let n=o?.constructor?.name??(o===null?"null":typeof o);throw Error(`Tag not resolved for ${n} value`)}return r}function voe(e,t,{anchors:r,doc:o}){if(!o.directives)return"";let n=[],i=(Li.isScalar(e)||Li.isCollection(e))&&e.anchor;if(i&&hoe.anchorIsValid(i))r.add(i),n.push(`&${i}`);let s=e.tag??(t.default?null:t.tag);if(s)n.push(o.directives.tagString(s));return n.join(" ")}function woe(e,t,r,o){if(Li.isPair(e))return e.toString(t,r,o);if(Li.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(t.resolvedAliases)t.resolvedAliases.add(e);else t.resolvedAliases=new Set([e]);e=e.resolve(t.doc)}}let n=void 0,i=Li.isNode(e)?e:t.doc.createNode(e,{onTagObj:(l)=>n=l});n??(n=Soe(t.doc.schema.tags,i));let s=voe(i,n,t);if(s.length>0)t.indentAtStart=(t.indentAtStart??0)+s.length+1;let a=typeof n.stringify==="function"?n.stringify(i,t,r,o):Li.isScalar(i)?yoe.stringifyString(i,t,r,o):i.toString(t,r,o);if(!s)return a;return Li.isScalar(i)||a[0]==="{"||a[0]==="["?`${s} ${a}`:`${s}
|
|
327
|
+
${t.indent}${a}`}xoe.createStringifyContext=boe;xoe.stringify=woe});var jU=ye(function(Ioe){var Co=qe(),LU=It(),ZU=Vd(),Wd=Jd();function Aoe({key:e,value:t},r,o,n){let{allNullValues:i,doc:s,indent:a,indentStep:l,options:{commentString:u,indentSeq:d,simpleKeys:p}}=r,m=Co.isNode(e)&&e.comment||null;if(p){if(m)throw Error("With simple keys, key nodes cannot have comments");if(Co.isCollection(e)||!Co.isNode(e)&&typeof e==="object")throw Error("With simple keys, collection cannot be used as a key value")}let h=!p&&(!e||m&&t==null&&!r.inFlow||Co.isCollection(e)||(Co.isScalar(e)?e.type===LU.Scalar.BLOCK_FOLDED||e.type===LU.Scalar.BLOCK_LITERAL:typeof e==="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(p||!i),indent:a+l});let S=!1,y=!1,v=ZU.stringify(e,r,()=>S=!0,()=>y=!0);if(!h&&!r.inFlow&&v.length>1024){if(p)throw Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(i||t==null){if(S&&o)o();return v===""?"?":h?`? ${v}`:v}}else if(i&&!p||t==null&&h){if(v=`? ${v}`,m&&!S)v+=Wd.lineComment(v,r.indent,u(m));else if(y&&n)n();return v}if(S)m=null;if(h){if(m)v+=Wd.lineComment(v,r.indent,u(m));v=`? ${v}
|
|
327
328
|
${a}:`}else if(v=`${v}:`,m)v+=Wd.lineComment(v,r.indent,u(m));let x,_,k;if(Co.isNode(t))x=!!t.spaceBefore,_=t.commentBefore,k=t.comment;else if(x=!1,_=null,k=null,t&&typeof t==="object")t=s.createNode(t);if(r.implicitKey=!1,!h&&!m&&Co.isScalar(t))r.indentAtStart=v.length+1;if(y=!1,!d&&l.length>=2&&!r.inFlow&&!h&&Co.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor)r.indent=r.indent.substring(2);let O=!1,L=ZU.stringify(t,r,()=>O=!0,()=>y=!0),P=" ";if(m||x||_){if(P=x?`
|
|
328
329
|
`:"",_){let K=u(_);P+=`
|
|
329
330
|
${Wd.indentComment(K,r.indent)}`}if(L===""&&!r.inFlow){if(P===`
|
|
@@ -333,32 +334,32 @@ ${Wd.indentComment(K,r.indent)}`}if(L===""&&!r.inFlow){if(P===`
|
|
|
333
334
|
${r.indent}`}else if(!h&&Co.isCollection(t)){let K=L[0],z=L.indexOf(`
|
|
334
335
|
`),W=z!==-1,ee=r.inFlow??t.flow??t.items.length===0;if(W||!ee){let j=!1;if(W&&(K==="&"||K==="!")){let T=L.indexOf(" ");if(K==="&"&&T!==-1&&T<z&&L[T+1]==="!")T=L.indexOf(" ",T+1);if(T===-1||z<T)j=!0}if(!j)P=`
|
|
335
336
|
${r.indent}`}}else if(L===""||L[0]===`
|
|
336
|
-
`)P="";if(v+=P+L,r.inFlow){if(O&&o)o()}else if(k&&!O)v+=Wd.lineComment(v,r.indent,u(k));else if(y&&n)n();return v}
|
|
337
|
+
`)P="";if(v+=P+L,r.inFlow){if(O&&o)o()}else if(k&&!O)v+=Wd.lineComment(v,r.indent,u(k));else if(y&&n)n();return v}Ioe.stringifyPair=Aoe});var Ek=ye(function($oe){var BU=Fr("process");function Roe(e,...t){if(e==="debug")console.log(...t)}function Toe(e,t){if(e==="debug"||e==="warn")if(typeof BU.emitWarning==="function")BU.emitWarning(t);else console.warn(t)}$oe.debug=Roe;$oe.warn=Toe});var Dg=ye(function(Poe){var Ng=qe(),UU=It(),zg="<<",Pg={identify:(e)=>e===zg||typeof e==="symbol"&&e.description===zg,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new UU.Scalar(Symbol(zg)),{addToJSMap:MU}),stringify:()=>zg},zoe=(e,t)=>(Pg.identify(t)||Ng.isScalar(t)&&(!t.type||t.type===UU.Scalar.PLAIN)&&Pg.identify(t.value))&&e?.doc.schema.tags.some((r)=>r.tag===Pg.tag&&r.default);function MU(e,t,r){let o=qU(e,r);if(Ng.isSeq(o))for(let n of o.items)Ak(e,t,n);else if(Array.isArray(o))for(let n of o)Ak(e,t,n);else Ak(e,t,o)}function Ak(e,t,r){let o=qU(e,r);if(!Ng.isMap(o))throw Error("Merge sources must be maps or map aliases");let n=o.toJSON(null,e,Map);for(let[i,s]of n)if(t instanceof Map){if(!t.has(i))t.set(i,s)}else if(t instanceof Set)t.add(i);else if(!Object.prototype.hasOwnProperty.call(t,i))Object.defineProperty(t,i,{value:s,writable:!0,enumerable:!0,configurable:!0});return t}function qU(e,t){return e&&Ng.isAlias(t)?t.resolve(e.doc,e):t}Poe.addMergeToJSMap=MU;Poe.isMergeKey=zoe;Poe.merge=Pg});var kk=ye(function(Moe){var Zoe=Ek(),FU=Dg(),joe=Vd(),JU=qe(),Ik=Ni();function Boe(e,t,{key:r,value:o}){if(JU.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,o);else if(FU.isMergeKey(e,r))FU.addMergeToJSMap(e,t,o);else{let n=Ik.toJS(r,"",e);if(t instanceof Map)t.set(n,Ik.toJS(o,n,e));else if(t instanceof Set)t.add(n);else{let i=Uoe(r,n,e),s=Ik.toJS(o,i,e);if(i in t)Object.defineProperty(t,i,{value:s,writable:!0,enumerable:!0,configurable:!0});else t[i]=s}}return t}function Uoe(e,t,r){if(t===null)return"";if(typeof t!=="object")return String(t);if(JU.isNode(e)&&r?.doc){let o=joe.createStringifyContext(r.doc,{});o.anchors=new Set;for(let i of r.anchors.keys())o.anchors.add(i.anchor);o.inFlow=!0,o.inStringifyKey=!0;let n=e.toString(o);if(!r.mapKeyWarned){let i=JSON.stringify(n);if(i.length>40)i=i.substring(0,36)+'..."';Zoe.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Moe.addPairToJSMap=Boe});var Zi=ye(function(Hoe){var KU=Fd(),Foe=jU(),Joe=kk(),Lg=qe();function Koe(e,t,r){let o=KU.createNode(e,void 0,r),n=KU.createNode(t,void 0,r);return new Zg(o,n)}class Zg{constructor(e,t=null){Object.defineProperty(this,Lg.NODE_TYPE,{value:Lg.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:r}=this;if(Lg.isNode(t))t=t.clone(e);if(Lg.isNode(r))r=r.clone(e);return new Zg(t,r)}toJSON(e,t){let r=t?.mapAsMap?new Map:{};return Joe.addPairToJSMap(t,r,this)}toString(e,t,r){return e?.doc?Foe.stringifyPair(this,e,t,r):JSON.stringify(this)}}Hoe.Pair=Zg;Hoe.createPair=Koe});var Rk=ye(function(Xoe){var na=qe(),HU=Vd(),jg=Jd();function Goe(e,t,r){return(t.inFlow??e.flow?Yoe:Qoe)(e,t,r)}function Qoe({comment:e,items:t},r,{blockItemPrefix:o,flowChars:n,itemIndent:i,onChompKeep:s,onComment:a}){let{indent:l,options:{commentString:u}}=r,d=Object.assign({},r,{indent:i,type:null}),p=!1,m=[];for(let S=0;S<t.length;++S){let y=t[S],v=null;if(na.isNode(y)){if(!p&&y.spaceBefore)m.push("");if(Bg(r,m,y.commentBefore,p),y.comment)v=y.comment}else if(na.isPair(y)){let _=na.isNode(y.key)?y.key:null;if(_){if(!p&&_.spaceBefore)m.push("");Bg(r,m,_.commentBefore,p)}}p=!1;let x=HU.stringify(y,d,()=>v=null,()=>p=!0);if(v)x+=jg.lineComment(x,i,u(v));if(p&&v)p=!1;m.push(o+x)}let h;if(m.length===0)h=n.start+n.end;else{h=m[0];for(let S=1;S<m.length;++S){let y=m[S];h+=y?`
|
|
337
338
|
${l}${y}`:`
|
|
338
339
|
`}}if(e){if(h+=`
|
|
339
|
-
`+jg.indentComment(u(e),l),a)a()}else if(p&&s)s();return h}function
|
|
340
|
+
`+jg.indentComment(u(e),l),a)a()}else if(p&&s)s();return h}function Yoe({items:e},t,{flowChars:r,itemIndent:o}){let{indent:n,indentStep:i,flowCollectionPadding:s,options:{commentString:a}}=t;o+=i;let l=Object.assign({},t,{indent:o,inFlow:!0,type:null}),u=!1,d=0,p=[];for(let S=0;S<e.length;++S){let y=e[S],v=null;if(na.isNode(y)){if(y.spaceBefore)p.push("");if(Bg(t,p,y.commentBefore,!1),y.comment)v=y.comment}else if(na.isPair(y)){let _=na.isNode(y.key)?y.key:null;if(_){if(_.spaceBefore)p.push("");if(Bg(t,p,_.commentBefore,!1),_.comment)u=!0}let k=na.isNode(y.value)?y.value:null;if(k){if(k.comment)v=k.comment;if(k.commentBefore)u=!0}else if(y.value==null&&_?.comment)v=_.comment}if(v)u=!0;let x=HU.stringify(y,l,()=>v=null);if(u||(u=p.length>d||x.includes(`
|
|
340
341
|
`)),S<e.length-1)x+=",";else if(t.options.trailingComma){if(t.options.lineWidth>0)u||(u=p.reduce((_,k)=>_+k.length+2,2)+(x.length+2)>t.options.lineWidth);if(u)x+=","}if(v)x+=jg.lineComment(x,o,a(v));p.push(x),d=p.length}let{start:m,end:h}=r;if(p.length===0)return m+h;else{if(!u){let S=p.reduce((y,v)=>y+v.length+2,2);u=t.options.lineWidth>0&&S>t.options.lineWidth}if(u){let S=m;for(let y of p)S+=y?`
|
|
341
342
|
${i}${n}${y}`:`
|
|
342
343
|
`;return`${S}
|
|
343
|
-
${n}${h}`}else return`${m}${s}${p.join(" ")}${s}${h}`}}function Bg({indent:e,options:{commentString:t}},r,o,n){if(o&&n)o=o.replace(/^\n+/,"");if(o){let i=jg.indentComment(t(o),e);r.push(i.trimStart())}}
|
|
344
|
-
`:" ")}return
|
|
344
|
+
${n}${h}`}else return`${m}${s}${p.join(" ")}${s}${h}`}}function Bg({indent:e,options:{commentString:t}},r,o,n){if(o&&n)o=o.replace(/^\n+/,"");if(o){let i=jg.indentComment(t(o),e);r.push(i.trimStart())}}Xoe.stringifyCollection=Goe});var Bi=ye(function(iie){var tie=Rk(),rie=kk(),nie=Tg(),ji=qe(),Ug=Zi(),oie=It();function Gd(e,t){let r=ji.isScalar(t)?t.value:t;for(let o of e)if(ji.isPair(o)){if(o.key===t||o.key===r)return o;if(ji.isScalar(o.key)&&o.key.value===r)return o}return}class VU extends nie.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(ji.MAP,e);this.items=[]}static from(e,t,r){let{keepUndefined:o,replacer:n}=r,i=new this(e),s=(a,l)=>{if(typeof n==="function")l=n.call(t,a,l);else if(Array.isArray(n)&&!n.includes(a))return;if(l!==void 0||o)i.items.push(Ug.createPair(a,l,r))};if(t instanceof Map)for(let[a,l]of t)s(a,l);else if(t&&typeof t==="object")for(let a of Object.keys(t))s(a,t[a]);if(typeof e.sortMapEntries==="function")i.items.sort(e.sortMapEntries);return i}add(e,t){let r;if(ji.isPair(e))r=e;else if(!e||typeof e!=="object"||!("key"in e))r=new Ug.Pair(e,e?.value);else r=new Ug.Pair(e.key,e.value);let o=Gd(this.items,r.key),n=this.schema?.sortMapEntries;if(o){if(!t)throw Error(`Key ${r.key} already set`);if(ji.isScalar(o.value)&&oie.isScalarValue(r.value))o.value.value=r.value;else o.value=r.value}else if(n){let i=this.items.findIndex((s)=>n(r,s)<0);if(i===-1)this.items.push(r);else this.items.splice(i,0,r)}else this.items.push(r)}delete(e){let t=Gd(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){let o=Gd(this.items,e)?.value;return(!t&&ji.isScalar(o)?o.value:o)??void 0}has(e){return!!Gd(this.items,e)}set(e,t){this.add(new Ug.Pair(e,t),!0)}toJSON(e,t,r){let o=r?new r:t?.mapAsMap?new Map:{};if(t?.onCreate)t.onCreate(o);for(let n of this.items)rie.addPairToJSMap(t,o,n);return o}toString(e,t,r){if(!e)return JSON.stringify(this);for(let o of this.items)if(!ji.isPair(o))throw Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);if(!e.allNullValues&&this.hasAllNullValues(!1))e=Object.assign({},e,{allNullValues:!0});return tie.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:t})}}iie.YAMLMap=VU;iie.findPair=Gd});var Wc=ye(function(uie){var cie=qe(),WU=Bi(),lie={collection:"map",default:!0,nodeClass:WU.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){if(!cie.isMap(e))t("Expected a mapping for this tag");return e},createNode:(e,t,r)=>WU.YAMLMap.from(e,t,r)};uie.map=lie});var Ui=ye(function(yie){var pie=Fd(),fie=Rk(),mie=Tg(),qg=qe(),hie=It(),gie=Ni();class GU extends mie.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(qg.SEQ,e);this.items=[]}add(e){this.items.push(e)}delete(e){let t=Mg(e);if(typeof t!=="number")return!1;return this.items.splice(t,1).length>0}get(e,t){let r=Mg(e);if(typeof r!=="number")return;let o=this.items[r];return!t&&qg.isScalar(o)?o.value:o}has(e){let t=Mg(e);return typeof t==="number"&&t<this.items.length}set(e,t){let r=Mg(e);if(typeof r!=="number")throw Error(`Expected a valid index, not ${e}.`);let o=this.items[r];if(qg.isScalar(o)&&hie.isScalarValue(t))o.value=t;else this.items[r]=t}toJSON(e,t){let r=[];if(t?.onCreate)t.onCreate(r);let o=0;for(let n of this.items)r.push(gie.toJS(n,String(o++),t));return r}toString(e,t,r){if(!e)return JSON.stringify(this);return fie.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:t})}static from(e,t,r){let{replacer:o}=r,n=new this(e);if(t&&Symbol.iterator in Object(t)){let i=0;for(let s of t){if(typeof o==="function"){let a=t instanceof Set?s:String(i++);s=o.call(t,a,s)}n.items.push(pie.createNode(s,void 0,r))}}return n}}function Mg(e){let t=qg.isScalar(e)?e.value:e;if(t&&typeof t==="string")t=Number(t);return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:null}yie.YAMLSeq=GU});var Gc=ye(function(wie){var Sie=qe(),QU=Ui(),vie={collection:"seq",default:!0,nodeClass:QU.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){if(!Sie.isSeq(e))t("Expected a sequence for this tag");return e},createNode:(e,t,r)=>QU.YAMLSeq.from(e,t,r)};wie.seq=vie});var Qd=ye(function(Aie){var _ie=Hd(),Eie={identify:(e)=>typeof e==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(e)=>e,stringify(e,t,r,o){return t=Object.assign({actualString:!0},t),_ie.stringifyString(e,t,r,o)}};Aie.string=Eie});var Fg=ye(function(kie){var YU=It(),XU={identify:(e)=>e==null,createNode:()=>new YU.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new YU.Scalar(null),stringify:({source:e},t)=>typeof e==="string"&&XU.test.test(e)?e:t.options.nullStr};kie.nullTag=XU});var Tk=ye(function($ie){var Tie=It(),eM={identify:(e)=>typeof e==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:(e)=>new Tie.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&eM.test.test(e)){let o=e[0]==="t"||e[0]==="T";if(t===o)return e}return t?r.options.trueStr:r.options.falseStr}};$ie.boolTag=eM});var Qc=ye(function(zie){function Cie({format:e,minFractionDigits:t,tag:r,value:o}){if(typeof o==="bigint")return String(o);let n=typeof o==="number"?o:Number(o);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let i=Object.is(o,-0)?"-0":JSON.stringify(o);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(i)&&!i.includes("e")){let s=i.indexOf(".");if(s<0)s=i.length,i+=".";let a=t-(i.length-s-1);while(a-- >0)i+="0"}return i}zie.stringifyNumber=Cie});var Ok=ye(function(jie){var Nie=It(),$k=Qc(),Die={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(e)=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:$k.stringifyNumber},Lie={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:(e)=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():$k.stringifyNumber(e)}},Zie={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new Nie.Scalar(parseFloat(e)),r=e.indexOf(".");if(r!==-1&&e[e.length-1]==="0")t.minFractionDigits=e.length-r-1;return t},stringify:$k.stringifyNumber};jie.float=Zie;jie.floatExp=Lie;jie.floatNaN=Die});var zk=ye(function(Kie){var tM=Qc(),Jg=(e)=>typeof e==="bigint"||Number.isInteger(e),Ck=(e,t,r,{intAsBigInt:o})=>o?BigInt(e):parseInt(e.substring(t),r);function rM(e,t,r){let{value:o}=e;if(Jg(o)&&o>=0)return r+o.toString(t);return tM.stringifyNumber(e)}var qie={identify:(e)=>Jg(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Ck(e,2,8,r),stringify:(e)=>rM(e,8,"0o")},Fie={identify:Jg,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Ck(e,0,10,r),stringify:tM.stringifyNumber},Jie={identify:(e)=>Jg(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Ck(e,2,16,r),stringify:(e)=>rM(e,16,"0x")};Kie.int=Fie;Kie.intHex=Jie;Kie.intOct=qie});var nM=ye(function(rse){var Gie=Wc(),Qie=Fg(),Yie=Gc(),Xie=Qd(),ese=Tk(),Pk=Ok(),Nk=zk(),tse=[Gie.map,Yie.seq,Xie.string,Qie.nullTag,ese.boolTag,Nk.intOct,Nk.int,Nk.intHex,Pk.floatNaN,Pk.floatExp,Pk.float];rse.schema=tse});var iM=ye(function(use){var ose=It(),ise=Wc(),sse=Gc();function oM(e){return typeof e==="bigint"||Number.isInteger(e)}var Kg=({value:e})=>JSON.stringify(e),ase=[{identify:(e)=>typeof e==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(e)=>e,stringify:Kg},{identify:(e)=>e==null,createNode:()=>new ose.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Kg},{identify:(e)=>typeof e==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(e)=>e==="true",stringify:Kg},{identify:oM,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>oM(e)?e.toString():JSON.stringify(e)},{identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:(e)=>parseFloat(e),stringify:Kg}],cse={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},lse=[ise.map,sse.seq].concat(ase,cse);use.schema=lse});var Lk=ye(function(mse){var Yd=Fr("buffer"),Dk=It(),pse=Hd(),fse={identify:(e)=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Yd.Buffer==="function")return Yd.Buffer.from(e,"base64");else if(typeof atob==="function"){let r=atob(e.replace(/[\n\r]/g,"")),o=new Uint8Array(r.length);for(let n=0;n<r.length;++n)o[n]=r.charCodeAt(n);return o}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},o,n,i){if(!r)return"";let s=r,a;if(typeof Yd.Buffer==="function")a=s instanceof Yd.Buffer?s.toString("base64"):Yd.Buffer.from(s.buffer).toString("base64");else if(typeof btoa==="function"){let l="";for(let u=0;u<s.length;++u)l+=String.fromCharCode(s[u]);a=btoa(l)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Dk.Scalar.BLOCK_LITERAL),t!==Dk.Scalar.QUOTE_DOUBLE){let l=Math.max(o.options.lineWidth-o.indent.length,o.options.minContentWidth),u=Math.ceil(a.length/l),d=Array(u);for(let p=0,m=0;p<u;++p,m+=l)d[p]=a.substr(m,l);a=d.join(t===Dk.Scalar.BLOCK_LITERAL?`
|
|
345
|
+
`:" ")}return pse.stringifyString({comment:e,type:t,value:a},o,n,i)}};mse.binary=fse});var Vg=ye(function(Sse){var Hg=qe(),Zk=Zi(),gse=It(),yse=Ui();function sM(e,t){if(Hg.isSeq(e))for(let r=0;r<e.items.length;++r){let o=e.items[r];if(Hg.isPair(o))continue;else if(Hg.isMap(o)){if(o.items.length>1)t("Each pair must have its own sequence indicator");let n=o.items[0]||new Zk.Pair(new gse.Scalar(null));if(o.commentBefore)n.key.commentBefore=n.key.commentBefore?`${o.commentBefore}
|
|
345
346
|
${n.key.commentBefore}`:o.commentBefore;if(o.comment){let i=n.value??n.key;i.comment=i.comment?`${o.comment}
|
|
346
|
-
${i.comment}`:o.comment}o=n}e.items[r]=Hg.isPair(o)?o:new Zk.Pair(o)}else t("Expected a sequence for this tag");return e}function aM(e,t,r){let{replacer:o}=r,n=new gse.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let i=0;if(t&&Symbol.iterator in Object(t))for(let s of t){if(typeof o==="function")s=o.call(t,String(i++),s);let a,l;if(Array.isArray(s))if(s.length===2)a=s[0],l=s[1];else throw TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){let u=Object.keys(s);if(u.length===1)a=u[0],l=s[a];else throw TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=s;n.items.push(Zk.createPair(a,l,r))}return n}var yse={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:sM,createNode:aM};bse.createPairs=aM;bse.pairs=yse;bse.resolvePairs=sM});var Bk=ye(function(Ese){var cM=qe(),jk=Ni(),Xd=Bi(),xse=Ui(),lM=Vg();class oa extends xse.YAMLSeq{constructor(){super();this.add=Xd.YAMLMap.prototype.add.bind(this),this.delete=Xd.YAMLMap.prototype.delete.bind(this),this.get=Xd.YAMLMap.prototype.get.bind(this),this.has=Xd.YAMLMap.prototype.has.bind(this),this.set=Xd.YAMLMap.prototype.set.bind(this),this.tag=oa.tag}toJSON(e,t){if(!t)return super.toJSON(e);let r=new Map;if(t?.onCreate)t.onCreate(r);for(let o of this.items){let n,i;if(cM.isPair(o))n=jk.toJS(o.key,"",t),i=jk.toJS(o.value,n,t);else n=jk.toJS(o,"",t);if(r.has(n))throw Error("Ordered maps must not include duplicate keys");r.set(n,i)}return r}static from(e,t,r){let o=lM.createPairs(e,t,r),n=new this;return n.items=o.items,n}}oa.tag="tag:yaml.org,2002:omap";var _se={collection:"seq",identify:(e)=>e instanceof Map,nodeClass:oa,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=lM.resolvePairs(e,t),o=[];for(let{key:n}of r.items)if(cM.isScalar(n))if(o.includes(n.value))t(`Ordered maps must not include duplicate keys: ${n.value}`);else o.push(n.value);return Object.assign(new oa,r)},createNode:(e,t,r)=>oa.from(e,t,r)};Ese.YAMLOMap=oa;Ese.omap=_se});var mM=ye(function(kse){var uM=It();function dM({value:e,source:t},r){if(t&&(e?pM:fM).test.test(t))return t;return e?r.options.trueStr:r.options.falseStr}var pM={identify:(e)=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new uM.Scalar(!0),stringify:dM},fM={identify:(e)=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new uM.Scalar(!1),stringify:dM};kse.falseTag=fM;kse.trueTag=pM});var hM=ye(function(Pse){var $se=It(),Uk=Qc(),Ose={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(e)=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Uk.stringifyNumber},Cse={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(e)=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Uk.stringifyNumber(e)}},zse={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new $se.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let o=e.substring(r+1).replace(/_/g,"");if(o[o.length-1]==="0")t.minFractionDigits=o.length}return t},stringify:Uk.stringifyNumber};Pse.float=zse;Pse.floatExp=Cse;Pse.floatNaN=Ose});var yM=ye(function(Mse){var gM=Qc(),ep=(e)=>typeof e==="bigint"||Number.isInteger(e);function Wg(e,t,r,{intAsBigInt:o}){let n=e[0];if(n==="-"||n==="+")t+=1;if(e=e.substring(t).replace(/_/g,""),o){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let s=BigInt(e);return n==="-"?BigInt(-1)*s:s}let i=parseInt(e,r);return n==="-"?-1*i:i}function Mk(e,t,r){let{value:o}=e;if(ep(o)){let n=o.toString(t);return o<0?"-"+r+n.substr(1):r+n}return gM.stringifyNumber(e)}var Zse={identify:ep,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Wg(e,2,2,r),stringify:(e)=>Mk(e,2,"0b")},jse={identify:ep,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Wg(e,1,8,r),stringify:(e)=>Mk(e,8,"0")},Bse={identify:ep,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Wg(e,0,10,r),stringify:gM.stringifyNumber},Use={identify:ep,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Wg(e,2,16,r),stringify:(e)=>Mk(e,16,"0x")};Mse.int=Bse;Mse.intBin=Zse;Mse.intHex=Use;Mse.intOct=jse});var qk=ye(function(Vse){var Yg=qe(),Gg=Zi(),Qg=Bi();class ia extends Qg.YAMLMap{constructor(e){super(e);this.tag=ia.tag}add(e){let t;if(Yg.isPair(e))t=e;else if(e&&typeof e==="object"&&"key"in e&&"value"in e&&e.value===null)t=new Gg.Pair(e.key,null);else t=new Gg.Pair(e,null);if(!Qg.findPair(this.items,t.key))this.items.push(t)}get(e,t){let r=Qg.findPair(this.items,e);return!t&&Yg.isPair(r)?Yg.isScalar(r.key)?r.key.value:r.key:r}set(e,t){if(typeof t!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let r=Qg.findPair(this.items,e);if(r&&!t)this.items.splice(this.items.indexOf(r),1);else if(!r&&t)this.items.push(new Gg.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,r);else throw Error("Set items must all have null values")}static from(e,t,r){let{replacer:o}=r,n=new this(e);if(t&&Symbol.iterator in Object(t))for(let i of t){if(typeof o==="function")i=o.call(t,i,i);n.items.push(Gg.createPair(i,null,r))}return n}}ia.tag="tag:yaml.org,2002:set";var Hse={collection:"map",identify:(e)=>e instanceof Set,nodeClass:ia,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>ia.from(e,t,r),resolve(e,t){if(Yg.isMap(e))if(e.hasAllNullValues(!0))return Object.assign(new ia,e);else t("Set items must all have null values");else t("Expected a mapping for this tag");return e}};Vse.YAMLSet=ia;Vse.set=Hse});var Jk=ye(function(eae){var Qse=Qc();function Fk(e,t){let r=e[0],o=r==="-"||r==="+"?e.substring(1):e,n=(s)=>t?BigInt(s):Number(s),i=o.replace(/_/g,"").split(":").reduce((s,a)=>s*n(60)+n(a),n(0));return r==="-"?n(-1)*i:i}function bM(e){let{value:t}=e,r=(s)=>s;if(typeof t==="bigint")r=(s)=>BigInt(s);else if(isNaN(t)||!isFinite(t))return Qse.stringifyNumber(e);let o="";if(t<0)o="-",t*=r(-1);let n=r(60),i=[t%n];if(t<60)i.unshift(0);else if(t=(t-i[0])/n,i.unshift(t%n),t>=60)t=(t-i[0])/n,i.unshift(t);return o+i.map((s)=>String(s).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Yse={identify:(e)=>typeof e==="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>Fk(e,r),stringify:bM},Xse={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(e)=>Fk(e,!1),stringify:bM},SM={identify:(e)=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(SM.test);if(!t)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,o,n,i,s,a]=t.map(Number),l=t[7]?Number((t[7]+"00").substr(1,3)):0,u=Date.UTC(r,o-1,n,i||0,s||0,a||0,l),d=t[8];if(d&&d!=="Z"){let p=Fk(d,!1);if(Math.abs(p)<30)p*=60;u-=60000*p}return new Date(u)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};eae.floatTime=Xse;eae.intTime=Yse;eae.timestamp=SM});var wM=ye(function(mae){var oae=Wc(),iae=Fg(),sae=Gc(),aae=Qd(),cae=Lk(),vM=mM(),Kk=hM(),Xg=yM(),lae=Dg(),uae=Bk(),dae=Vg(),pae=qk(),Hk=Jk(),fae=[oae.map,sae.seq,aae.string,iae.nullTag,vM.trueTag,vM.falseTag,Xg.intBin,Xg.intOct,Xg.int,Xg.intHex,Kk.floatNaN,Kk.floatExp,Kk.float,cae.binary,lae.merge,uae.omap,dae.pairs,pae.set,Hk.intTime,Hk.floatTime,Hk.timestamp];mae.schema=fae});var OM=ye(function(_ae){var AM=Wc(),gae=Fg(),IM=Gc(),yae=Qd(),bae=Tk(),Vk=Ok(),Wk=zk(),Sae=nM(),vae=iM(),kM=Lk(),tp=Dg(),RM=Bk(),TM=Vg(),xM=wM(),$M=qk(),ey=Jk(),_M=new Map([["core",Sae.schema],["failsafe",[AM.map,IM.seq,yae.string]],["json",vae.schema],["yaml11",xM.schema],["yaml-1.1",xM.schema]]),EM={binary:kM.binary,bool:bae.boolTag,float:Vk.float,floatExp:Vk.floatExp,floatNaN:Vk.floatNaN,floatTime:ey.floatTime,int:Wk.int,intHex:Wk.intHex,intOct:Wk.intOct,intTime:ey.intTime,map:AM.map,merge:tp.merge,null:gae.nullTag,omap:RM.omap,pairs:TM.pairs,seq:IM.seq,set:$M.set,timestamp:ey.timestamp},wae={"tag:yaml.org,2002:binary":kM.binary,"tag:yaml.org,2002:merge":tp.merge,"tag:yaml.org,2002:omap":RM.omap,"tag:yaml.org,2002:pairs":TM.pairs,"tag:yaml.org,2002:set":$M.set,"tag:yaml.org,2002:timestamp":ey.timestamp};function xae(e,t,r){let o=_M.get(t);if(o&&!e)return r&&!o.includes(tp.merge)?o.concat(tp.merge):o.slice();let n=o;if(!n)if(Array.isArray(e))n=[];else{let i=Array.from(_M.keys()).filter((s)=>s!=="yaml11").map((s)=>JSON.stringify(s)).join(", ");throw Error(`Unknown schema "${t}"; use one of ${i} or define customTags array`)}if(Array.isArray(e))for(let i of e)n=n.concat(i);else if(typeof e==="function")n=e(n.slice());if(r)n=n.concat(tp.merge);return n.reduce((i,s)=>{let a=typeof s==="string"?EM[s]:s;if(!a){let l=JSON.stringify(s),u=Object.keys(EM).map((d)=>JSON.stringify(d)).join(", ");throw Error(`Unknown custom tag ${l}; use one of ${u}`)}if(!i.includes(a))i.push(a);return i},[])}_ae.coreKnownTags=wae;_ae.getTags=xae});var Yk=ye(function($ae){var Gk=qe(),Iae=Wc(),kae=Gc(),Rae=Qd(),ty=OM(),Tae=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Qk{constructor({compat:e,customTags:t,merge:r,resolveKnownTags:o,schema:n,sortMapEntries:i,toStringDefaults:s}){this.compat=Array.isArray(e)?ty.getTags(e,"compat"):e?ty.getTags(null,e):null,this.name=typeof n==="string"&&n||"core",this.knownTags=o?ty.coreKnownTags:{},this.tags=ty.getTags(t,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Gk.MAP,{value:Iae.map}),Object.defineProperty(this,Gk.SCALAR,{value:Rae.string}),Object.defineProperty(this,Gk.SEQ,{value:kae.seq}),this.sortMapEntries=typeof i==="function"?i:i===!0?Tae:null}clone(){let e=Object.create(Qk.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}$ae.Schema=Qk});var CM=ye(function(Pae){var Cae=qe(),Xk=Vd(),rp=Jd();function zae(e,t){let r=[],o=t.directives===!0;if(t.directives!==!1&&e.directives){let l=e.directives.toString(e);if(l)r.push(l),o=!0;else if(e.directives.docStart)o=!0}if(o)r.push("---");let n=Xk.createStringifyContext(e,t),{commentString:i}=n.options;if(e.commentBefore){if(r.length!==1)r.unshift("");let l=i(e.commentBefore);r.unshift(rp.indentComment(l,""))}let s=!1,a=null;if(e.contents){if(Cae.isNode(e.contents)){if(e.contents.spaceBefore&&o)r.push("");if(e.contents.commentBefore){let d=i(e.contents.commentBefore);r.push(rp.indentComment(d,""))}n.forceBlockIndent=!!e.comment,a=e.contents.comment}let l=a?void 0:()=>s=!0,u=Xk.stringify(e.contents,n,()=>a=null,l);if(a)u+=rp.lineComment(u,"",i(a));if((u[0]==="|"||u[0]===">")&&r[r.length-1]==="---")r[r.length-1]=`--- ${u}`;else r.push(u)}else r.push(Xk.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let l=i(e.comment);if(l.includes(`
|
|
347
|
+
${i.comment}`:o.comment}o=n}e.items[r]=Hg.isPair(o)?o:new Zk.Pair(o)}else t("Expected a sequence for this tag");return e}function aM(e,t,r){let{replacer:o}=r,n=new yse.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let i=0;if(t&&Symbol.iterator in Object(t))for(let s of t){if(typeof o==="function")s=o.call(t,String(i++),s);let a,l;if(Array.isArray(s))if(s.length===2)a=s[0],l=s[1];else throw TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){let u=Object.keys(s);if(u.length===1)a=u[0],l=s[a];else throw TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=s;n.items.push(Zk.createPair(a,l,r))}return n}var bse={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:sM,createNode:aM};Sse.createPairs=aM;Sse.pairs=bse;Sse.resolvePairs=sM});var Bk=ye(function(Ase){var cM=qe(),jk=Ni(),Xd=Bi(),_se=Ui(),lM=Vg();class oa extends _se.YAMLSeq{constructor(){super();this.add=Xd.YAMLMap.prototype.add.bind(this),this.delete=Xd.YAMLMap.prototype.delete.bind(this),this.get=Xd.YAMLMap.prototype.get.bind(this),this.has=Xd.YAMLMap.prototype.has.bind(this),this.set=Xd.YAMLMap.prototype.set.bind(this),this.tag=oa.tag}toJSON(e,t){if(!t)return super.toJSON(e);let r=new Map;if(t?.onCreate)t.onCreate(r);for(let o of this.items){let n,i;if(cM.isPair(o))n=jk.toJS(o.key,"",t),i=jk.toJS(o.value,n,t);else n=jk.toJS(o,"",t);if(r.has(n))throw Error("Ordered maps must not include duplicate keys");r.set(n,i)}return r}static from(e,t,r){let o=lM.createPairs(e,t,r),n=new this;return n.items=o.items,n}}oa.tag="tag:yaml.org,2002:omap";var Ese={collection:"seq",identify:(e)=>e instanceof Map,nodeClass:oa,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=lM.resolvePairs(e,t),o=[];for(let{key:n}of r.items)if(cM.isScalar(n))if(o.includes(n.value))t(`Ordered maps must not include duplicate keys: ${n.value}`);else o.push(n.value);return Object.assign(new oa,r)},createNode:(e,t,r)=>oa.from(e,t,r)};Ase.YAMLOMap=oa;Ase.omap=Ese});var mM=ye(function(Rse){var uM=It();function dM({value:e,source:t},r){if(t&&(e?pM:fM).test.test(t))return t;return e?r.options.trueStr:r.options.falseStr}var pM={identify:(e)=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new uM.Scalar(!0),stringify:dM},fM={identify:(e)=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new uM.Scalar(!1),stringify:dM};Rse.falseTag=fM;Rse.trueTag=pM});var hM=ye(function(Nse){var Ose=It(),Uk=Qc(),Cse={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(e)=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Uk.stringifyNumber},zse={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(e)=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Uk.stringifyNumber(e)}},Pse={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Ose.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let o=e.substring(r+1).replace(/_/g,"");if(o[o.length-1]==="0")t.minFractionDigits=o.length}return t},stringify:Uk.stringifyNumber};Nse.float=Pse;Nse.floatExp=zse;Nse.floatNaN=Cse});var yM=ye(function(qse){var gM=Qc(),ep=(e)=>typeof e==="bigint"||Number.isInteger(e);function Wg(e,t,r,{intAsBigInt:o}){let n=e[0];if(n==="-"||n==="+")t+=1;if(e=e.substring(t).replace(/_/g,""),o){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let s=BigInt(e);return n==="-"?BigInt(-1)*s:s}let i=parseInt(e,r);return n==="-"?-1*i:i}function Mk(e,t,r){let{value:o}=e;if(ep(o)){let n=o.toString(t);return o<0?"-"+r+n.substr(1):r+n}return gM.stringifyNumber(e)}var jse={identify:ep,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Wg(e,2,2,r),stringify:(e)=>Mk(e,2,"0b")},Bse={identify:ep,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Wg(e,1,8,r),stringify:(e)=>Mk(e,8,"0")},Use={identify:ep,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Wg(e,0,10,r),stringify:gM.stringifyNumber},Mse={identify:ep,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Wg(e,2,16,r),stringify:(e)=>Mk(e,16,"0x")};qse.int=Use;qse.intBin=jse;qse.intHex=Mse;qse.intOct=Bse});var qk=ye(function(Wse){var Yg=qe(),Gg=Zi(),Qg=Bi();class ia extends Qg.YAMLMap{constructor(e){super(e);this.tag=ia.tag}add(e){let t;if(Yg.isPair(e))t=e;else if(e&&typeof e==="object"&&"key"in e&&"value"in e&&e.value===null)t=new Gg.Pair(e.key,null);else t=new Gg.Pair(e,null);if(!Qg.findPair(this.items,t.key))this.items.push(t)}get(e,t){let r=Qg.findPair(this.items,e);return!t&&Yg.isPair(r)?Yg.isScalar(r.key)?r.key.value:r.key:r}set(e,t){if(typeof t!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let r=Qg.findPair(this.items,e);if(r&&!t)this.items.splice(this.items.indexOf(r),1);else if(!r&&t)this.items.push(new Gg.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,r);else throw Error("Set items must all have null values")}static from(e,t,r){let{replacer:o}=r,n=new this(e);if(t&&Symbol.iterator in Object(t))for(let i of t){if(typeof o==="function")i=o.call(t,i,i);n.items.push(Gg.createPair(i,null,r))}return n}}ia.tag="tag:yaml.org,2002:set";var Vse={collection:"map",identify:(e)=>e instanceof Set,nodeClass:ia,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>ia.from(e,t,r),resolve(e,t){if(Yg.isMap(e))if(e.hasAllNullValues(!0))return Object.assign(new ia,e);else t("Set items must all have null values");else t("Expected a mapping for this tag");return e}};Wse.YAMLSet=ia;Wse.set=Vse});var Jk=ye(function(tae){var Yse=Qc();function Fk(e,t){let r=e[0],o=r==="-"||r==="+"?e.substring(1):e,n=(s)=>t?BigInt(s):Number(s),i=o.replace(/_/g,"").split(":").reduce((s,a)=>s*n(60)+n(a),n(0));return r==="-"?n(-1)*i:i}function bM(e){let{value:t}=e,r=(s)=>s;if(typeof t==="bigint")r=(s)=>BigInt(s);else if(isNaN(t)||!isFinite(t))return Yse.stringifyNumber(e);let o="";if(t<0)o="-",t*=r(-1);let n=r(60),i=[t%n];if(t<60)i.unshift(0);else if(t=(t-i[0])/n,i.unshift(t%n),t>=60)t=(t-i[0])/n,i.unshift(t);return o+i.map((s)=>String(s).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Xse={identify:(e)=>typeof e==="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>Fk(e,r),stringify:bM},eae={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(e)=>Fk(e,!1),stringify:bM},SM={identify:(e)=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(SM.test);if(!t)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,o,n,i,s,a]=t.map(Number),l=t[7]?Number((t[7]+"00").substr(1,3)):0,u=Date.UTC(r,o-1,n,i||0,s||0,a||0,l),d=t[8];if(d&&d!=="Z"){let p=Fk(d,!1);if(Math.abs(p)<30)p*=60;u-=60000*p}return new Date(u)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};tae.floatTime=eae;tae.intTime=Xse;tae.timestamp=SM});var wM=ye(function(hae){var iae=Wc(),sae=Fg(),aae=Gc(),cae=Qd(),lae=Lk(),vM=mM(),Kk=hM(),Xg=yM(),uae=Dg(),dae=Bk(),pae=Vg(),fae=qk(),Hk=Jk(),mae=[iae.map,aae.seq,cae.string,sae.nullTag,vM.trueTag,vM.falseTag,Xg.intBin,Xg.intOct,Xg.int,Xg.intHex,Kk.floatNaN,Kk.floatExp,Kk.float,lae.binary,uae.merge,dae.omap,pae.pairs,fae.set,Hk.intTime,Hk.floatTime,Hk.timestamp];hae.schema=mae});var OM=ye(function(Eae){var AM=Wc(),yae=Fg(),IM=Gc(),bae=Qd(),Sae=Tk(),Vk=Ok(),Wk=zk(),vae=nM(),wae=iM(),kM=Lk(),tp=Dg(),RM=Bk(),TM=Vg(),xM=wM(),$M=qk(),ey=Jk(),_M=new Map([["core",vae.schema],["failsafe",[AM.map,IM.seq,bae.string]],["json",wae.schema],["yaml11",xM.schema],["yaml-1.1",xM.schema]]),EM={binary:kM.binary,bool:Sae.boolTag,float:Vk.float,floatExp:Vk.floatExp,floatNaN:Vk.floatNaN,floatTime:ey.floatTime,int:Wk.int,intHex:Wk.intHex,intOct:Wk.intOct,intTime:ey.intTime,map:AM.map,merge:tp.merge,null:yae.nullTag,omap:RM.omap,pairs:TM.pairs,seq:IM.seq,set:$M.set,timestamp:ey.timestamp},xae={"tag:yaml.org,2002:binary":kM.binary,"tag:yaml.org,2002:merge":tp.merge,"tag:yaml.org,2002:omap":RM.omap,"tag:yaml.org,2002:pairs":TM.pairs,"tag:yaml.org,2002:set":$M.set,"tag:yaml.org,2002:timestamp":ey.timestamp};function _ae(e,t,r){let o=_M.get(t);if(o&&!e)return r&&!o.includes(tp.merge)?o.concat(tp.merge):o.slice();let n=o;if(!n)if(Array.isArray(e))n=[];else{let i=Array.from(_M.keys()).filter((s)=>s!=="yaml11").map((s)=>JSON.stringify(s)).join(", ");throw Error(`Unknown schema "${t}"; use one of ${i} or define customTags array`)}if(Array.isArray(e))for(let i of e)n=n.concat(i);else if(typeof e==="function")n=e(n.slice());if(r)n=n.concat(tp.merge);return n.reduce((i,s)=>{let a=typeof s==="string"?EM[s]:s;if(!a){let l=JSON.stringify(s),u=Object.keys(EM).map((d)=>JSON.stringify(d)).join(", ");throw Error(`Unknown custom tag ${l}; use one of ${u}`)}if(!i.includes(a))i.push(a);return i},[])}Eae.coreKnownTags=xae;Eae.getTags=_ae});var Yk=ye(function(Oae){var Gk=qe(),kae=Wc(),Rae=Gc(),Tae=Qd(),ty=OM(),$ae=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Qk{constructor({compat:e,customTags:t,merge:r,resolveKnownTags:o,schema:n,sortMapEntries:i,toStringDefaults:s}){this.compat=Array.isArray(e)?ty.getTags(e,"compat"):e?ty.getTags(null,e):null,this.name=typeof n==="string"&&n||"core",this.knownTags=o?ty.coreKnownTags:{},this.tags=ty.getTags(t,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Gk.MAP,{value:kae.map}),Object.defineProperty(this,Gk.SCALAR,{value:Tae.string}),Object.defineProperty(this,Gk.SEQ,{value:Rae.seq}),this.sortMapEntries=typeof i==="function"?i:i===!0?$ae:null}clone(){let e=Object.create(Qk.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}Oae.Schema=Qk});var CM=ye(function(Nae){var zae=qe(),Xk=Vd(),rp=Jd();function Pae(e,t){let r=[],o=t.directives===!0;if(t.directives!==!1&&e.directives){let l=e.directives.toString(e);if(l)r.push(l),o=!0;else if(e.directives.docStart)o=!0}if(o)r.push("---");let n=Xk.createStringifyContext(e,t),{commentString:i}=n.options;if(e.commentBefore){if(r.length!==1)r.unshift("");let l=i(e.commentBefore);r.unshift(rp.indentComment(l,""))}let s=!1,a=null;if(e.contents){if(zae.isNode(e.contents)){if(e.contents.spaceBefore&&o)r.push("");if(e.contents.commentBefore){let d=i(e.contents.commentBefore);r.push(rp.indentComment(d,""))}n.forceBlockIndent=!!e.comment,a=e.contents.comment}let l=a?void 0:()=>s=!0,u=Xk.stringify(e.contents,n,()=>a=null,l);if(a)u+=rp.lineComment(u,"",i(a));if((u[0]==="|"||u[0]===">")&&r[r.length-1]==="---")r[r.length-1]=`--- ${u}`;else r.push(u)}else r.push(Xk.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let l=i(e.comment);if(l.includes(`
|
|
347
348
|
`))r.push("..."),r.push(rp.indentComment(l,""));else r.push(`... ${l}`)}else r.push("...");else{let l=e.comment;if(l&&s)l=l.replace(/^\n+/,"");if(l){if((!s||a)&&r[r.length-1]!=="")r.push("");r.push(rp.indentComment(i(l),""))}}return r.join(`
|
|
348
349
|
`)+`
|
|
349
|
-
`}
|
|
350
|
+
`}Nae.stringifyDocument=Pae});var np=ye(function(Fae){var Lae=qd(),Yc=Tg(),en=qe(),Zae=Zi(),jae=Ni(),Bae=Yk(),Uae=CM(),eR=Ig(),Mae=Sk(),qae=Fd(),tR=bk();class rR{constructor(e,t,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,en.NODE_TYPE,{value:en.DOC});let o=null;if(typeof t==="function"||Array.isArray(t))o=t;else if(r===void 0&&t)r=t,t=void 0;let n=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=n;let{version:i}=n;if(r?._directives){if(this.directives=r._directives.atDocument(),this.directives.yaml.explicit)i=this.directives.yaml.version}else this.directives=new tR.Directives({version:i});this.setSchema(i,r),this.contents=e===void 0?null:this.createNode(e,o,r)}clone(){let e=Object.create(rR.prototype,{[en.NODE_TYPE]:{value:en.DOC}});if(e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives)e.directives=this.directives.clone();if(e.schema=this.schema.clone(),e.contents=en.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range)e.range=this.range.slice();return e}add(e){if(Xc(this.contents))this.contents.add(e)}addIn(e,t){if(Xc(this.contents))this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let r=eR.anchorNames(this);e.anchor=!t||r.has(t)?eR.findNewAnchor(t||"a",r):t}return new Lae.Alias(e.anchor)}createNode(e,t,r){let o=void 0;if(typeof t==="function")e=t.call({"":e},"",e),o=t;else if(Array.isArray(t)){let y=(x)=>typeof x==="number"||x instanceof String||x instanceof Number,v=t.filter(y).map(String);if(v.length>0)t=t.concat(v);o=t}else if(r===void 0&&t)r=t,t=void 0;let{aliasDuplicateObjects:n,anchorPrefix:i,flow:s,keepUndefined:a,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:p,sourceObjects:m}=eR.createNodeAnchors(this,i||"a"),h={aliasDuplicateObjects:n??!0,keepUndefined:a??!1,onAnchor:d,onTagObj:l,replacer:o,schema:this.schema,sourceObjects:m},S=qae.createNode(e,u,h);if(s&&en.isCollection(S))S.flow=!0;return p(),S}createPair(e,t,r={}){let o=this.createNode(e,null,r),n=this.createNode(t,null,r);return new Zae.Pair(o,n)}delete(e){return Xc(this.contents)?this.contents.delete(e):!1}deleteIn(e){if(Yc.isEmptyPath(e)){if(this.contents==null)return!1;return this.contents=null,!0}return Xc(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return en.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){if(Yc.isEmptyPath(e))return!t&&en.isScalar(this.contents)?this.contents.value:this.contents;return en.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return en.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){if(Yc.isEmptyPath(e))return this.contents!==void 0;return en.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){if(this.contents==null)this.contents=Yc.collectionFromPath(this.schema,[e],t);else if(Xc(this.contents))this.contents.set(e,t)}setIn(e,t){if(Yc.isEmptyPath(e))this.contents=t;else if(this.contents==null)this.contents=Yc.collectionFromPath(this.schema,Array.from(e),t);else if(Xc(this.contents))this.contents.setIn(e,t)}setSchema(e,t={}){if(typeof e==="number")e=String(e);let r;switch(e){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new tR.Directives({version:"1.1"});r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=e;else this.directives=new tR.Directives({version:e});r={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;r=null;break;default:{let o=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${o}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(r)this.schema=new Bae.Schema(Object.assign(r,t));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:r,maxAliasCount:o,onAnchor:n,reviver:i}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o==="number"?o:100},a=jae.toJS(this.contents,t??"",s);if(typeof n==="function")for(let{count:l,res:u}of s.anchors.values())n(u,l);return typeof i==="function"?Mae.applyReviver(i,{"":a},"",a):a}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return Uae.stringifyDocument(this,e)}}function Xc(e){if(en.isCollection(e))return!0;throw Error("Expected a YAML collection as document contents")}Fae.Document=rR});var op=ye(function(Hae){class ry extends Error{constructor(e,t,r,o){super();this.name=e,this.code=r,this.message=o,this.pos=t}}class zM extends ry{constructor(e,t,r){super("YAMLParseError",e,t,r)}}class PM extends ry{constructor(e,t,r){super("YAMLWarning",e,t,r)}}var Kae=(e,t)=>(r)=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map((a)=>t.linePos(a));let{line:o,col:n}=r.linePos[0];r.message+=` at line ${o}, column ${n}`;let i=n-1,s=e.substring(t.lineStarts[o-1],t.lineStarts[o]).replace(/[\n\r]+$/,"");if(i>=60&&s.length>80){let a=Math.min(i-39,s.length-79);s="\u2026"+s.substring(a),i-=a-1}if(s.length>80)s=s.substring(0,79)+"\u2026";if(o>1&&/^ *$/.test(s.substring(0,i))){let a=e.substring(t.lineStarts[o-2],t.lineStarts[o-1]);if(a.length>80)a=a.substring(0,79)+`\u2026
|
|
350
351
|
`;s=a+s}if(/[^ ]/.test(s)){let a=1,l=r.linePos[1];if(l?.line===o&&l.col>n)a=Math.max(1,Math.min(l.col-n,80-i));let u=" ".repeat(i)+"^".repeat(a);r.message+=`:
|
|
351
352
|
|
|
352
353
|
${s}
|
|
353
354
|
${u}
|
|
354
|
-
`}};
|
|
355
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(nR(t.key)||nR(t.value))return!0}return!1;default:return!0}}
|
|
356
|
-
`+y.comment;else a.comment=y.comment;continue}if(y.newlineAfterProp||
|
|
357
|
-
`+k.comment;else _.comment=k.comment;let O=new DM.Pair(_);if(r.options.keepSourceTokens)O.srcToken=d;a.items.push(O)}}if(u&&u<l)n(u,"IMPOSSIBLE","Map comment with trailing content");return a.range=[o.offset,l,u??l],a}
|
|
358
|
-
`+P.comment;else u.comment=P.comment;p=P.end;continue}if(!s&&r.options.strict&&
|
|
355
|
+
`}};Hae.YAMLError=ry;Hae.YAMLParseError=zM;Hae.YAMLWarning=PM;Hae.prettifyError=Kae});var ip=ye(function(Xae){function Yae(e,{flow:t,indicator:r,next:o,offset:n,onError:i,parentIndent:s,startOnNewline:a}){let l=!1,u=a,d=a,p="",m="",h=!1,S=!1,y=null,v=null,x=null,_=null,k=null,O=null,L=null;for(let z of e){if(S){if(z.type!=="space"&&z.type!=="newline"&&z.type!=="comma")i(z.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");S=!1}if(y){if(u&&z.type!=="comment"&&z.type!=="newline")i(y,"TAB_AS_INDENT","Tabs are not allowed as indentation");y=null}switch(z.type){case"space":if(!t&&(r!=="doc-start"||o?.type!=="flow-collection")&&z.source.includes("\t"))y=z;d=!0;break;case"comment":{if(!d)i(z,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let W=z.source.substring(1)||" ";if(!p)p=W;else p+=m+W;m="",u=!1;break}case"newline":if(u){if(p)p+=z.source;else if(!O||r!=="seq-item-ind")l=!0}else m+=z.source;if(u=!0,h=!0,v||x)_=z;d=!0;break;case"anchor":if(v)i(z,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(z.source.endsWith(":"))i(z.offset+z.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);v=z,L??(L=z.offset),u=!1,d=!1,S=!0;break;case"tag":{if(x)i(z,"MULTIPLE_TAGS","A node can have at most one tag");x=z,L??(L=z.offset),u=!1,d=!1,S=!0;break}case r:if(v||x)i(z,"BAD_PROP_ORDER",`Anchors and tags must be after the ${z.source} indicator`);if(O)i(z,"UNEXPECTED_TOKEN",`Unexpected ${z.source} in ${t??"collection"}`);O=z,u=r==="seq-item-ind"||r==="explicit-key-ind",d=!1;break;case"comma":if(t){if(k)i(z,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`);k=z,u=!1,d=!1;break}default:i(z,"UNEXPECTED_TOKEN",`Unexpected ${z.type} token`),u=!1,d=!1}}let P=e[e.length-1],K=P?P.offset+P.source.length:n;if(S&&o&&o.type!=="space"&&o.type!=="newline"&&o.type!=="comma"&&(o.type!=="scalar"||o.source!==""))i(o.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(y&&(u&&y.indent<=s||o?.type==="block-map"||o?.type==="block-seq"))i(y,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:k,found:O,spaceBefore:l,comment:p,hasNewline:h,anchor:v,tag:x,newlineAfterProp:_,end:K,start:L??K}}Xae.resolveProps=Yae});var ny=ye(function(tce){function nR(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
356
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(nR(t.key)||nR(t.value))return!0}return!1;default:return!0}}tce.containsNewline=nR});var oR=ye(function(ice){var nce=ny();function oce(e,t,r){if(t?.type==="flow-collection"){let o=t.end[0];if(o.indent===e&&(o.source==="]"||o.source==="}")&&nce.containsNewline(t))r(o,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}ice.flowIndentCheck=oce});var iR=ye(function(cce){var NM=qe();function ace(e,t,r){let{uniqueKeys:o}=e.options;if(o===!1)return!1;let n=typeof o==="function"?o:(i,s)=>i===s||NM.isScalar(i)&&NM.isScalar(s)&&i.value===s.value;return t.some((i)=>n(i.key,r))}cce.mapIncludes=ace});var BM=ye(function(mce){var DM=Zi(),uce=Bi(),LM=ip(),dce=ny(),ZM=oR(),pce=iR(),jM="All mapping items must start at the same column";function fce({composeNode:e,composeEmptyNode:t},r,o,n,i){let a=new(i?.nodeClass??uce.YAMLMap)(r.schema);if(r.atRoot)r.atRoot=!1;let l=o.offset,u=null;for(let d of o.items){let{start:p,key:m,sep:h,value:S}=d,y=LM.resolveProps(p,{indicator:"explicit-key-ind",next:m??h?.[0],offset:l,onError:n,parentIndent:o.indent,startOnNewline:!0}),v=!y.found;if(v){if(m){if(m.type==="block-seq")n(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in m&&m.indent!==o.indent)n(l,"BAD_INDENT",jM)}if(!y.anchor&&!y.tag&&!h){if(u=y.end,y.comment)if(a.comment)a.comment+=`
|
|
357
|
+
`+y.comment;else a.comment=y.comment;continue}if(y.newlineAfterProp||dce.containsNewline(m))n(m??p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(y.found?.indent!==o.indent)n(l,"BAD_INDENT",jM);r.atKey=!0;let x=y.end,_=m?e(r,m,y,n):t(r,x,p,null,y,n);if(r.schema.compat)ZM.flowIndentCheck(o.indent,m,n);if(r.atKey=!1,pce.mapIncludes(r,a.items,_))n(x,"DUPLICATE_KEY","Map keys must be unique");let k=LM.resolveProps(h??[],{indicator:"map-value-ind",next:S,offset:_.range[2],onError:n,parentIndent:o.indent,startOnNewline:!m||m.type==="block-scalar"});if(l=k.end,k.found){if(v){if(S?.type==="block-map"&&!k.hasNewline)n(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(r.options.strict&&y.start<k.found.offset-1024)n(_.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let O=S?e(r,S,k,n):t(r,l,h,null,k,n);if(r.schema.compat)ZM.flowIndentCheck(o.indent,S,n);l=O.range[2];let L=new DM.Pair(_,O);if(r.options.keepSourceTokens)L.srcToken=d;a.items.push(L)}else{if(v)n(_.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(k.comment)if(_.comment)_.comment+=`
|
|
358
|
+
`+k.comment;else _.comment=k.comment;let O=new DM.Pair(_);if(r.options.keepSourceTokens)O.srcToken=d;a.items.push(O)}}if(u&&u<l)n(u,"IMPOSSIBLE","Map comment with trailing content");return a.range=[o.offset,l,u??l],a}mce.resolveBlockMap=fce});var UM=ye(function(vce){var gce=Ui(),yce=ip(),bce=oR();function Sce({composeNode:e,composeEmptyNode:t},r,o,n,i){let a=new(i?.nodeClass??gce.YAMLSeq)(r.schema);if(r.atRoot)r.atRoot=!1;if(r.atKey)r.atKey=!1;let l=o.offset,u=null;for(let{start:d,value:p}of o.items){let m=yce.resolveProps(d,{indicator:"seq-item-ind",next:p,offset:l,onError:n,parentIndent:o.indent,startOnNewline:!0});if(!m.found)if(m.anchor||m.tag||p)if(p?.type==="block-seq")n(m.end,"BAD_INDENT","All sequence items must start at the same column");else n(l,"MISSING_CHAR","Sequence item without - indicator");else{if(u=m.end,m.comment)a.comment=m.comment;continue}let h=p?e(r,p,m,n):t(r,m.end,d,null,m,n);if(r.schema.compat)bce.flowIndentCheck(o.indent,p,n);l=h.range[2],a.items.push(h)}return a.range=[o.offset,l,u??l],a}vce.resolveBlockSeq=Sce});var el=ye(function(_ce){function xce(e,t,r,o){let n="";if(e){let i=!1,s="";for(let a of e){let{source:l,type:u}=a;switch(u){case"space":i=!0;break;case"comment":{if(r&&!i)o(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=l.substring(1)||" ";if(!n)n=d;else n+=s+d;s="";break}case"newline":if(n)s+=l;i=!0;break;default:o(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}t+=l.length}}return{comment:n,offset:t}}_ce.resolveEnd=xce});var FM=ye(function(Cce){var Ace=qe(),Ice=Zi(),MM=Bi(),kce=Ui(),Rce=el(),qM=ip(),Tce=ny(),$ce=iR(),sR="Block collections are not allowed within flow collections",aR=(e)=>e&&(e.type==="block-map"||e.type==="block-seq");function Oce({composeNode:e,composeEmptyNode:t},r,o,n,i){let s=o.start.source==="{",a=s?"flow map":"flow sequence",u=new(i?.nodeClass??(s?MM.YAMLMap:kce.YAMLSeq))(r.schema);u.flow=!0;let d=r.atRoot;if(d)r.atRoot=!1;if(r.atKey)r.atKey=!1;let p=o.offset+o.start.source.length;for(let v=0;v<o.items.length;++v){let x=o.items[v],{start:_,key:k,sep:O,value:L}=x,P=qM.resolveProps(_,{flow:a,indicator:"explicit-key-ind",next:k??O?.[0],offset:p,onError:n,parentIndent:o.indent,startOnNewline:!1});if(!P.found){if(!P.anchor&&!P.tag&&!O&&!L){if(v===0&&P.comma)n(P.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(v<o.items.length-1)n(P.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`);if(P.comment)if(u.comment)u.comment+=`
|
|
359
|
+
`+P.comment;else u.comment=P.comment;p=P.end;continue}if(!s&&r.options.strict&&Tce.containsNewline(k))n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0){if(P.comma)n(P.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`)}else{if(!P.comma)n(P.start,"MISSING_CHAR",`Missing , between ${a} items`);if(P.comment){let K="";e:for(let z of _)switch(z.type){case"comma":case"space":break;case"comment":K=z.source.substring(1);break e;default:break e}if(K){let z=u.items[u.items.length-1];if(Ace.isPair(z))z=z.value??z.key;if(z.comment)z.comment+=`
|
|
359
360
|
`+K;else z.comment=K;P.comment=P.comment.substring(K.length+1)}}}if(!s&&!O&&!P.found){let K=L?e(r,L,P,n):t(r,P.end,O,null,P,n);if(u.items.push(K),p=K.range[2],aR(L))n(K.range,"BLOCK_IN_FLOW",sR)}else{r.atKey=!0;let K=P.end,z=k?e(r,k,P,n):t(r,K,_,null,P,n);if(aR(k))n(z.range,"BLOCK_IN_FLOW",sR);r.atKey=!1;let W=qM.resolveProps(O??[],{flow:a,indicator:"map-value-ind",next:L,offset:z.range[2],onError:n,parentIndent:o.indent,startOnNewline:!1});if(W.found){if(!s&&!P.found&&r.options.strict){if(O)for(let T of O){if(T===W.found)break;if(T.type==="newline"){n(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(P.start<W.found.offset-1024)n(W.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(L)if("source"in L&&L.source?.[0]===":")n(L,"MISSING_CHAR",`Missing space after : in ${a}`);else n(W.start,"MISSING_CHAR",`Missing , or : between ${a} items`);let ee=L?e(r,L,W,n):W.found?t(r,W.end,O,null,W,n):null;if(ee){if(aR(L))n(ee.range,"BLOCK_IN_FLOW",sR)}else if(W.comment)if(z.comment)z.comment+=`
|
|
360
|
-
`+W.comment;else z.comment=W.comment;let j=new
|
|
361
|
-
`+v.comment;else u.comment=v.comment;u.range=[o.offset,y,v.offset]}else u.range=[o.offset,y,y];return u}
|
|
361
|
+
`+W.comment;else z.comment=W.comment;let j=new Ice.Pair(z,ee);if(r.options.keepSourceTokens)j.srcToken=x;if(s){let T=u;if($ce.mapIncludes(r,T.items,z))n(K,"DUPLICATE_KEY","Map keys must be unique");T.items.push(j)}else{let T=new MM.YAMLMap(r.schema);T.flow=!0,T.items.push(j);let Z=(ee??z).range;T.range=[z.range[0],Z[1],Z[2]],u.items.push(T)}p=ee?ee.range[2]:W.end}}let m=s?"}":"]",[h,...S]=o.end,y=p;if(h?.source===m)y=h.offset+h.source.length;else{let v=a[0].toUpperCase()+a.substring(1),x=d?`${v} must end with a ${m}`:`${v} in block collection must be sufficiently indented and end with a ${m}`;if(n(p,d?"MISSING_CHAR":"BAD_INDENT",x),h&&h.source.length!==1)S.unshift(h)}if(S.length>0){let v=Rce.resolveEnd(S,y,r.options.strict,n);if(v.comment)if(u.comment)u.comment+=`
|
|
362
|
+
`+v.comment;else u.comment=v.comment;u.range=[o.offset,y,v.offset]}else u.range=[o.offset,y,y];return u}Cce.resolveFlowCollection=Oce});var JM=ye(function(Mce){var Pce=qe(),Nce=It(),Dce=Bi(),Lce=Ui(),Zce=BM(),jce=UM(),Bce=FM();function cR(e,t,r,o,n,i){let s=r.type==="block-map"?Zce.resolveBlockMap(e,t,r,o,i):r.type==="block-seq"?jce.resolveBlockSeq(e,t,r,o,i):Bce.resolveFlowCollection(e,t,r,o,i),a=s.constructor;if(n==="!"||n===a.tagName)return s.tag=a.tagName,s;if(n)s.tag=n;return s}function Uce(e,t,r,o,n){let i=o.tag,s=!i?null:t.directives.tagName(i.source,(m)=>n(i,"TAG_RESOLVE_FAILED",m));if(r.type==="block-seq"){let{anchor:m,newlineAfterProp:h}=o,S=m&&i?m.offset>i.offset?m:i:m??i;if(S&&(!h||h.offset<S.offset))n(S,"MISSING_CHAR","Missing newline after block sequence props")}let a=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!i||!s||s==="!"||s===Dce.YAMLMap.tagName&&a==="map"||s===Lce.YAMLSeq.tagName&&a==="seq")return cR(e,t,r,n,s);let l=t.schema.tags.find((m)=>m.tag===s&&m.collection===a);if(!l){let m=t.schema.knownTags[s];if(m?.collection===a)t.schema.tags.push(Object.assign({},m,{default:!1})),l=m;else{if(m)n(i,"BAD_COLLECTION_TYPE",`${m.tag} used for ${a} collection, but expects ${m.collection??"scalar"}`,!0);else n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0);return cR(e,t,r,n,s)}}let u=cR(e,t,r,n,s,l),d=l.resolve?.(u,(m)=>n(i,"TAG_RESOLVE_FAILED",m),t.options)??u,p=Pce.isNode(d)?d:new Nce.Scalar(d);if(p.range=u.range,p.tag=s,l?.format)p.format=l.format;return p}Mce.composeCollection=Uce});var uR=ye(function(Hce){var lR=It();function Fce(e,t,r){let o=t.offset,n=Jce(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[o,o,o]};let i=n.mode===">"?lR.Scalar.BLOCK_FOLDED:lR.Scalar.BLOCK_LITERAL,s=t.source?Kce(t.source):[],a=s.length;for(let y=s.length-1;y>=0;--y){let v=s[y][1];if(v===""||v==="\r")a=y;else break}if(a===0){let y=n.chomp==="+"&&s.length>0?`
|
|
362
363
|
`.repeat(Math.max(1,s.length-1)):"",v=o+n.length;if(t.source)v+=t.source.length;return{value:y,type:i,comment:n.comment,range:[o,v,v]}}let l=t.indent+n.indent,u=t.offset+n.length,d=0;for(let y=0;y<a;++y){let[v,x]=s[y];if(x===""||x==="\r"){if(n.indent===0&&v.length>l)l=v.length}else{if(v.length<l)r(u+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(n.indent===0)l=v.length;if(d=y,l===0&&!e.atRoot)r(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=v.length+x.length+1}for(let y=s.length-1;y>=a;--y)if(s[y][0].length>l)a=y+1;let p="",m="",h=!1;for(let y=0;y<d;++y)p+=s[y][0].slice(l)+`
|
|
363
364
|
`;for(let y=d;y<a;++y){let[v,x]=s[y];u+=v.length+x.length+1;let _=x[x.length-1]==="\r";if(_)x=x.slice(0,-1);if(x&&v.length<l){let O=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(u-x.length-(_?2:1),"BAD_INDENT",O),v=""}if(i===lR.Scalar.BLOCK_LITERAL)p+=m+v.slice(l)+x,m=`
|
|
364
365
|
`;else if(v.length>l||x[0]==="\t"){if(m===" ")m=`
|
|
@@ -373,41 +374,41 @@ ${u}
|
|
|
373
374
|
`+s[y][0].slice(l);if(p[p.length-1]!==`
|
|
374
375
|
`)p+=`
|
|
375
376
|
`;break;default:p+=`
|
|
376
|
-
`}let S=o+n.length+t.source.length;return{value:p,type:i,comment:n.comment,range:[o,S,S]}}function
|
|
377
|
+
`}let S=o+n.length+t.source.length;return{value:p,type:i,comment:n.comment,range:[o,S,S]}}function Jce({offset:e,props:t},r,o){if(t[0].type!=="block-scalar-header")return o(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],i=n[0],s=0,a="",l=-1;for(let m=1;m<n.length;++m){let h=n[m];if(!a&&(h==="-"||h==="+"))a=h;else{let S=Number(h);if(!s&&S)s=S;else if(l===-1)l=e+m}}if(l!==-1)o(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let u=!1,d="",p=n.length;for(let m=1;m<t.length;++m){let h=t[m];switch(h.type){case"space":u=!0;case"newline":p+=h.source.length;break;case"comment":if(r&&!u)o(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");p+=h.source.length,d=h.source.substring(1);break;case"error":o(h,"UNEXPECTED_TOKEN",h.message),p+=h.source.length;break;default:{let S=`Unexpected token in block scalar header: ${h.type}`;o(h,"UNEXPECTED_TOKEN",S);let y=h.source;if(y&&typeof y==="string")p+=y.length}}}return{mode:i,indent:s,chomp:a,comment:d,length:p}}function Kce(e){let t=e.split(/\n( *)/),r=t[0],o=r.match(/^( *)/),i=[o?.[1]?[o[1],r.slice(o[1].length)]:["",r]];for(let s=1;s<t.length;s+=2)i.push([t[s],t[s+1]]);return i}Hce.resolveBlockScalar=Fce});var pR=ye(function(nle){var dR=It(),Wce=el();function Gce(e,t,r){let{offset:o,type:n,source:i,end:s}=e,a,l,u=(m,h,S)=>r(o+m,h,S);switch(n){case"scalar":a=dR.Scalar.PLAIN,l=Qce(i,u);break;case"single-quoted-scalar":a=dR.Scalar.QUOTE_SINGLE,l=Yce(i,u);break;case"double-quoted-scalar":a=dR.Scalar.QUOTE_DOUBLE,l=Xce(i,u);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[o,o+i.length,o+i.length]}}let d=o+i.length,p=Wce.resolveEnd(s,d,t,r);return{value:l,type:a,comment:p.comment,range:[o,d,p.offset]}}function Qce(e,t){let r="";switch(e[0]){case"\t":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}if(r)t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`);return KM(e)}function Yce(e,t){if(e[e.length-1]!=="'"||e.length===1)t(e.length,"MISSING_CHAR","Missing closing 'quote");return KM(e.slice(1,-1)).replace(/''/g,"'")}function KM(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
377
378
|
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
378
379
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let o=t.exec(e);if(!o)return e;let n=o[1],i=" ",s=t.lastIndex;r.lastIndex=s;while(o=r.exec(e)){if(o[1]==="")if(i===`
|
|
379
380
|
`)n+=i;else i=`
|
|
380
|
-
`;else n+=i+o[1],i=" ";s=r.lastIndex}let a=/[ \t]*(.*)/sy;return a.lastIndex=s,o=a.exec(e),n+i+(o?.[1]??"")}function
|
|
381
|
+
`;else n+=i+o[1],i=" ";s=r.lastIndex}let a=/[ \t]*(.*)/sy;return a.lastIndex=s,o=a.exec(e),n+i+(o?.[1]??"")}function Xce(e,t){let r="";for(let o=1;o<e.length-1;++o){let n=e[o];if(n==="\r"&&e[o+1]===`
|
|
381
382
|
`)continue;if(n===`
|
|
382
|
-
`){let{fold:i,offset:s}=
|
|
383
|
+
`){let{fold:i,offset:s}=ele(e,o);r+=i,o=s}else if(n==="\\"){let i=e[++o],s=tle[i];if(s)r+=s;else if(i===`
|
|
383
384
|
`){i=e[o+1];while(i===" "||i==="\t")i=e[++o+1]}else if(i==="\r"&&e[o+1]===`
|
|
384
|
-
`){i=e[++o+1];while(i===" "||i==="\t")i=e[++o+1]}else if(i==="x"||i==="u"||i==="U"){let a=i==="x"?2:i==="u"?4:8;r+=
|
|
385
|
+
`){i=e[++o+1];while(i===" "||i==="\t")i=e[++o+1]}else if(i==="x"||i==="u"||i==="U"){let a=i==="x"?2:i==="u"?4:8;r+=rle(e,o+1,a,t),o+=a}else{let a=e.substr(o-1,2);t(o-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),r+=a}}else if(n===" "||n==="\t"){let i=o,s=e[o+1];while(s===" "||s==="\t")s=e[++o+1];if(s!==`
|
|
385
386
|
`&&!(s==="\r"&&e[o+2]===`
|
|
386
|
-
`))r+=o>i?e.slice(i,o+1):n}else r+=n}if(e[e.length-1]!=='"'||e.length===1)t(e.length,"MISSING_CHAR",'Missing closing "quote');return r}function
|
|
387
|
+
`))r+=o>i?e.slice(i,o+1):n}else r+=n}if(e[e.length-1]!=='"'||e.length===1)t(e.length,"MISSING_CHAR",'Missing closing "quote');return r}function ele(e,t){let r="",o=e[t+1];while(o===" "||o==="\t"||o===`
|
|
387
388
|
`||o==="\r"){if(o==="\r"&&e[t+2]!==`
|
|
388
389
|
`)break;if(o===`
|
|
389
390
|
`)r+=`
|
|
390
|
-
`;t+=1,o=e[t+1]}if(!r)r=" ";return{fold:r,offset:t}}var
|
|
391
|
-
`,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function
|
|
391
|
+
`;t+=1,o=e[t+1]}if(!r)r=" ";return{fold:r,offset:t}}var tle={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
392
|
+
`,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function rle(e,t,r,o){let n=e.substr(t,r),s=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(s)}catch{let a=e.substr(t-2,r+2);return o(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}nle.resolveFlowScalar=Gce});var VM=ye(function(ule){var sa=qe(),HM=It(),ile=uR(),sle=pR();function ale(e,t,r,o){let{value:n,type:i,comment:s,range:a}=t.type==="block-scalar"?ile.resolveBlockScalar(e,t,o):sle.resolveFlowScalar(t,e.options.strict,o),l=r?e.directives.tagName(r.source,(p)=>o(r,"TAG_RESOLVE_FAILED",p)):null,u;if(e.options.stringKeys&&e.atKey)u=e.schema[sa.SCALAR];else if(l)u=cle(e.schema,n,l,r,o);else if(t.type==="scalar")u=lle(e,n,t,o);else u=e.schema[sa.SCALAR];let d;try{let p=u.resolve(n,(m)=>o(r??t,"TAG_RESOLVE_FAILED",m),e.options);d=sa.isScalar(p)?p:new HM.Scalar(p)}catch(p){let m=p instanceof Error?p.message:String(p);o(r??t,"TAG_RESOLVE_FAILED",m),d=new HM.Scalar(n)}if(d.range=a,d.source=n,i)d.type=i;if(l)d.tag=l;if(u.format)d.format=u.format;if(s)d.comment=s;return d}function cle(e,t,r,o,n){if(r==="!")return e[sa.SCALAR];let i=[];for(let a of e.tags)if(!a.collection&&a.tag===r)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(t))return a;let s=e.knownTags[r];if(s&&!s.collection)return e.tags.push(Object.assign({},s,{default:!1,test:void 0})),s;return n(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[sa.SCALAR]}function lle({atKey:e,directives:t,schema:r},o,n,i){let s=r.tags.find((a)=>(a.default===!0||e&&a.default==="key")&&a.test?.test(o))||r[sa.SCALAR];if(r.compat){let a=r.compat.find((l)=>l.default&&l.test?.test(o))??r[sa.SCALAR];if(s.tag!==a.tag){let l=t.tagString(s.tag),u=t.tagString(a.tag),d=`Value may be parsed as either ${l} or ${u}`;i(n,"TAG_RESOLVE_FAILED",d,!0)}}return s}ule.composeScalar=ale});var WM=ye(function(fle){function ple(e,t,r){if(t){r??(r=t.length);for(let o=r-1;o>=0;--o){let n=t[o];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}n=t[++o];while(n?.type==="space")e+=n.source.length,n=t[++o];break}}return e}fle.emptyScalarPosition=ple});var YM=ye(function(xle){var hle=qd(),gle=qe(),yle=JM(),GM=VM(),ble=el(),Sle=WM(),vle={composeNode:QM,composeEmptyNode:fR};function QM(e,t,r,o){let n=e.atKey,{spaceBefore:i,comment:s,anchor:a,tag:l}=r,u,d=!0;switch(t.type){case"alias":if(u=wle(e,t,o),a||l)o(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(u=GM.composeScalar(e,t,l,o),a)u.anchor=a.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(u=yle.composeCollection(vle,e,t,r,o),a)u.anchor=a.source.substring(1)}catch(p){let m=p instanceof Error?p.message:String(p);o(t,"RESOURCE_EXHAUSTION",m)}break;default:{let p=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;o(t,"UNEXPECTED_TOKEN",p),d=!1}}if(u??(u=fR(e,t.offset,void 0,null,r,o)),a&&u.anchor==="")o(a,"BAD_ALIAS","Anchor cannot be an empty string");if(n&&e.options.stringKeys&&(!gle.isScalar(u)||typeof u.value!=="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str"))o(l??t,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(i)u.spaceBefore=!0;if(s)if(t.type==="scalar"&&t.source==="")u.comment=s;else u.commentBefore=s;if(e.options.keepSourceTokens&&d)u.srcToken=t;return u}function fR(e,t,r,o,{spaceBefore:n,comment:i,anchor:s,tag:a,end:l},u){let d={type:"scalar",offset:Sle.emptyScalarPosition(t,r,o),indent:-1,source:""},p=GM.composeScalar(e,d,a,u);if(s){if(p.anchor=s.source.substring(1),p.anchor==="")u(s,"BAD_ALIAS","Anchor cannot be an empty string")}if(n)p.spaceBefore=!0;if(i)p.comment=i,p.range[2]=l;return p}function wle({options:e},{offset:t,source:r,end:o},n){let i=new hle.Alias(r.substring(1));if(i.source==="")n(t,"BAD_ALIAS","Alias cannot be an empty string");if(i.source.endsWith(":"))n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let s=t+r.length,a=ble.resolveEnd(o,s,e.strict,n);if(i.range=[t,s,a.offset],a.comment)i.comment=a.comment;return i}xle.composeEmptyNode=fR;xle.composeNode=QM});var eq=ye(function(Tle){var Ale=np(),XM=YM(),Ile=el(),kle=ip();function Rle(e,t,{offset:r,start:o,value:n,end:i},s){let a=Object.assign({_directives:t},e),l=new Ale.Document(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},d=kle.resolveProps(o,{indicator:"doc-start",next:n??i?.[0],offset:r,onError:s,parentIndent:0,startOnNewline:!0});if(d.found){if(l.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!d.hasNewline)s(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}l.contents=n?XM.composeNode(u,n,d,s):XM.composeEmptyNode(u,d.end,o,null,d,s);let p=l.contents.range[2],m=Ile.resolveEnd(i,p,!1,s);if(m.comment)l.comment=m.comment;return l.range=[r,p,m.offset],l}Tle.composeDoc=Rle});var mR=ye(function(Dle){var Ole=Fr("process"),Cle=bk(),zle=np(),sp=op(),tq=qe(),Ple=eq(),Nle=el();function ap(e){if(typeof e==="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r==="string"?r.length:1)]}function rq(e){let t="",r=!1,o=!1;for(let n=0;n<e.length;++n){let i=e[n];switch(i[0]){case"#":t+=(t===""?"":o?`
|
|
392
393
|
|
|
393
394
|
`:`
|
|
394
|
-
`)+(i.substring(1)||" "),r=!0,o=!1;break;case"%":if(e[n+1]?.[0]!=="#")n+=1;r=!1;break;default:if(!r)o=!0;r=!1}}return{comment:t,afterEmptyLine:o}}class nq{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,r,o,n)=>{let i=ap(t);if(n)this.warnings.push(new sp.YAMLWarning(i,r,o));else this.errors.push(new sp.YAMLParseError(i,r,o))},this.directives=new
|
|
395
|
+
`)+(i.substring(1)||" "),r=!0,o=!1;break;case"%":if(e[n+1]?.[0]!=="#")n+=1;r=!1;break;default:if(!r)o=!0;r=!1}}return{comment:t,afterEmptyLine:o}}class nq{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,r,o,n)=>{let i=ap(t);if(n)this.warnings.push(new sp.YAMLWarning(i,r,o));else this.errors.push(new sp.YAMLParseError(i,r,o))},this.directives=new Cle.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:r,afterEmptyLine:o}=rq(this.prelude);if(r){let n=e.contents;if(t)e.comment=e.comment?`${e.comment}
|
|
395
396
|
${r}`:r;else if(o||e.directives.docStart||!n)e.commentBefore=r;else if(tq.isCollection(n)&&!n.flow&&n.items.length>0){let i=n.items[0];if(tq.isPair(i))i=i.key;let s=i.commentBefore;i.commentBefore=s?`${r}
|
|
396
397
|
${s}`:r}else{let i=n.commentBefore;n.commentBefore=i?`${r}
|
|
397
|
-
${i}`:r}}if(t){for(let n=0;n<this.errors.length;++n)e.errors.push(this.errors[n]);for(let n=0;n<this.warnings.length;++n)e.warnings.push(this.warnings[n])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:rq(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,r=-1){for(let o of e)yield*this.next(o);yield*this.end(t,r)}*next(e){if(
|
|
398
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new sp.YAMLParseError(ap(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),o=new
|
|
398
|
+
${i}`:r}}if(t){for(let n=0;n<this.errors.length;++n)e.errors.push(this.errors[n]);for(let n=0;n<this.warnings.length;++n)e.warnings.push(this.warnings[n])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:rq(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,r=-1){for(let o of e)yield*this.next(o);yield*this.end(t,r)}*next(e){if(Ole.env.LOG_STREAM)console.dir(e,{depth:null});switch(e.type){case"directive":this.directives.add(e.source,(t,r,o)=>{let n=ap(e);n[0]+=t,this.onError(n,"BAD_DIRECTIVE",r,o)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=Ple.composeDoc(this.options,this.directives,e,this.onError);if(this.atDirectives&&!t.directives.docStart)this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(t,!1),this.doc)yield this.doc;this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new sp.YAMLParseError(ap(e),"UNEXPECTED_TOKEN",t);if(this.atDirectives||!this.doc)this.errors.push(r);else this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){this.errors.push(new sp.YAMLParseError(ap(e),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let t=Nle.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
399
|
+
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new sp.YAMLParseError(ap(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),o=new zle.Document(void 0,r);if(this.atDirectives)this.onError(t,"MISSING_CHAR","Missing directives-end indicator line");o.range=[0,t,t],this.decorate(o,!1),yield o}}}Dle.Composer=nq});var sq=ye(function(Jle){var Zle=uR(),jle=pR(),Ble=op(),oq=Hd();function Ule(e,t=!0,r){if(e){let o=(n,i,s)=>{let a=typeof n==="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(a,i,s);else throw new Ble.YAMLParseError([a,a+1],i,s)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return jle.resolveFlowScalar(e,t,o);case"block-scalar":return Zle.resolveBlockScalar({options:{strict:t}},e,o)}}return null}function Mle(e,t){let{implicitKey:r=!1,indent:o,inFlow:n=!1,offset:i=-1,type:s="PLAIN"}=t,a=oq.stringifyString({type:s,value:e},{implicitKey:r,indent:o>0?" ".repeat(o):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:"newline",offset:-1,indent:o,source:`
|
|
399
400
|
`}];switch(a[0]){case"|":case">":{let u=a.indexOf(`
|
|
400
401
|
`),d=a.substring(0,u),p=a.substring(u+1)+`
|
|
401
402
|
`,m=[{type:"block-scalar-header",offset:i,indent:o,source:d}];if(!iq(m,l))m.push({type:"newline",offset:-1,indent:o,source:`
|
|
402
|
-
`});return{type:"block-scalar",offset:i,indent:o,props:m,source:p}}case'"':return{type:"double-quoted-scalar",offset:i,indent:o,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:i,indent:o,source:a,end:l};default:return{type:"scalar",offset:i,indent:o,source:a,end:l}}}function
|
|
403
|
+
`});return{type:"block-scalar",offset:i,indent:o,props:m,source:p}}case'"':return{type:"double-quoted-scalar",offset:i,indent:o,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:i,indent:o,source:a,end:l};default:return{type:"scalar",offset:i,indent:o,source:a,end:l}}}function qle(e,t,r={}){let{afterKey:o=!1,implicitKey:n=!1,inFlow:i=!1,type:s}=r,a="indent"in e?e.indent:null;if(o&&typeof a==="number")a+=2;if(!s)switch(e.type){case"single-quoted-scalar":s="QUOTE_SINGLE";break;case"double-quoted-scalar":s="QUOTE_DOUBLE";break;case"block-scalar":{let u=e.props[0];if(u.type!=="block-scalar-header")throw Error("Invalid block scalar header");s=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:s="PLAIN"}let l=oq.stringifyString({type:s,value:t},{implicitKey:n||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":Fle(e,l);break;case'"':hR(e,l,"double-quoted-scalar");break;case"'":hR(e,l,"single-quoted-scalar");break;default:hR(e,l,"scalar")}}function Fle(e,t){let r=t.indexOf(`
|
|
403
404
|
`),o=t.substring(0,r),n=t.substring(r+1)+`
|
|
404
405
|
`;if(e.type==="block-scalar"){let i=e.props[0];if(i.type!=="block-scalar-header")throw Error("Invalid block scalar header");i.source=o,e.source=n}else{let{offset:i}=e,s="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:s,source:o}];if(!iq(a,"end"in e?e.end:void 0))a.push({type:"newline",offset:-1,indent:s,source:`
|
|
405
406
|
`});for(let l of Object.keys(e))if(l!=="type"&&l!=="offset")delete e[l];Object.assign(e,{type:"block-scalar",indent:s,props:a,source:n})}}function iq(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function hR(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let o=e.props.slice(1),n=t.length;if(e.props[0].type==="block-scalar-header")n-=e.props[0].source.length;for(let i of o)i.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:o});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
406
|
-
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let o="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter((i)=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(e))if(i!=="type"&&i!=="offset")delete e[i];Object.assign(e,{type:r,indent:o,source:t,end:n})}}}
|
|
407
|
+
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let o="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter((i)=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(e))if(i!=="type"&&i!=="offset")delete e[i];Object.assign(e,{type:r,indent:o,source:t,end:n})}}}Jle.createScalarToken=Mle;Jle.resolveAsScalar=Ule;Jle.setScalarValue=qle});var aq=ye(function(Gle){var Wle=(e)=>("type"in e)?iy(e):oy(e);function iy(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=iy(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=oy(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=oy(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=oy(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function oy({start:e,key:t,sep:r,value:o}){let n="";for(let i of e)n+=i.source;if(t)n+=iy(t);if(r)for(let i of r)n+=i.source;if(o)n+=iy(o);return n}Gle.stringify=Wle});var uq=ye(function(Xle){var gR=Symbol("break visit"),Yle=Symbol("skip children"),cq=Symbol("remove item");function aa(e,t){if("type"in e&&e.type==="document")e={start:e.start,value:e.value};lq(Object.freeze([]),e,t)}aa.BREAK=gR;aa.SKIP=Yle;aa.REMOVE=cq;aa.itemAtPath=(e,t)=>{let r=e;for(let[o,n]of t){let i=r?.[o];if(i&&"items"in i)r=i.items[n];else return}return r};aa.parentCollection=(e,t)=>{let r=aa.itemAtPath(e,t.slice(0,-1)),o=t[t.length-1][0],n=r?.[o];if(n&&"items"in n)return n;throw Error("Parent collection not found")};function lq(e,t,r){let o=r(t,e);if(typeof o==="symbol")return o;for(let n of["key","value"]){let i=t[n];if(i&&"items"in i){for(let s=0;s<i.items.length;++s){let a=lq(Object.freeze(e.concat([[n,s]])),i.items[s],r);if(typeof a==="number")s=a-1;else if(a===gR)return gR;else if(a===cq)i.items.splice(s,1),s-=1}if(typeof o==="function"&&n==="key")o=o(t,e)}}return typeof o==="function"?o(t,e):o}Xle.visit=aa});var sy=ye(function(aue){var yR=sq(),tue=aq(),rue=uq(),bR="\uFEFF",SR="\x02",vR="\x18",wR="\x1F",nue=(e)=>!!e&&("items"in e),oue=(e)=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function iue(e){switch(e){case bR:return"<BOM>";case SR:return"<DOC>";case vR:return"<FLOW_END>";case wR:return"<SCALAR>";default:return JSON.stringify(e)}}function sue(e){switch(e){case bR:return"byte-order-mark";case SR:return"doc-mode";case vR:return"flow-error-end";case wR:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
407
408
|
`:case`\r
|
|
408
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}
|
|
409
|
-
`:case"\r":case"\t":return!0;default:return!1}}var dq=new Set("0123456789ABCDEFabcdef"),
|
|
410
|
-
\r `),xR=(e)=>!e||
|
|
409
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}aue.createScalarToken=yR.createScalarToken;aue.resolveAsScalar=yR.resolveAsScalar;aue.setScalarValue=yR.setScalarValue;aue.stringify=tue.stringify;aue.visit=rue.visit;aue.BOM=bR;aue.DOCUMENT=SR;aue.FLOW_END=vR;aue.SCALAR=wR;aue.isCollection=nue;aue.isScalar=oue;aue.prettyToken=iue;aue.tokenType=sue});var _R=ye(function(_ue){var cp=sy();function Sn(e){switch(e){case void 0:case" ":case`
|
|
410
|
+
`:case"\r":case"\t":return!0;default:return!1}}var dq=new Set("0123456789ABCDEFabcdef"),wue=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ay=new Set(",[]{}"),xue=new Set(` ,[]{}
|
|
411
|
+
\r `),xR=(e)=>!e||xue.has(e);class pq{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let r=this.next??"stream";while(r&&(t||this.hasChars(1)))r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,t=this.buffer[e];while(t===" "||t==="\t")t=this.buffer[++e];if(!t||t==="#"||t===`
|
|
411
412
|
`)return!0;if(t==="\r")return this.buffer[e+1]===`
|
|
412
413
|
`;return!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let r=0;while(t===" ")t=this.buffer[++r+e];if(t==="\r"){let o=this.buffer[r+e+1];if(o===`
|
|
413
414
|
`||!o&&!this.atEnd)return e+r+1}return t===`
|
|
@@ -422,14 +423,14 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
422
423
|
`&&n>=this.pos&&n+1+t>s)e=n;else break}while(!0);return yield cp.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,r=this.pos-1,o;while(o=this.buffer[++r])if(o===":"){let n=this.buffer[r+1];if(Sn(n)||e&&ay.has(n))break;t=r}else if(Sn(o)){let n=this.buffer[r+1];if(o==="\r")if(n===`
|
|
423
424
|
`)r+=1,o=`
|
|
424
425
|
`,n=this.buffer[r+1];else t=r;if(n==="#"||e&&ay.has(n))break;if(o===`
|
|
425
|
-
`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(e&&ay.has(o))break;t=r}if(!o&&!this.atEnd)return this.setNext("plain-scalar");return yield cp.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc"}*pushCount(e){if(e>0)return yield this.buffer.substr(this.pos,e),this.pos+=e,e;return 0}*pushToIndex(e,t){let r=this.buffer.slice(this.pos,e);if(r)return yield r,this.pos+=r.length,r.length;else if(t)yield"";return 0}*pushIndicators(){let e=0;e:while(!0){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(xR),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,r=this.charAt(1);if(Sn(r)||t&&ay.has(r)){if(!t)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];while(!Sn(t)&&t!==">")t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];while(t)if(
|
|
426
|
+
`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(e&&ay.has(o))break;t=r}if(!o&&!this.atEnd)return this.setNext("plain-scalar");return yield cp.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc"}*pushCount(e){if(e>0)return yield this.buffer.substr(this.pos,e),this.pos+=e,e;return 0}*pushToIndex(e,t){let r=this.buffer.slice(this.pos,e);if(r)return yield r,this.pos+=r.length,r.length;else if(t)yield"";return 0}*pushIndicators(){let e=0;e:while(!0){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(xR),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,r=this.charAt(1);if(Sn(r)||t&&ay.has(r)){if(!t)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];while(!Sn(t)&&t!==">")t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];while(t)if(wue.has(t))t=this.buffer[++e];else if(t==="%"&&dq.has(this.buffer[e+1])&&dq.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];if(e===`
|
|
426
427
|
`)return yield*this.pushCount(1);else if(e==="\r"&&this.charAt(1)===`
|
|
427
|
-
`)return yield*this.pushCount(2);else return 0}*pushSpaces(e){let t=this.pos-1,r;do r=this.buffer[++t];while(r===" "||e&&r==="\t");let o=t-this.pos;if(o>0)yield this.buffer.substr(this.pos,o),this.pos=t;return o}*pushUntil(e){let t=this.pos,r=this.buffer[t];while(!e(r))r=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}
|
|
428
|
+
`)return yield*this.pushCount(2);else return 0}*pushSpaces(e){let t=this.pos-1,r;do r=this.buffer[++t];while(r===" "||e&&r==="\t");let o=t-this.pos;if(o>0)yield this.buffer.substr(this.pos,o),this.pos=t;return o}*pushUntil(e){let t=this.pos,r=this.buffer[t];while(!e(r))r=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}_ue.Lexer=pq});var ER=ye(function(Aue){class fq{constructor(){this.lineStarts=[],this.addNewLine=(e)=>this.lineStarts.push(e),this.linePos=(e)=>{let t=0,r=this.lineStarts.length;while(t<r){let n=t+r>>1;if(this.lineStarts[n]<e)t=n+1;else r=n}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let o=this.lineStarts[t-1];return{line:t,col:e-o+1}}}}Aue.LineCounter=fq});var AR=ye(function(Tue){var kue=Fr("process"),mq=sy(),Rue=_R();function Mi(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function hq(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function yq(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function cy(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function tl(e){if(e.length===0)return[];let t=e.length;e:while(--t>=0)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}while(e[++t]?.type==="space");return e.splice(t,e.length)}function ly(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function gq(e){if(e.start.type==="flow-seq-start"){for(let t of e.items)if(t.sep&&!t.value&&!Mi(t.start,"explicit-key-ind")&&!Mi(t.sep,"map-value-ind")){if(t.key)t.value=t.key;if(delete t.key,yq(t.value))if(t.value.end)ly(t.value.end,t.sep);else t.value.end=t.sep;else ly(t.start,t.sep);delete t.sep}}}class bq{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Rue.Lexer,this.onNewLine=e}*parse(e,t=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let r of this.lexer.lex(e,t))yield*this.next(r);if(!t)yield*this.end()}*next(e){if(this.source=e,kue.env.LOG_TOKENS)console.log("|",mq.prettyToken(e));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=mq.tokenType(e);if(!t){let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.length}else if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+e.length);break;case"space":if(this.atNewLine&&e[0]===" ")this.indent+=e.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=e.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let r=this.peek(1);if(t.type==="block-scalar")t.indent="indent"in r?r.indent:0;else if(t.type==="flow-collection"&&r.type==="document")t.indent=0;if(t.type==="flow-collection")gq(t);switch(r.type){case"document":r.value=t;break;case"block-scalar":r.props.push(t);break;case"block-map":{let o=r.items[r.items.length-1];if(o.value){r.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(o.sep)o.value=t;else{Object.assign(o,{key:t,sep:[]}),this.onKeyLine=!o.explicitKey;return}break}case"block-seq":{let o=r.items[r.items.length-1];if(o.value)r.items.push({start:[],value:t});else o.value=t;break}case"flow-collection":{let o=r.items[r.items.length-1];if(!o||o.value)r.items.push({start:[],key:t,sep:[]});else if(o.sep)o.value=t;else Object.assign(o,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let o=t.items[t.items.length-1];if(o&&!o.sep&&!o.value&&o.start.length>0&&hq(o.start)===-1&&(t.indent===0||o.start.every((n)=>n.type!=="comment"||n.indent<t.indent))){if(r.type==="document")r.end=o.start;else r.items.push({start:o.start});t.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")e.start.push(this.sourceToken);this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{if(hq(e.start)!==-1)yield*this.pop(),yield*this.step();else e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);if(t)this.stack.push(t);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=cy(this.peek(2)),r=tl(t),o;if(e.end)o=e.end,o.push(this.sourceToken),delete e.end;else o=[this.sourceToken];let n={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=n}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
|
|
428
429
|
`)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
429
430
|
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let r="end"in t.value?t.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){ly(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",n=[];if(o&&t.sep&&!t.value){let i=[];for(let s=0;s<t.sep.length;++s){let a=t.sep[s];switch(a.type){case"newline":i.push(s);break;case"space":break;case"comment":if(a.indent>e.indent)i.length=0;break;default:i.length=0}}if(i.length>=2)n=t.sep.splice(i[1])}switch(this.type){case"anchor":case"tag":if(o||t.value)n.push(this.sourceToken),e.items.push({start:n}),this.onKeyLine=!0;else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"explicit-key-ind":if(!t.sep&&!t.explicitKey)t.start.push(this.sourceToken),t.explicitKey=!0;else if(o||t.value)n.push(this.sourceToken),e.items.push({start:n,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(!t.sep)if(Mi(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let i=tl(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Mi(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]});else if(yq(t.key)&&!Mi(t.sep,"newline")){let i=tl(t.start),s=t.key,a=t.sep;a.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:s,sep:a}]})}else if(n.length>0)t.sep=t.sep.concat(n,this.sourceToken);else t.sep.push(this.sourceToken);else if(!t.sep)Object.assign(t,{key:null,sep:[this.sourceToken]});else if(t.value||o)e.items.push({start:n,key:null,sep:[this.sourceToken]});else if(Mi(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else t.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);if(o||t.value)e.items.push({start:n,key:i,sep:[]}),this.onKeyLine=!0;else if(t.sep)this.stack.push(i);else Object.assign(t,{key:i,sep:[]}),this.onKeyLine=!0;return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Mi(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(r)e.items.push({start:n});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let r="end"in t.value?t.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){ly(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;if(t.value||Mi(t.start,"seq-item-ind"))e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!t||t.sep)e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return;case"map-value-ind":if(!t||t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!t||t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);if(!t||t.value)e.items.push({start:[],key:o,sep:[]});else if(t.sep)this.stack.push(o);else Object.assign(t,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);if(r)this.stack.push(r);else yield*this.pop(),yield*this.step()}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=cy(r),n=tl(o);gq(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
430
431
|
`)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
431
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=cy(e),r=tl(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=cy(e),r=tl(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((r)=>r.type==="newline"||r.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}
|
|
432
|
-
`)}function Pq(e,t,r,o){if(!vn(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>Po(s.key)&&s.key.value===t),i=e.createPair(r,[...o]);if(n>=0){let s=e.contents.items[n];Tq(s?.key,i.key),Tq(s?.value,i.value),e.contents.items.splice(n,1,i)}else e.contents.add(i);return i}function Nq(e){let t=zq(e),r=zde(t.toJS()),o=CR(t,"schemaVersion"),n=CR(t,"model");$q(o,CR(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",Qs);let i=Pq(t,"preset","bundles",r.bundles);if($q(n,i.key),t.delete("model"),r.add)t.set("add",r.add);else t.delete("add");if(r.remove)t.set("remove",r.remove);else t.delete("remove");return Fi(t),Ys.parse(t.toJS()),t.toString({lineWidth:0})}function Dq(e){let t=zq(e),r=Pde(t.toJS());if(r.bundlesOverride)Pq(t,"presetOverride","bundlesOverride",r.bundlesOverride);else t.delete("presetOverride"),t.delete("bundlesOverride");if(r.addOverride)t.set("addOverride",r.addOverride);else t.delete("addOverride");if(r.removeOverride)t.set("removeOverride",r.removeOverride);else t.delete("removeOverride");return Fi(t),hn.parse(t.toJS()),t.toString({lineWidth:0})}var Oq,up,$de,Ode,Cde;var Lq=b(()=>{my();Vn();ue();rl();$o();Oq=c.enum(["core","default","pro"]),up=c.string().min(1),$de=c.strictObject({schemaVersion:c.literal(1),brainVersion:Ct,model:c.literal("rover"),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),preset:Oq,aiApiKey:up,gitSyncToken:up,contentRepoAdminToken:up,agePublicKey:c.string().startsWith("age1").min(1)}),Ode=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),presetOverride:Oq.optional(),aiApiKeyOverride:up.optional(),gitSyncTokenOverride:up.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:c.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),Cde=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function jq(e,t){let r=tn(e,{keepSourceTokens:!0});if(r.errors.length>0||!vn(r.contents))throw Error(`Invalid ${t} YAML`);return r}function jde(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Bq(e,t,r){if(!jde(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function Uq(e){let t=yr(e,Zde);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function Mq(e,t){let r=jq(e,"pilot desired-state"),o=Dde.parse(r.toJS());return Bq("pilot.yaml",o.bundles,t),r.set("bundleContract",Qs),r.set("bundles",t.targetBundles),Fi(r),Ys.parse(r.toJS()),r.toString({lineWidth:0})}function qq(e,t,r){let o=jq(e,`cohort ${t}`),n=Lde.parse(o.toJS());if(n.bundlesOverride===void 0){if(r!==void 0)throw Error(`Capability bundle review names inheriting cohort ${t}`)}else{if(r===void 0)throw Error(`Cohort ${t} has an explicit legacy bundle selection but no reviewed mapping`);Bq(`cohort ${t}`,n.bundlesOverride,r),o.set("bundlesOverride",r.targetBundles)}return Fi(o),hn.parse(o.toJS()),o.toString({lineWidth:0})}var Nde,zR,hy,Dde,Lde,Zq,Zde;var Fq=b(()=>{my();Vn();ue();rl();$o();Nde=c.enum(["core","site","publishing","team"]),zR=c.array(Nde).min(1),hy=c.array(c.string().min(1)),Dde=c.strictObject({brainVersion:Ct,bundles:zR,add:hy.optional(),remove:hy.optional(),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),aiApiKey:c.string().min(1),gitSyncToken:c.string().min(1),contentRepoAdminToken:c.string().min(1),agePublicKey:c.string().startsWith("age1").min(1)}),Lde=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),bundlesOverride:zR.optional(),addOverride:hy.optional(),removeOverride:hy.optional(),aiApiKeyOverride:c.string().min(1).optional(),gitSyncTokenOverride:c.string().min(1).optional()}),Zq=c.strictObject({sourceBundles:zR,targetBundles:c.array(KI).min(1)}),Zde=c.strictObject({bundleContract:c.literal(Qs),pilot:Zq,cohorts:c.record(br,Zq)})});var Wq={};Lt(Wq,{loadCapabilityBundleReview:()=>Vde,loadReviewedSitePins:()=>Hde,parseReviewedSitePins:()=>Vq,stageLegacyCrossover:()=>Gde});import{access as Bde,cp as Ude,mkdir as Jq,readFile as ol,readdir as Hq,writeFile as nl}from"fs/promises";import{basename as Mde,join as eo,relative as gy,resolve as Kq}from"path";import{fileURLToPath as qde}from"url";function Vq(e){let t=yr(e,Fde);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function Hde(e){return Vq(await ol(e,"utf8"))}async function Vde(e){return Uq(await ol(e,"utf8"))}async function Wde(e,t){let r=eo(e,"users"),o=(await Hq(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),i=[];for(let s of o){let a=eo(r,s),l=await ol(a,"utf8"),u=tn(l,{keepSourceTokens:!0});if(u.errors.length>0||!vn(u.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let d=Jde.parse(u.toJS());if(!d.siteOverride)continue;let p=t?.[d.handle];if(!p)throw Error(`User ${d.handle} has a siteOverride but no reviewed site pin`);if(n.delete(d.handle),p.package!==d.siteOverride.package||p.theme!==d.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${d.handle}`);if(d.siteOverride.version!==void 0&&d.siteOverride.version!==p.version)throw Error(`Reviewed site version does not match the existing pin for user ${d.handle}`);if(d.siteOverride.themeVersion!==void 0&&d.siteOverride.themeVersion!==p.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${d.handle}`);if(u.setIn(["siteOverride","version"],p.version),p.themeVersion!==void 0)u.setIn(["siteOverride","themeVersion"],p.themeVersion);else u.deleteIn(["siteOverride","themeVersion"]);dg.parse(u.toJS());let m=u.toString({lineWidth:0});if(m!==l)await nl(a,m),i.push(gy(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return i}async function Gde(e,t,r={}){let o=Kq(e),n=Kq(t);if(o===n||n.startsWith(`${o}/`))throw Error("Crossover output must be outside the source repository");await Ude(o,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(k)=>{let O=Mde(k);return O!==".git"&&O!==".operator"&&O!==".brains-ops"&&O!==".turbo"&&O!=="dist"&&O!=="node_modules"&&O!==".env"&&O!==".env.local"&&!O.endsWith(".secrets.yaml")}});let i=[],s=eo(n,"docs","canonical-crossover-record.md");try{await Bde(s)}catch{await Jq(eo(n,"docs"),{recursive:!0}),await nl(s,await ol(Kde,"utf8")),i.push("docs/canonical-crossover-record.md")}let a=eo(n,"pilot.yaml"),l=await ol(a,"utf8"),d=tn(l).toJS();if(!Nd(d))throw Error(`${a} is not a YAML mapping`);let p=Array.isArray(d.bundles),m=r.bundleReview,h;if(p){if(!m)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");h=Mq(l,m.pilot)}else h=Nq(l);await nl(a,h),i.push("pilot.yaml");let S=eo(n,"cohorts"),y=(await Hq(S,{withFileTypes:!0})).filter((k)=>k.isFile()&&/\.ya?ml$/.test(k.name)).map((k)=>k.name).sort(),v=new Set(Object.keys(m?.cohorts??{}));for(let k of y){let O=eo(S,k),L=await ol(O,"utf8"),P=k.replace(/\.ya?ml$/,""),K=m?.cohorts[P];if(K)v.delete(P);await nl(O,p?qq(L,P,K):Dq(L)),i.push(gy(n,O))}if(p&&v.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...v].sort().join(", ")}`);i.push(...await Wde(n,r.sitePins));let x=await xt(n),_=hg(x.pilot.githubOrg);for(let k of x.users){let O=await _(k),L=eo(n,"users",k.handle);if(await Jq(L,{recursive:!0}),O.brainYaml){let P=eo(L,"brain.yaml");await nl(P,O.brainYaml),i.push(gy(n,P))}if(O.envFile){let P=eo(L,".env");await nl(P,O.envFile),i.push(gy(n,P))}}return await Pi(n,{registry:x}),i.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(i)].sort()}}var Fde,Jde,Kde;var Gq=b(()=>{Vn();Dd();ue();rl();ak();Lq();Fq();gn();Pd();$o();Fde=c.strictObject({sites:c.record(br,HI)}),Jde=c.object({handle:br,siteOverride:c.object({package:c.string().min(1),version:Ct.optional(),theme:c.string().min(1).optional(),themeVersion:Ct.optional()}).optional()}).passthrough(),Kde=qde(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var Yq,Qde,Yde,Xde,to,dp,epe,PR,tpe,rpe,Qq,npe,ope,Xq,QPe,e6;var yy=b(()=>{eI();Yq=["primary","secondary"],Qde=c.custom((e)=>typeof e==="function","Expected a React component"),Yde=c.strictObject({show:c.boolean().optional(),label:c.string().min(1).optional(),slot:c.enum(Yq).optional(),priority:c.number().optional()}),Xde=c.strictObject({id:c.string().min(1),template:c.string().min(1),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.record(c.string(),c.unknown()).optional()}).optional(),order:c.number().optional()}),to=c.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),dp=c.strictObject({title:c.string().optional(),description:c.string().optional(),navigationLabel:c.string().optional()}),epe=c.strictObject({id:c.string().min(1),path:c.string().startsWith("/"),title:c.string().optional(),pageLabel:c.string().optional(),description:c.string().optional(),sections:c.array(Xde).optional(),layout:c.string().min(1).optional(),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),sourceEntityId:c.string().optional(),external:c.boolean().optional(),navigation:Yde.optional(),translations:c.record(to,dp).optional()}),PR=c.strictObject({label:c.string().min(1),pluralName:c.string().min(1).optional(),layout:c.string().min(1).optional(),detailTemplate:c.string().min(1).optional(),paginate:c.boolean().optional(),pageSize:c.number().int().positive().optional(),citable:c.boolean().optional(),navigation:c.strictObject({show:c.boolean().optional(),slot:c.enum(Yq).optional(),priority:c.number().optional()}).optional()}),tpe=c.strictObject({schema:c.custom((e)=>e instanceof c.ZodType,"Expected a Zod schema"),component:c.custom((e)=>typeof e==="function","Expected a React component"),title:c.string().min(1),description:c.string(),requiredPermission:c.enum(["admin","trusted","public"]).optional(),fullscreen:c.boolean().optional(),dataSource:c.string().min(1).optional(),components:c.record(to,c.custom((e)=>typeof e==="function","Expected a React component")).optional()}),rpe=c.custom((e)=>typeof e==="object"&&e!==null&&Reflect.get(e,"kind")==="rizom-data-source"&&typeof Reflect.get(e,"id")==="string"&&typeof Reflect.get(e,"fetch")==="function","Expected a fetching data source declared with defineDataSource"),Qq=c.strictObject({namespace:c.string().min(1),sections:c.record(c.string(),tpe)}),npe=c.record(c.string(),c.json()),ope=c.record(c.string(),c.record(c.string(),npe)),Xq={layouts:c.record(c.string(),Qde).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:c.array(epe),content:ope.optional(),sections:c.union([Qq,c.array(Qq)]).optional(),themeOverride:c.string().optional(),headScripts:c.array(c.string()).optional(),entityDisplay:c.record(c.string(),PR),staticAssets:c.record(c.string(),c.string()).optional(),languages:c.array(to).min(1).optional(),dataSources:c.array(rpe).readonly().optional()},QPe=c.strictObject(Xq).partial(),e6=c.strictObject(Xq).superRefine((e,t)=>{let r=e.languages??[],o=new Set;for(let[u,d]of r.entries()){let p=d.toLowerCase();if(o.has(p))t.addIssue({code:"custom",path:["languages",u],message:`Language "${d}" is declared twice`});o.add(p)}let n=r.slice(1).map((u)=>`/${u.toLowerCase()}`),i=new Set;for(let[u,d]of e.routes.entries()){if(i.has(d.id))t.addIssue({code:"custom",path:["routes",u,"id"],message:`Duplicate route id "${d.id}"`});i.add(d.id);let p=d.path.toLowerCase(),m=n.find((S)=>p===S||p.startsWith(`${S}/`));if(m)t.addIssue({code:"custom",path:["routes",u,"path"],message:`Route path "${d.path}" is under ${m}, where another language's pages are built`});let h=d.layout??"default";if(!e.layouts[h])t.addIssue({code:"custom",path:["routes",u,"layout"],message:`Unknown layout "${h}"`});for(let[S,y]of(d.sections??[]).entries()){let v=/^([^:.\s]+)\.([^:.\s]+)$/.exec(y.template);if(v)t.addIssue({code:"custom",path:["routes",u,"sections",S,"template"],message:`Section template "${y.template}" is written "${v[1]}:${v[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],a=new Map(s.map((u)=>[u.namespace,u]));if(a.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});let l=new Set;for(let[u,d]of(e.dataSources??[]).entries()){if(l.has(d.id))t.addIssue({code:"custom",path:["dataSources",u],message:`Data source "${d.id}" is declared twice`});l.add(d.id)}for(let u of s)for(let[d,p]of Object.entries(u.sections))if(p.dataSource&&!l.has(p.dataSource))t.addIssue({code:"custom",path:["sections",u.namespace,d,"dataSource"],message:`Section "${u.namespace}:${d}" reads data source "${p.dataSource}", which the site does not declare`});for(let[u,d]of Object.entries(e.content??{})){let p=a.get(u);if(!p){t.addIssue({code:"custom",path:["content",u],message:`Content namespace "${u}" has no section group`});continue}for(let[m,h]of Object.entries(d)){let S=p.sections[m];if(!S){t.addIssue({code:"custom",path:["content",u,m],message:`Content section "${u}:${m}" is not defined`});continue}let y=S.schema.safeParse(h);if(!y.success)t.addIssue({code:"custom",path:["content",u,m],message:`Content does not satisfy the "${u}:${m}" schema: ${c.prettifyError(y.error)}`})}}})});var t6,r6,n6,by,o6,spe,i6,s6,ape,a6,c6,cpe,Sy;var NR=b(()=>{wt();ue();yy();yy();t6=c.object({id:c.string(),template:c.string(),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.looseObject({id:c.string().optional(),limit:c.number().optional(),offset:c.number().optional()}).optional()}).optional(),order:c.number().optional()}),r6=["primary","secondary"],n6=c.object({show:c.boolean().default(!1),label:c.string().optional(),slot:c.enum(r6).default("primary"),priority:c.number().min(0).max(100).default(50)}).optional(),by=c.object({id:c.string(),path:c.string(),title:c.string().default(""),pageLabel:c.string().optional(),description:c.string().default(""),sections:c.array(t6).default([]),layout:c.string().default("default"),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),sourceEntityId:c.string().optional(),external:c.boolean().optional(),navigation:n6,translations:c.record(to,dp).optional(),languages:c.array(to).optional()}),o6=c.object({routes:c.array(by),pluginId:c.string()}),spe=he({channel:"plugin:site-builder:route:register",request:o6,response:c.void(),delivery:"command"}),i6=c.strictObject({}),s6=c.array(by),ape=he({channel:"site-builder:routes:list",request:i6,response:s6,delivery:"request"}),a6=c.strictObject({}),c6=c.array(by),cpe=he({channel:"plugin:site-builder:pages",request:a6,response:c6,delivery:"collect"}),Sy=c.object({label:c.string(),href:c.string(),priority:c.number()})});var l6,u6,d6,lpe;var p6=b(()=>{wt();ue();l6=c.object({pluginId:c.string(),slotName:c.string(),render:c.custom((e)=>typeof e==="function"),priority:c.number().optional()}),u6=c.strictObject({}),d6=c.array(l6),lpe=he({channel:"plugin:site-builder:slots",request:u6,response:d6,delivery:"collect"})});var f6="site:metadata:updated",vy,m6,h6,il,g6,upe,dpe,ppe;var DR=b(()=>{wt();ue();NR();vy=c.object({heading:c.string().describe("Main CTA heading text"),subtitle:c.string().optional().describe("A line under the CTA heading"),buttonText:c.string().describe("Call-to-action button text"),buttonLink:c.string().describe("URL or anchor for the CTA button")}),m6=c.object({title:c.string().optional(),description:c.string().optional(),copyright:c.string().optional(),cta:vy.optional()}),h6=c.object({blurb:c.string().optional().describe("Short italic subtitle under the section title")}),il=c.object({represents:c.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:c.string().describe("The site's title"),description:c.string().describe("The site's description"),url:c.string().optional().describe("Canonical site URL"),copyright:c.string().optional().describe("Copyright notice text"),logo:c.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:c.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:c.string().optional().describe("Analytics script HTML"),cta:vy.optional().describe("Call-to-action configuration"),sections:c.record(c.string(),h6).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:c.record(to,m6).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),g6=c.strictObject({}),upe=he({channel:"site:metadata:get",request:g6,response:il,delivery:"request"}),dpe=Gn(f6,il),ppe=il.extend({copyright:c.string(),navigation:c.object({primary:c.array(Sy),secondary:c.array(Sy)}),socialLinks:c.array(FI).optional().describe("Social media links from profile metadata"),photo:c.string().optional().describe("The anchor's photo, as ")})});var pNe;var LR=b(()=>{ue();pNe=c.record(c.string(),c.unknown())});var pp=b(()=>{LR()});var y6=b(()=>{wt();pp()});var b6=b(()=>{pp();wt()});var S6=b(()=>{pp();wt()});var RNe,TNe;var ZR=b(()=>{ue();RNe=c.record(c.string(),c.unknown()),TNe=c.object({label:c.string().optional(),line:c.boolean().optional(),itemTitle:c.string().optional(),itemLabel:c.string().optional()}).loose()});var CNe;var v6=b(()=>{ue();Pc();CNe=c.record(c.string(),c.unknown())});var w6=b(()=>{Pc()});var _6=b(()=>{ue();ZR()});var E6;var A6=b(()=>{wt();ue();E6=c.object({id:c.string().min(1),title:c.string().min(1),url:c.url().optional(),brain:Dc.optional()})});var _y=b(()=>{pp();y6();b6();S6();ZR();v6();w6();_6();A6();LR()});var Ipe;var I6=b(()=>{ue();Ipe=c.object({slug:c.string(),title:c.string(),type:c.string(),entityId:c.string(),contentHash:c.string()})});var jR=b(()=>{_y();I6();_y();_y()});var k6=b(()=>{jR();ue()});var BR=()=>{};var kpe,Rpe,Tpe;var Ey=b(()=>{ue();wt();kpe={url:c.string(),typeLabel:c.string(),listUrl:c.string(),listLabel:c.string()},Rpe={url:c.string().nullable().default(null),typeLabel:c.string().nullable().default(null),listUrl:c.string().nullable().default(null),listLabel:c.string().nullable().default(null)},Tpe=c.object({name:c.string(),description:c.string(),schema:c.unknown(),basePrompt:c.string().optional(),useKnowledgeContext:c.boolean().optional(),requiredPermission:c.enum(["admin","trusted","public"]),formatter:c.unknown().optional(),overlayFormatter:c.unknown().optional(),layout:c.object({component:c.unknown().optional(),fullscreen:c.boolean().optional(),formats:c.unknown().optional()}).optional(),dataSourceId:c.string().optional()})});var Ay=b(()=>{Ey()});var $6=b(()=>{Ay()});var UR=()=>{};var Ope,Cpe,sl,O6,zpe;var C6=b(()=>{wt();ue();UR();Ope=c.enum(["admin","trusted","public"]),Cpe=c.enum(["create","update","delete","extract","publish"]),sl=c.enum(["never","admin","trusted","public"]),O6=c.strictObject({create:sl.optional(),update:sl.optional(),delete:sl.optional(),extract:sl.optional(),publish:sl.optional()}),zpe=c.record(c.string(),O6)});var z6=b(()=>{Ay();Ey()});var Ppe,Npe,Iy,Dpe,Lpe,Zpe;var P6=b(()=>{ue();Ppe=c.enum(["site-content-preview","site-content-production"]),Npe=c.enum(["web","image","pdf","epub"]),Iy=c.custom((e)=>typeof e==="function"),Dpe=c.object({name:c.string(),schema:c.unknown(),description:c.string().optional(),pluginId:c.string(),renderers:c.object({web:c.union([Iy,c.string()]).optional(),image:c.union([Iy,c.string()]).optional(),pdf:c.union([Iy,c.string()]).optional(),epub:c.union([Iy,c.string()]).optional()})}),Lpe=c.object({enableContentGeneration:c.boolean().default(!1),outputDir:c.string(),workingDir:c.string().optional(),environment:c.enum(["preview","production"]).default("preview"),siteConfig:c.object({title:c.string(),description:c.string(),url:c.string().optional()}).optional()}),Zpe=c.object({success:c.boolean(),routesBuilt:c.number(),errors:c.array(c.string()).optional(),warnings:c.array(c.string()).optional()})});var N6=b(()=>{Ey();$6();Ay();C6();UR();z6();P6()});var MR=ye(function(Bpe,ky){(function(){function e(g,E){Object.defineProperty(o.prototype,g,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",E[0],E[1])}})}function t(g){if(g===null||typeof g!=="object")return null;return g=De&&g[De]||g["@@iterator"],typeof g==="function"?g:null}function r(g,E){g=(g=g.constructor)&&(g.displayName||g.name)||"ReactClass";var D=g+"."+E;Qe[D]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",E,g),Qe[D]=!0)}function o(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||bt}function n(){}function i(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||bt}function s(){}function a(g){return""+g}function l(g){try{a(g);var E=!1}catch(M){E=!0}if(E){E=console;var D=E.error,J=typeof Symbol==="function"&&Symbol.toStringTag&&g[Symbol.toStringTag]||g.constructor.name||"Object";return D.call(E,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",J),a(g)}}function u(g){if(g==null)return null;if(typeof g==="function")return g.$$typeof===$n?null:g.displayName||g.name||null;if(typeof g==="string")return g;switch(g){case H:return"Fragment";case re:return"Profiler";case G:return"StrictMode";case xe:return"Suspense";case ke:return"SuspenseList";case Ue:return"Activity"}if(typeof g==="object")switch(typeof g.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),g.$$typeof){case N:return"Portal";case me:return g.displayName||"Context";case ae:return(g._context.displayName||"Context")+".Consumer";case Se:var E=g.render;return g=g.displayName,g||(g=E.displayName||E.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case Ie:return E=g.displayName||null,E!==null?E:u(g.type)||"Memo";case _e:E=g._payload,g=g._init;try{return u(g(E))}catch(D){}}return null}function d(g){if(g===H)return"<>";if(typeof g==="object"&&g!==null&&g.$$typeof===_e)return"<...>";try{var E=u(g);return E?"<"+E+">":"<...>"}catch(D){return"<...>"}}function p(){var g=Le.A;return g===null?null:g.getOwner()}function m(){return Error("react-stack-top-frame")}function h(g){if(uo.call(g,"key")){var E=Object.getOwnPropertyDescriptor(g,"key").get;if(E&&E.isReactWarning)return!1}return g.key!==void 0}function S(g,E){function D(){us||(us=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",E))}D.isReactWarning=!0,Object.defineProperty(g,"key",{get:D,configurable:!0})}function y(){var g=u(this.type);return ds[g]||(ds[g]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),g=this.props.ref,g!==void 0?g:null}function v(g,E,D,J,M,te){var se=D.ref;return g={$$typeof:q,type:g,key:E,props:D,_owner:J},(se!==void 0?se:null)!==null?Object.defineProperty(g,"ref",{enumerable:!1,get:y}):Object.defineProperty(g,"ref",{enumerable:!1,value:null}),g._store={},Object.defineProperty(g._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(g,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(g,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:M}),Object.defineProperty(g,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:te}),Object.freeze&&(Object.freeze(g.props),Object.freeze(g)),g}function x(g,E){return E=v(g.type,E,g.props,g._owner,g._debugStack,g._debugTask),g._store&&(E._store.validated=g._store.validated),E}function _(g){k(g)?g._store&&(g._store.validated=1):typeof g==="object"&&g!==null&&g.$$typeof===_e&&(g._payload.status==="fulfilled"?k(g._payload.value)&&g._payload.value._store&&(g._payload.value._store.validated=1):g._store&&(g._store.validated=1))}function k(g){return typeof g==="object"&&g!==null&&g.$$typeof===q}function O(g){var E={"=":"=0",":":"=2"};return"$"+g.replace(/[=:]/g,function(D){return E[D]})}function L(g,E){return typeof g==="object"&&g!==null&&g.key!=null?(l(g.key),O(""+g.key)):E.toString(36)}function P(g){switch(g.status){case"fulfilled":return g.value;case"rejected":throw g.reason;default:switch(typeof g.status==="string"?g.then(s,s):(g.status="pending",g.then(function(E){g.status==="pending"&&(g.status="fulfilled",g.value=E)},function(E){g.status==="pending"&&(g.status="rejected",g.reason=E)})),g.status){case"fulfilled":return g.value;case"rejected":throw g.reason}}throw g}function K(g,E,D,J,M){var te=typeof g;if(te==="undefined"||te==="boolean")g=null;var se=!1;if(g===null)se=!0;else switch(te){case"bigint":case"string":case"number":se=!0;break;case"object":switch(g.$$typeof){case q:case N:se=!0;break;case _e:return se=g._init,K(se(g._payload),E,D,J,M)}}if(se){se=g,M=M(se);var be=J===""?"."+L(se,0):J;return Or(M)?(D="",be!=null&&(D=be.replace(Aa,"$&/")+"/"),K(M,E,D,"",function(Te){return Te})):M!=null&&(k(M)&&(M.key!=null&&(se&&se.key===M.key||l(M.key)),D=x(M,D+(M.key==null||se&&se.key===M.key?"":(""+M.key).replace(Aa,"$&/")+"/")+be),J!==""&&se!=null&&k(se)&&se.key==null&&se._store&&!se._store.validated&&(D._store.validated=2),M=D),E.push(M)),1}if(se=0,be=J===""?".":J+":",Or(g))for(var fe=0;fe<g.length;fe++)J=g[fe],te=be+L(J,fe),se+=K(J,E,D,te,M);else if(fe=t(g),typeof fe==="function")for(fe===g.entries&&(Qo||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Qo=!0),g=fe.call(g),fe=0;!(J=g.next()).done;)J=J.value,te=be+L(J,fe++),se+=K(J,E,D,te,M);else if(te==="object"){if(typeof g.then==="function")return K(P(g),E,D,J,M);throw E=String(g),Error("Objects are not valid as a React child (found: "+(E==="[object Object]"?"object with keys {"+Object.keys(g).join(", ")+"}":E)+"). If you meant to render a collection of children, use an array instead.")}return se}function z(g,E,D){if(g==null)return g;var J=[],M=0;return K(g,J,"","",function(te){return E.call(D,te,M++)}),J}function W(g){if(g._status===-1){var E=g._ioInfo;E!=null&&(E.start=E.end=performance.now()),E=g._result;var D=E();if(D.then(function(M){if(g._status===0||g._status===-1){g._status=1,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="fulfilled",D.value=M)}},function(M){if(g._status===0||g._status===-1){g._status=2,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="rejected",D.reason=M)}}),E=g._ioInfo,E!=null){E.value=D;var J=D.displayName;typeof J==="string"&&(E.name=J)}g._status===-1&&(g._status=0,g._result=D)}if(g._status===1)return E=g._result,E===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
432
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=cy(e),r=tl(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=cy(e),r=tl(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((r)=>r.type==="newline"||r.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}Tue.Parser=bq});var _q=ye(function(Zue){var Sq=mR(),Oue=np(),lp=op(),Cue=Ek(),zue=qe(),Pue=ER(),vq=AR();function wq(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Pue.LineCounter||null,prettyErrors:t}}function Nue(e,t={}){let{lineCounter:r,prettyErrors:o}=wq(t),n=new vq.Parser(r?.addNewLine),i=new Sq.Composer(t),s=Array.from(i.compose(n.parse(e)));if(o&&r)for(let a of s)a.errors.forEach(lp.prettifyError(e,r)),a.warnings.forEach(lp.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},i.streamInfo())}function xq(e,t={}){let{lineCounter:r,prettyErrors:o}=wq(t),n=new vq.Parser(r?.addNewLine),i=new Sq.Composer(t),s=null;for(let a of i.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new lp.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(o&&r)s.errors.forEach(lp.prettifyError(e,r)),s.warnings.forEach(lp.prettifyError(e,r));return s}function Due(e,t,r){let o=void 0;if(typeof t==="function")o=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=xq(e,r);if(!n)return null;if(n.warnings.forEach((i)=>Cue.warn(n.options.logLevel,i)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:o},r))}function Lue(e,t,r){let o=null;if(typeof t==="function"||Array.isArray(t))o=t;else if(r===void 0&&t)r=t;if(typeof r==="string")r=r.length;if(typeof r==="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}if(zue.isDocument(e)&&!o)return e.toString(r);return new Oue.Document(e,o,r).toString(r)}Zue.parse=Due;Zue.parseAllDocuments=Nue;Zue.parseDocument=xq;Zue.stringify=Lue});var que,Fue,Jue,IR,Kue,qi,Hue,Vue,Wue,Gue,gPe,Que,Yue,Xue,uy,Eq,ede,tde,rde,nde,ode,ide,sde,ade,cde,lde,vn,zo,ude,Po,kR,dde,pde,fde,mde,hde,gde,yde,bde,Sde,tn,vde,wde,xde;var rl=b(()=>{que=mR(),Fue=np(),Jue=Yk(),IR=op(),Kue=qd(),qi=qe(),Hue=Zi(),Vue=It(),Wue=Bi(),Gue=Ui(),gPe=sy(),Que=_R(),Yue=ER(),Xue=AR(),uy=_q(),Eq=Ud();ede=que.Composer,tde=Fue.Document,rde=Jue.Schema,nde=IR.YAMLError,ode=IR.YAMLParseError,ide=IR.YAMLWarning,sde=Kue.Alias,ade=qi.isAlias,cde=qi.isCollection,lde=qi.isDocument,vn=qi.isMap,zo=qi.isNode,ude=qi.isPair,Po=qi.isScalar,kR=qi.isSeq,dde=Hue.Pair,pde=Vue.Scalar,fde=Wue.YAMLMap,mde=Gue.YAMLSeq,hde=Que.Lexer,gde=Yue.LineCounter,yde=Xue.Parser,bde=uy.parse,Sde=uy.parseAllDocuments,tn=uy.parseDocument,vde=uy.stringify,wde=Eq.visit,xde=Eq.visitAsync});var Rq={};Lt(Rq,{migratePilotDeploySecrets:()=>Iq,migratePilotEnvSchema:()=>kq,migratePilotRepoProviderKeys:()=>$de,migrateProviderKeyFieldsYaml:()=>$R,openaiSelectorFor:()=>OR,renameProviderKeyFields:()=>Fi});import{readdir as _de,readFile as RR,writeFile as Aq}from"fs/promises";import{join as No}from"path";function $R(e){let t=tn(e,{keepSourceTokens:!0});return Fi(t)?t.toString({lineWidth:0}):e}function Fi(e){if(!vn(e.contents))return!1;return e.contents.items.filter((r)=>{if(!Po(r.key)||typeof r.key.value!=="string")return!1;let o=Ede[r.key.value];if(!o)return!1;if(r.key.value==="aiApiKey"&&Po(r.value)&&r.value.value===py)r.value.value=fy;return r.key.value=o,!0}).length>0}function OR(e){return e===py?fy:e}function Iq(e){return e.replace(new RegExp(`^(\\s+- )${py}$`,"m"),`$1${fy}`)}function kq(e){return e.replace(new RegExp(`^${py}=`,"m"),`${fy}=`)}async function dy(e){try{return(await _de(e)).filter((r)=>r.endsWith(".yaml")).sort()}catch{return[]}}async function TR(e){try{return await RR(e,"utf8")}catch{return}}async function Rde(e){let t=await dy(No(e,"cohorts")),r=await Promise.all(t.map(async(i)=>{let s=yr(await RR(No(e,"cohorts",i),"utf8"),Ide);return s.ok&&s.data.aiApiKeyOverride?s.data.members:[]})),o=(await dy(No(e,"users"))).filter((i)=>!i.endsWith(".secrets.yaml")),n=await Promise.all(o.map(async(i)=>{let s=yr(await RR(No(e,"users",i),"utf8"),Ade);return s.ok&&s.data.aiApiKeyOverride?[i.replace(/\.yaml$/,"")]:[]}));return[...new Set([...r.flat(),...n.flat()])]}async function Tde(e,t,r,o){let n=No(e,"users",`${t}.secrets.yaml.age`),i=await TR(n);if(i===void 0)return!1;if(!r)throw Error(`users/${t}.secrets.yaml.age may hold the legacy AI key; set AGE_SECRET_KEY or AGE_SECRET_KEY_FILE to migrate it`);let s=new Pu;s.addIdentity(r);let a=await s.decrypt(bi.decode(i),"text"),l=$R(a);if(l===a)return!1;let u=new zu;return u.addRecipient(o),await Aq(n,bi.encode(await u.encrypt(l))),!0}async function $de(e,t){let r=["pilot.yaml",...(await dy(No(e,"cohorts"))).map((l)=>`cohorts/${l}`),...(await dy(No(e,"users"))).filter((l)=>!l.endsWith(".secrets.yaml")).map((l)=>`users/${l}`)],o=await Rde(e),n=await Promise.all([...r.map((l)=>({file:l,migrate:$R})),{file:".env.schema",migrate:kq},{file:"deploy/kamal/deploy.yml",migrate:Iq}].map(async({file:l,migrate:u})=>{let d=No(e,l),p=await TR(d);if(p===void 0)return[];let m=u(p);if(m===p)return[];return await Aq(d,m),[l]})),i=yr(await TR(No(e,"pilot.yaml"))??"",kde),s=dk(e,t,Lr(e)),a=o.length===0?[]:await Promise.all(o.map(async(l)=>{if(!i.ok)throw Error("pilot.yaml needs agePublicKey to re-encrypt secrets");return await Tde(e,l,s,i.data.agePublicKey)?[`users/${l}.secrets.yaml.age`]:[]}));return[...n.flat(),...a.flat()]}var py="AI_API_KEY",fy="OPENAI_API_KEY",Ede,Ade,Ide,kde;var my=b(()=>{yi();wi();Vn();ue();rl();fk();Ede={aiApiKey:"openaiApiKey",aiApiKeyOverride:"openaiApiKeyOverride"};Ade=c.looseObject({aiApiKeyOverride:c.string().optional()}),Ide=c.looseObject({members:c.array(c.string()).default([]),aiApiKeyOverride:c.string().optional()}),kde=c.looseObject({agePublicKey:c.string()})});function Cq(e){if(e==="core")return{bundles:["core","media","web","chat"]};if(e==="default")return{bundles:["core","media","automation","web","chat","site","publishing","federation"],remove:[...zde]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"]}}function Pde(e){let t=Ode.parse(e);return Ys.parse({brainVersion:t.brainVersion,bundleContract:Qs,...Cq(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,openaiApiKey:OR(t.aiApiKey),gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function Nde(e){let t=Cde.parse(e),r=t.presetOverride?Cq(t.presetOverride):void 0;return hn.parse({members:[...t.members],...t.brainVersionOverride?{brainVersionOverride:t.brainVersionOverride}:{},...r?{bundlesOverride:r.bundles,...r.add?{addOverride:r.add}:{},...r.remove?{removeOverride:r.remove}:{}}:{},...t.aiApiKeyOverride?{openaiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function zq(e){let t=tn(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!vn(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function CR(e,t){if(!vn(e.contents))return;return e.contents.items.find((r)=>Po(r.key)&&r.key.value===t)}function Tq(e,t){if(!zo(e)||!zo(t))return;if(e.commentBefore!==void 0)t.commentBefore=e.commentBefore;if(e.comment!==void 0)t.comment=e.comment;if(e.spaceBefore!==void 0)t.spaceBefore=e.spaceBefore}function $q(e,t){if(!e||!zo(t))return;let r=[zo(e.key)?e.key.commentBefore:void 0,zo(e.key)?e.key.comment:void 0,zo(e.value)?e.value.commentBefore:void 0,zo(e.value)?e.value.comment:void 0].filter((o)=>o!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((o)=>o!==void 0).join(`
|
|
433
|
+
`)}function Pq(e,t,r,o){if(!vn(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>Po(s.key)&&s.key.value===t),i=e.createPair(r,[...o]);if(n>=0){let s=e.contents.items[n];Tq(s?.key,i.key),Tq(s?.value,i.value),e.contents.items.splice(n,1,i)}else e.contents.add(i);return i}function Nq(e){let t=zq(e),r=Pde(t.toJS()),o=CR(t,"schemaVersion"),n=CR(t,"model");$q(o,CR(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",Qs);let i=Pq(t,"preset","bundles",r.bundles);if($q(n,i.key),t.delete("model"),r.add)t.set("add",r.add);else t.delete("add");if(r.remove)t.set("remove",r.remove);else t.delete("remove");return Fi(t),Ys.parse(t.toJS()),t.toString({lineWidth:0})}function Dq(e){let t=zq(e),r=Nde(t.toJS());if(r.bundlesOverride)Pq(t,"presetOverride","bundlesOverride",r.bundlesOverride);else t.delete("presetOverride"),t.delete("bundlesOverride");if(r.addOverride)t.set("addOverride",r.addOverride);else t.delete("addOverride");if(r.removeOverride)t.set("removeOverride",r.removeOverride);else t.delete("removeOverride");return Fi(t),hn.parse(t.toJS()),t.toString({lineWidth:0})}var Oq,up,Ode,Cde,zde;var Lq=b(()=>{my();Vn();ue();rl();$o();Oq=c.enum(["core","default","pro"]),up=c.string().min(1),Ode=c.strictObject({schemaVersion:c.literal(1),brainVersion:Ct,model:c.literal("rover"),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),preset:Oq,aiApiKey:up,gitSyncToken:up,contentRepoAdminToken:up,agePublicKey:c.string().startsWith("age1").min(1)}),Cde=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),presetOverride:Oq.optional(),aiApiKeyOverride:up.optional(),gitSyncTokenOverride:up.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:c.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),zde=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function jq(e,t){let r=tn(e,{keepSourceTokens:!0});if(r.errors.length>0||!vn(r.contents))throw Error(`Invalid ${t} YAML`);return r}function Bde(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function Bq(e,t,r){if(!Bde(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function Uq(e){let t=yr(e,jde);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function Mq(e,t){let r=jq(e,"pilot desired-state"),o=Lde.parse(r.toJS());return Bq("pilot.yaml",o.bundles,t),r.set("bundleContract",Qs),r.set("bundles",t.targetBundles),Fi(r),Ys.parse(r.toJS()),r.toString({lineWidth:0})}function qq(e,t,r){let o=jq(e,`cohort ${t}`),n=Zde.parse(o.toJS());if(n.bundlesOverride===void 0){if(r!==void 0)throw Error(`Capability bundle review names inheriting cohort ${t}`)}else{if(r===void 0)throw Error(`Cohort ${t} has an explicit legacy bundle selection but no reviewed mapping`);Bq(`cohort ${t}`,n.bundlesOverride,r),o.set("bundlesOverride",r.targetBundles)}return Fi(o),hn.parse(o.toJS()),o.toString({lineWidth:0})}var Dde,zR,hy,Lde,Zde,Zq,jde;var Fq=b(()=>{my();Vn();ue();rl();$o();Dde=c.enum(["core","site","publishing","team"]),zR=c.array(Dde).min(1),hy=c.array(c.string().min(1)),Lde=c.strictObject({brainVersion:Ct,bundles:zR,add:hy.optional(),remove:hy.optional(),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),aiApiKey:c.string().min(1),gitSyncToken:c.string().min(1),contentRepoAdminToken:c.string().min(1),agePublicKey:c.string().startsWith("age1").min(1)}),Zde=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),bundlesOverride:zR.optional(),addOverride:hy.optional(),removeOverride:hy.optional(),aiApiKeyOverride:c.string().min(1).optional(),gitSyncTokenOverride:c.string().min(1).optional()}),Zq=c.strictObject({sourceBundles:zR,targetBundles:c.array(KI).min(1)}),jde=c.strictObject({bundleContract:c.literal(Qs),pilot:Zq,cohorts:c.record(br,Zq)})});var Wq={};Lt(Wq,{loadCapabilityBundleReview:()=>Wde,loadReviewedSitePins:()=>Vde,parseReviewedSitePins:()=>Vq,stageLegacyCrossover:()=>Qde});import{access as Ude,cp as Mde,mkdir as Jq,readFile as ol,readdir as Hq,writeFile as nl}from"fs/promises";import{basename as qde,join as eo,relative as gy,resolve as Kq}from"path";import{fileURLToPath as Fde}from"url";function Vq(e){let t=yr(e,Jde);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function Vde(e){return Vq(await ol(e,"utf8"))}async function Wde(e){return Uq(await ol(e,"utf8"))}async function Gde(e,t){let r=eo(e,"users"),o=(await Hq(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),i=[];for(let s of o){let a=eo(r,s),l=await ol(a,"utf8"),u=tn(l,{keepSourceTokens:!0});if(u.errors.length>0||!vn(u.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let d=Kde.parse(u.toJS());if(!d.siteOverride)continue;let p=t?.[d.handle];if(!p)throw Error(`User ${d.handle} has a siteOverride but no reviewed site pin`);if(n.delete(d.handle),p.package!==d.siteOverride.package||p.theme!==d.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${d.handle}`);if(d.siteOverride.version!==void 0&&d.siteOverride.version!==p.version)throw Error(`Reviewed site version does not match the existing pin for user ${d.handle}`);if(d.siteOverride.themeVersion!==void 0&&d.siteOverride.themeVersion!==p.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${d.handle}`);if(u.setIn(["siteOverride","version"],p.version),p.themeVersion!==void 0)u.setIn(["siteOverride","themeVersion"],p.themeVersion);else u.deleteIn(["siteOverride","themeVersion"]);dg.parse(u.toJS());let m=u.toString({lineWidth:0});if(m!==l)await nl(a,m),i.push(gy(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return i}async function Qde(e,t,r={}){let o=Kq(e),n=Kq(t);if(o===n||n.startsWith(`${o}/`))throw Error("Crossover output must be outside the source repository");await Mde(o,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(k)=>{let O=qde(k);return O!==".git"&&O!==".operator"&&O!==".brains-ops"&&O!==".turbo"&&O!=="dist"&&O!=="node_modules"&&O!==".env"&&O!==".env.local"&&!O.endsWith(".secrets.yaml")}});let i=[],s=eo(n,"docs","canonical-crossover-record.md");try{await Ude(s)}catch{await Jq(eo(n,"docs"),{recursive:!0}),await nl(s,await ol(Hde,"utf8")),i.push("docs/canonical-crossover-record.md")}let a=eo(n,"pilot.yaml"),l=await ol(a,"utf8"),d=tn(l).toJS();if(!Nd(d))throw Error(`${a} is not a YAML mapping`);let p=Array.isArray(d.bundles),m=r.bundleReview,h;if(p){if(!m)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");h=Mq(l,m.pilot)}else h=Nq(l);await nl(a,h),i.push("pilot.yaml");let S=eo(n,"cohorts"),y=(await Hq(S,{withFileTypes:!0})).filter((k)=>k.isFile()&&/\.ya?ml$/.test(k.name)).map((k)=>k.name).sort(),v=new Set(Object.keys(m?.cohorts??{}));for(let k of y){let O=eo(S,k),L=await ol(O,"utf8"),P=k.replace(/\.ya?ml$/,""),K=m?.cohorts[P];if(K)v.delete(P);await nl(O,p?qq(L,P,K):Dq(L)),i.push(gy(n,O))}if(p&&v.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...v].sort().join(", ")}`);i.push(...await Gde(n,r.sitePins));let x=await xt(n),_=hg(x.pilot.githubOrg);for(let k of x.users){let O=await _(k),L=eo(n,"users",k.handle);if(await Jq(L,{recursive:!0}),O.brainYaml){let P=eo(L,"brain.yaml");await nl(P,O.brainYaml),i.push(gy(n,P))}if(O.envFile){let P=eo(L,".env");await nl(P,O.envFile),i.push(gy(n,P))}}return await Pi(n,{registry:x}),i.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(i)].sort()}}var Jde,Kde,Hde;var Gq=b(()=>{Vn();Dd();ue();rl();ak();Lq();Fq();gn();Pd();$o();Jde=c.strictObject({sites:c.record(br,HI)}),Kde=c.object({handle:br,siteOverride:c.object({package:c.string().min(1),version:Ct.optional(),theme:c.string().min(1).optional(),themeVersion:Ct.optional()}).optional()}).passthrough(),Hde=Fde(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var Yq,Yde,Xde,epe,to,dp,tpe,PR,rpe,npe,Qq,ope,ipe,Xq,YPe,e6;var yy=b(()=>{eI();Yq=["primary","secondary"],Yde=c.custom((e)=>typeof e==="function","Expected a React component"),Xde=c.strictObject({show:c.boolean().optional(),label:c.string().min(1).optional(),slot:c.enum(Yq).optional(),priority:c.number().optional()}),epe=c.strictObject({id:c.string().min(1),template:c.string().min(1),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.record(c.string(),c.unknown()).optional()}).optional(),order:c.number().optional()}),to=c.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),dp=c.strictObject({title:c.string().optional(),description:c.string().optional(),navigationLabel:c.string().optional()}),tpe=c.strictObject({id:c.string().min(1),path:c.string().startsWith("/"),title:c.string().optional(),pageLabel:c.string().optional(),description:c.string().optional(),sections:c.array(epe).optional(),layout:c.string().min(1).optional(),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),sourceEntityId:c.string().optional(),external:c.boolean().optional(),navigation:Xde.optional(),translations:c.record(to,dp).optional()}),PR=c.strictObject({label:c.string().min(1),pluralName:c.string().min(1).optional(),layout:c.string().min(1).optional(),detailTemplate:c.string().min(1).optional(),paginate:c.boolean().optional(),pageSize:c.number().int().positive().optional(),citable:c.boolean().optional(),navigation:c.strictObject({show:c.boolean().optional(),slot:c.enum(Yq).optional(),priority:c.number().optional()}).optional()}),rpe=c.strictObject({schema:c.custom((e)=>e instanceof c.ZodType,"Expected a Zod schema"),component:c.custom((e)=>typeof e==="function","Expected a React component"),title:c.string().min(1),description:c.string(),requiredPermission:c.enum(["admin","trusted","public"]).optional(),fullscreen:c.boolean().optional(),dataSource:c.string().min(1).optional(),components:c.record(to,c.custom((e)=>typeof e==="function","Expected a React component")).optional()}),npe=c.custom((e)=>typeof e==="object"&&e!==null&&Reflect.get(e,"kind")==="rizom-data-source"&&typeof Reflect.get(e,"id")==="string"&&typeof Reflect.get(e,"fetch")==="function","Expected a fetching data source declared with defineDataSource"),Qq=c.strictObject({namespace:c.string().min(1),sections:c.record(c.string(),rpe)}),ope=c.record(c.string(),c.json()),ipe=c.record(c.string(),c.record(c.string(),ope)),Xq={layouts:c.record(c.string(),Yde).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:c.array(tpe),content:ipe.optional(),sections:c.union([Qq,c.array(Qq)]).optional(),themeOverride:c.string().optional(),headScripts:c.array(c.string()).optional(),entityDisplay:c.record(c.string(),PR),staticAssets:c.record(c.string(),c.string()).optional(),languages:c.array(to).min(1).optional(),dataSources:c.array(npe).readonly().optional()},YPe=c.strictObject(Xq).partial(),e6=c.strictObject(Xq).superRefine((e,t)=>{let r=e.languages??[],o=new Set;for(let[u,d]of r.entries()){let p=d.toLowerCase();if(o.has(p))t.addIssue({code:"custom",path:["languages",u],message:`Language "${d}" is declared twice`});o.add(p)}let n=r.slice(1).map((u)=>`/${u.toLowerCase()}`),i=new Set;for(let[u,d]of e.routes.entries()){if(i.has(d.id))t.addIssue({code:"custom",path:["routes",u,"id"],message:`Duplicate route id "${d.id}"`});i.add(d.id);let p=d.path.toLowerCase(),m=n.find((S)=>p===S||p.startsWith(`${S}/`));if(m)t.addIssue({code:"custom",path:["routes",u,"path"],message:`Route path "${d.path}" is under ${m}, where another language's pages are built`});let h=d.layout??"default";if(!e.layouts[h])t.addIssue({code:"custom",path:["routes",u,"layout"],message:`Unknown layout "${h}"`});for(let[S,y]of(d.sections??[]).entries()){let v=/^([^:.\s]+)\.([^:.\s]+)$/.exec(y.template);if(v)t.addIssue({code:"custom",path:["routes",u,"sections",S,"template"],message:`Section template "${y.template}" is written "${v[1]}:${v[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],a=new Map(s.map((u)=>[u.namespace,u]));if(a.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});let l=new Set;for(let[u,d]of(e.dataSources??[]).entries()){if(l.has(d.id))t.addIssue({code:"custom",path:["dataSources",u],message:`Data source "${d.id}" is declared twice`});l.add(d.id)}for(let u of s)for(let[d,p]of Object.entries(u.sections))if(p.dataSource&&!l.has(p.dataSource))t.addIssue({code:"custom",path:["sections",u.namespace,d,"dataSource"],message:`Section "${u.namespace}:${d}" reads data source "${p.dataSource}", which the site does not declare`});for(let[u,d]of Object.entries(e.content??{})){let p=a.get(u);if(!p){t.addIssue({code:"custom",path:["content",u],message:`Content namespace "${u}" has no section group`});continue}for(let[m,h]of Object.entries(d)){let S=p.sections[m];if(!S){t.addIssue({code:"custom",path:["content",u,m],message:`Content section "${u}:${m}" is not defined`});continue}let y=S.schema.safeParse(h);if(!y.success)t.addIssue({code:"custom",path:["content",u,m],message:`Content does not satisfy the "${u}:${m}" schema: ${c.prettifyError(y.error)}`})}}})});var t6,r6,n6,by,o6,ape,i6,s6,cpe,a6,c6,lpe,Sy;var NR=b(()=>{wt();ue();yy();yy();t6=c.object({id:c.string(),template:c.string(),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.looseObject({id:c.string().optional(),limit:c.number().optional(),offset:c.number().optional()}).optional()}).optional(),order:c.number().optional()}),r6=["primary","secondary"],n6=c.object({show:c.boolean().default(!1),label:c.string().optional(),slot:c.enum(r6).default("primary"),priority:c.number().min(0).max(100).default(50)}).optional(),by=c.object({id:c.string(),path:c.string(),title:c.string().default(""),pageLabel:c.string().optional(),description:c.string().default(""),sections:c.array(t6).default([]),layout:c.string().default("default"),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),sourceEntityId:c.string().optional(),external:c.boolean().optional(),navigation:n6,translations:c.record(to,dp).optional(),languages:c.array(to).optional()}),o6=c.object({routes:c.array(by),pluginId:c.string()}),ape=he({channel:"plugin:site-builder:route:register",request:o6,response:c.void(),delivery:"command"}),i6=c.strictObject({}),s6=c.array(by),cpe=he({channel:"site-builder:routes:list",request:i6,response:s6,delivery:"request"}),a6=c.strictObject({}),c6=c.array(by),lpe=he({channel:"plugin:site-builder:pages",request:a6,response:c6,delivery:"collect"}),Sy=c.object({label:c.string(),href:c.string(),priority:c.number()})});var l6,u6,d6,upe;var p6=b(()=>{wt();ue();l6=c.object({pluginId:c.string(),slotName:c.string(),render:c.custom((e)=>typeof e==="function"),priority:c.number().optional()}),u6=c.strictObject({}),d6=c.array(l6),upe=he({channel:"plugin:site-builder:slots",request:u6,response:d6,delivery:"collect"})});var f6="site:metadata:updated",vy,m6,h6,il,g6,dpe,ppe,fpe;var DR=b(()=>{wt();ue();NR();vy=c.object({heading:c.string().describe("Main CTA heading text"),subtitle:c.string().optional().describe("A line under the CTA heading"),buttonText:c.string().describe("Call-to-action button text"),buttonLink:c.string().describe("URL or anchor for the CTA button")}),m6=c.object({title:c.string().optional(),description:c.string().optional(),copyright:c.string().optional(),cta:vy.optional()}),h6=c.object({blurb:c.string().optional().describe("Short italic subtitle under the section title")}),il=c.object({represents:c.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:c.string().describe("The site's title"),description:c.string().describe("The site's description"),url:c.string().optional().describe("Canonical site URL"),copyright:c.string().optional().describe("Copyright notice text"),logo:c.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:c.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:c.string().optional().describe("Analytics script HTML"),cta:vy.optional().describe("Call-to-action configuration"),sections:c.record(c.string(),h6).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:c.record(to,m6).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),g6=c.strictObject({}),dpe=he({channel:"site:metadata:get",request:g6,response:il,delivery:"request"}),ppe=Gn(f6,il),fpe=il.extend({copyright:c.string(),navigation:c.object({primary:c.array(Sy),secondary:c.array(Sy)}),socialLinks:c.array(FI).optional().describe("Social media links from profile metadata"),photo:c.string().optional().describe("The anchor's photo, as ")})});var fNe;var LR=b(()=>{ue();fNe=c.record(c.string(),c.unknown())});var pp=b(()=>{LR()});var y6=b(()=>{wt();pp()});var b6=b(()=>{pp();wt()});var S6=b(()=>{pp();wt()});var TNe,$Ne;var ZR=b(()=>{ue();TNe=c.record(c.string(),c.unknown()),$Ne=c.object({label:c.string().optional(),line:c.boolean().optional(),itemTitle:c.string().optional(),itemLabel:c.string().optional()}).loose()});var zNe;var v6=b(()=>{ue();Pc();zNe=c.record(c.string(),c.unknown())});var w6=b(()=>{Pc()});var _6=b(()=>{ue();ZR()});var E6;var A6=b(()=>{wt();ue();E6=c.object({id:c.string().min(1),title:c.string().min(1),url:c.url().optional(),brain:Dc.optional()})});var _y=b(()=>{pp();y6();b6();S6();ZR();v6();w6();_6();A6();LR()});var kpe;var I6=b(()=>{ue();kpe=c.object({slug:c.string(),title:c.string(),type:c.string(),entityId:c.string(),contentHash:c.string()})});var jR=b(()=>{_y();I6();_y();_y()});var k6=b(()=>{jR();ue()});var BR=()=>{};var Rpe,Tpe,$pe;var Ey=b(()=>{ue();wt();Rpe={url:c.string(),typeLabel:c.string(),listUrl:c.string(),listLabel:c.string()},Tpe={url:c.string().nullable().default(null),typeLabel:c.string().nullable().default(null),listUrl:c.string().nullable().default(null),listLabel:c.string().nullable().default(null)},$pe=c.object({name:c.string(),description:c.string(),schema:c.unknown(),basePrompt:c.string().optional(),useKnowledgeContext:c.boolean().optional(),requiredPermission:c.enum(["admin","trusted","public"]),formatter:c.unknown().optional(),overlayFormatter:c.unknown().optional(),layout:c.object({component:c.unknown().optional(),fullscreen:c.boolean().optional(),formats:c.unknown().optional()}).optional(),dataSourceId:c.string().optional()})});var Ay=b(()=>{Ey()});var $6=b(()=>{Ay()});var UR=()=>{};var Cpe,zpe,sl,O6,Ppe;var C6=b(()=>{wt();ue();UR();Cpe=c.enum(["admin","trusted","public"]),zpe=c.enum(["create","update","delete","extract","publish"]),sl=c.enum(["never","admin","trusted","public"]),O6=c.strictObject({create:sl.optional(),update:sl.optional(),delete:sl.optional(),extract:sl.optional(),publish:sl.optional()}),Ppe=c.record(c.string(),O6)});var z6=b(()=>{Ay();Ey()});var Npe,Dpe,Iy,Lpe,Zpe,jpe;var P6=b(()=>{ue();Npe=c.enum(["site-content-preview","site-content-production"]),Dpe=c.enum(["web","image","pdf","epub"]),Iy=c.custom((e)=>typeof e==="function"),Lpe=c.object({name:c.string(),schema:c.unknown(),description:c.string().optional(),pluginId:c.string(),renderers:c.object({web:c.union([Iy,c.string()]).optional(),image:c.union([Iy,c.string()]).optional(),pdf:c.union([Iy,c.string()]).optional(),epub:c.union([Iy,c.string()]).optional()})}),Zpe=c.object({enableContentGeneration:c.boolean().default(!1),outputDir:c.string(),workingDir:c.string().optional(),environment:c.enum(["preview","production"]).default("preview"),siteConfig:c.object({title:c.string(),description:c.string(),url:c.string().optional()}).optional()}),jpe=c.object({success:c.boolean(),routesBuilt:c.number(),errors:c.array(c.string()).optional(),warnings:c.array(c.string()).optional()})});var N6=b(()=>{Ey();$6();Ay();C6();UR();z6();P6()});var MR=ye(function(Upe,ky){(function(){function e(g,E){Object.defineProperty(o.prototype,g,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",E[0],E[1])}})}function t(g){if(g===null||typeof g!=="object")return null;return g=De&&g[De]||g["@@iterator"],typeof g==="function"?g:null}function r(g,E){g=(g=g.constructor)&&(g.displayName||g.name)||"ReactClass";var D=g+"."+E;Qe[D]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",E,g),Qe[D]=!0)}function o(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||bt}function n(){}function i(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||bt}function s(){}function a(g){return""+g}function l(g){try{a(g);var E=!1}catch(M){E=!0}if(E){E=console;var D=E.error,J=typeof Symbol==="function"&&Symbol.toStringTag&&g[Symbol.toStringTag]||g.constructor.name||"Object";return D.call(E,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",J),a(g)}}function u(g){if(g==null)return null;if(typeof g==="function")return g.$$typeof===$n?null:g.displayName||g.name||null;if(typeof g==="string")return g;switch(g){case H:return"Fragment";case re:return"Profiler";case G:return"StrictMode";case xe:return"Suspense";case ke:return"SuspenseList";case Ue:return"Activity"}if(typeof g==="object")switch(typeof g.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),g.$$typeof){case N:return"Portal";case me:return g.displayName||"Context";case ae:return(g._context.displayName||"Context")+".Consumer";case Se:var E=g.render;return g=g.displayName,g||(g=E.displayName||E.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case Ie:return E=g.displayName||null,E!==null?E:u(g.type)||"Memo";case _e:E=g._payload,g=g._init;try{return u(g(E))}catch(D){}}return null}function d(g){if(g===H)return"<>";if(typeof g==="object"&&g!==null&&g.$$typeof===_e)return"<...>";try{var E=u(g);return E?"<"+E+">":"<...>"}catch(D){return"<...>"}}function p(){var g=Le.A;return g===null?null:g.getOwner()}function m(){return Error("react-stack-top-frame")}function h(g){if(uo.call(g,"key")){var E=Object.getOwnPropertyDescriptor(g,"key").get;if(E&&E.isReactWarning)return!1}return g.key!==void 0}function S(g,E){function D(){us||(us=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",E))}D.isReactWarning=!0,Object.defineProperty(g,"key",{get:D,configurable:!0})}function y(){var g=u(this.type);return ds[g]||(ds[g]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),g=this.props.ref,g!==void 0?g:null}function v(g,E,D,J,M,te){var se=D.ref;return g={$$typeof:q,type:g,key:E,props:D,_owner:J},(se!==void 0?se:null)!==null?Object.defineProperty(g,"ref",{enumerable:!1,get:y}):Object.defineProperty(g,"ref",{enumerable:!1,value:null}),g._store={},Object.defineProperty(g._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(g,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(g,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:M}),Object.defineProperty(g,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:te}),Object.freeze&&(Object.freeze(g.props),Object.freeze(g)),g}function x(g,E){return E=v(g.type,E,g.props,g._owner,g._debugStack,g._debugTask),g._store&&(E._store.validated=g._store.validated),E}function _(g){k(g)?g._store&&(g._store.validated=1):typeof g==="object"&&g!==null&&g.$$typeof===_e&&(g._payload.status==="fulfilled"?k(g._payload.value)&&g._payload.value._store&&(g._payload.value._store.validated=1):g._store&&(g._store.validated=1))}function k(g){return typeof g==="object"&&g!==null&&g.$$typeof===q}function O(g){var E={"=":"=0",":":"=2"};return"$"+g.replace(/[=:]/g,function(D){return E[D]})}function L(g,E){return typeof g==="object"&&g!==null&&g.key!=null?(l(g.key),O(""+g.key)):E.toString(36)}function P(g){switch(g.status){case"fulfilled":return g.value;case"rejected":throw g.reason;default:switch(typeof g.status==="string"?g.then(s,s):(g.status="pending",g.then(function(E){g.status==="pending"&&(g.status="fulfilled",g.value=E)},function(E){g.status==="pending"&&(g.status="rejected",g.reason=E)})),g.status){case"fulfilled":return g.value;case"rejected":throw g.reason}}throw g}function K(g,E,D,J,M){var te=typeof g;if(te==="undefined"||te==="boolean")g=null;var se=!1;if(g===null)se=!0;else switch(te){case"bigint":case"string":case"number":se=!0;break;case"object":switch(g.$$typeof){case q:case N:se=!0;break;case _e:return se=g._init,K(se(g._payload),E,D,J,M)}}if(se){se=g,M=M(se);var be=J===""?"."+L(se,0):J;return Or(M)?(D="",be!=null&&(D=be.replace(Aa,"$&/")+"/"),K(M,E,D,"",function(Te){return Te})):M!=null&&(k(M)&&(M.key!=null&&(se&&se.key===M.key||l(M.key)),D=x(M,D+(M.key==null||se&&se.key===M.key?"":(""+M.key).replace(Aa,"$&/")+"/")+be),J!==""&&se!=null&&k(se)&&se.key==null&&se._store&&!se._store.validated&&(D._store.validated=2),M=D),E.push(M)),1}if(se=0,be=J===""?".":J+":",Or(g))for(var fe=0;fe<g.length;fe++)J=g[fe],te=be+L(J,fe),se+=K(J,E,D,te,M);else if(fe=t(g),typeof fe==="function")for(fe===g.entries&&(Qo||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Qo=!0),g=fe.call(g),fe=0;!(J=g.next()).done;)J=J.value,te=be+L(J,fe++),se+=K(J,E,D,te,M);else if(te==="object"){if(typeof g.then==="function")return K(P(g),E,D,J,M);throw E=String(g),Error("Objects are not valid as a React child (found: "+(E==="[object Object]"?"object with keys {"+Object.keys(g).join(", ")+"}":E)+"). If you meant to render a collection of children, use an array instead.")}return se}function z(g,E,D){if(g==null)return g;var J=[],M=0;return K(g,J,"","",function(te){return E.call(D,te,M++)}),J}function W(g){if(g._status===-1){var E=g._ioInfo;E!=null&&(E.start=E.end=performance.now()),E=g._result;var D=E();if(D.then(function(M){if(g._status===0||g._status===-1){g._status=1,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="fulfilled",D.value=M)}},function(M){if(g._status===0||g._status===-1){g._status=2,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="rejected",D.reason=M)}}),E=g._ioInfo,E!=null){E.value=D;var J=D.displayName;typeof J==="string"&&(E.name=J)}g._status===-1&&(g._status=0,g._result=D)}if(g._status===1)return E=g._result,E===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
433
434
|
|
|
434
435
|
Your code should look like:
|
|
435
436
|
const MyComponent = lazy(() => import('./MyComponent'))
|
|
@@ -441,8 +442,8 @@ Your code should look like:
|
|
|
441
442
|
1. You might have mismatching versions of React and the renderer (such as React DOM)
|
|
442
443
|
2. You might be breaking the Rules of Hooks
|
|
443
444
|
3. You might have more than one copy of React in the same app
|
|
444
|
-
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`),g}function j(){Le.asyncTransitions--}function T(g){if(U===null)try{var E=("require"+Math.random()).slice(0,7);U=(ky&&ky[E]).call(ky,"timers").setImmediate}catch(D){U=function(J){f===!1&&(f=!0,typeof MessageChannel>"u"&&console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var M=new MessageChannel;M.port1.onmessage=J,M.port2.postMessage(void 0)}}return U(g)}function Z(g){return 1<g.length&&typeof AggregateError==="function"?AggregateError(g):g[0]}function A(g,E){E!==ne-1&&console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),ne=E}function R(g,E,D){var J=Le.actQueue;if(J!==null)if(J.length!==0)try{I(J),T(function(){return R(g,E,D)});return}catch(M){Le.thrownErrors.push(M)}else Le.actQueue=null;0<Le.thrownErrors.length?(J=Z(Le.thrownErrors),Le.thrownErrors.length=0,D(J)):E(g)}function I(g){if(!X){X=!0;var E=0;try{for(;E<g.length;E++){var D=g[E];do{Le.didUsePromise=!1;var J=D(!1);if(J!==null){if(Le.didUsePromise){g[E]=D,g.splice(0,E);return}D=J}else break}while(1)}g.length=0}catch(M){g.splice(0,E+1),Le.thrownErrors.push(M)}finally{X=!1}}}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart==="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var q=Symbol.for("react.transitional.element"),N=Symbol.for("react.portal"),H=Symbol.for("react.fragment"),G=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),ae=Symbol.for("react.consumer"),me=Symbol.for("react.context"),Se=Symbol.for("react.forward_ref"),xe=Symbol.for("react.suspense"),ke=Symbol.for("react.suspense_list"),Ie=Symbol.for("react.memo"),_e=Symbol.for("react.lazy"),Ue=Symbol.for("react.activity"),De=Symbol.iterator,Qe={},bt={isMounted:function(){return!1},enqueueForceUpdate:function(g){r(g,"forceUpdate")},enqueueReplaceState:function(g){r(g,"replaceState")},enqueueSetState:function(g){r(g,"setState")}},Tt=Object.assign,Dt={};Object.freeze(Dt),o.prototype.isReactComponent={},o.prototype.setState=function(g,E){if(typeof g!=="object"&&typeof g!=="function"&&g!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,g,E,"setState")},o.prototype.forceUpdate=function(g){this.updater.enqueueForceUpdate(this,g,"forceUpdate")};var lt={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]};for(V in lt)lt.hasOwnProperty(V)&&e(V,lt[V]);n.prototype=o.prototype,lt=i.prototype=new n,lt.constructor=i,Tt(lt,o.prototype),lt.isPureReactComponent=!0;var Or=Array.isArray,$n=Symbol.for("react.client.reference"),Le={H:null,A:null,T:null,S:null,actQueue:null,asyncTransitions:0,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1,didUsePromise:!1,thrownErrors:[],getCurrentStack:null,recentlyCreatedOwnerStacks:0},uo=Object.prototype.hasOwnProperty,ls=console.createTask?console.createTask:function(){return null};lt={react_stack_bottom_frame:function(g){return g()}};var us,Ea,ds={},On=lt.react_stack_bottom_frame.bind(lt,m)(),Kl=ls(d(m)),Qo=!1,Aa=/\/+/g,Ia=typeof reportError==="function"?reportError:function(g){if(typeof window==="object"&&typeof window.ErrorEvent==="function"){var E=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof g==="object"&&g!==null&&typeof g.message==="string"?String(g.message):String(g),error:g});if(!window.dispatchEvent(E))return}else if(typeof process==="object"&&typeof process.emit==="function"){process.emit("uncaughtException",g);return}console.error(g)},f=!1,U=null,ne=0,ie=!1,X=!1,w=typeof queueMicrotask==="function"?function(g){queueMicrotask(function(){return queueMicrotask(g)})}:T;lt=Object.freeze({__proto__:null,c:function(g){return ee().useMemoCache(g)}});var V={map:z,forEach:function(g,E,D){z(g,function(){E.apply(this,arguments)},D)},count:function(g){var E=0;return z(g,function(){E++}),E},toArray:function(g){return z(g,function(E){return E})||[]},only:function(g){if(!k(g))throw Error("React.Children.only expected to receive a single React element child.");return g}};Bpe.Activity=Ue,Bpe.Children=V,Bpe.Component=o,Bpe.Fragment=H,Bpe.Profiler=re,Bpe.PureComponent=i,Bpe.StrictMode=G,Bpe.Suspense=xe,Bpe.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Le,Bpe.__COMPILER_RUNTIME=lt,Bpe.act=function(g){var E=Le.actQueue,D=ne;ne++;var J=Le.actQueue=E!==null?E:[],M=!1;try{var te=g()}catch(fe){Le.thrownErrors.push(fe)}if(0<Le.thrownErrors.length)throw A(E,D),g=Z(Le.thrownErrors),Le.thrownErrors.length=0,g;if(te!==null&&typeof te==="object"&&typeof te.then==="function"){var se=te;return w(function(){M||ie||(ie=!0,console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),{then:function(fe,Te){M=!0,se.then(function(Pe){if(A(E,D),D===0){try{I(J),T(function(){return R(Pe,fe,Te)})}catch(ps){Le.thrownErrors.push(ps)}if(0<Le.thrownErrors.length){var Cn=Z(Le.thrownErrors);Le.thrownErrors.length=0,Te(Cn)}}else fe(Pe)},function(Pe){A(E,D),0<Le.thrownErrors.length?(Pe=Z(Le.thrownErrors),Le.thrownErrors.length=0,Te(Pe)):Te(Pe)})}}}var be=te;if(A(E,D),D===0&&(I(J),J.length!==0&&w(function(){M||ie||(ie=!0,console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"))}),Le.actQueue=null),0<Le.thrownErrors.length)throw g=Z(Le.thrownErrors),Le.thrownErrors.length=0,g;return{then:function(fe,Te){M=!0,D===0?(Le.actQueue=J,T(function(){return R(be,fe,Te)})):fe(be)}}},Bpe.cache=function(g){return function(){return g.apply(null,arguments)}},Bpe.cacheSignal=function(){return null},Bpe.captureOwnerStack=function(){var g=Le.getCurrentStack;return g===null?null:g()},Bpe.cloneElement=function(g,E,D){if(g===null||g===void 0)throw Error("The argument must be a React element, but you passed "+g+".");var J=Tt({},g.props),M=g.key,te=g._owner;if(E!=null){var se;e:{if(uo.call(E,"ref")&&(se=Object.getOwnPropertyDescriptor(E,"ref").get)&&se.isReactWarning){se=!1;break e}se=E.ref!==void 0}se&&(te=p()),h(E)&&(l(E.key),M=""+E.key);for(be in E)!uo.call(E,be)||be==="key"||be==="__self"||be==="__source"||be==="ref"&&E.ref===void 0||(J[be]=E[be])}var be=arguments.length-2;if(be===1)J.children=D;else if(1<be){se=Array(be);for(var fe=0;fe<be;fe++)se[fe]=arguments[fe+2];J.children=se}J=v(g.type,M,J,te,g._debugStack,g._debugTask);for(M=2;M<arguments.length;M++)_(arguments[M]);return J},Bpe.createContext=function(g){return g={$$typeof:me,_currentValue:g,_currentValue2:g,_threadCount:0,Provider:null,Consumer:null},g.Provider=g,g.Consumer={$$typeof:ae,_context:g},g._currentRenderer=null,g._currentRenderer2=null,g},Bpe.createElement=function(g,E,D){for(var J=2;J<arguments.length;J++)_(arguments[J]);J={};var M=null;if(E!=null)for(fe in Ea||!("__self"in E)||"key"in E||(Ea=!0,console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")),h(E)&&(l(E.key),M=""+E.key),E)uo.call(E,fe)&&fe!=="key"&&fe!=="__self"&&fe!=="__source"&&(J[fe]=E[fe]);var te=arguments.length-2;if(te===1)J.children=D;else if(1<te){for(var se=Array(te),be=0;be<te;be++)se[be]=arguments[be+2];Object.freeze&&Object.freeze(se),J.children=se}if(g&&g.defaultProps)for(fe in te=g.defaultProps,te)J[fe]===void 0&&(J[fe]=te[fe]);M&&S(J,typeof g==="function"?g.displayName||g.name||"Unknown":g);var fe=1e4>Le.recentlyCreatedOwnerStacks++;return v(g,M,J,p(),fe?Error("react-stack-top-frame"):On,fe?ls(d(g)):Kl)},Bpe.createRef=function(){var g={current:null};return Object.seal(g),g},Bpe.forwardRef=function(g){g!=null&&g.$$typeof===Ie?console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof g!=="function"?console.error("forwardRef requires a render function but was given %s.",g===null?"null":typeof g):g.length!==0&&g.length!==2&&console.error("forwardRef render functions accept exactly two parameters: props and ref. %s",g.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),g!=null&&g.defaultProps!=null&&console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");var E={$$typeof:Se,render:g},D;return Object.defineProperty(E,"displayName",{enumerable:!1,configurable:!0,get:function(){return D},set:function(J){D=J,g.name||g.displayName||(Object.defineProperty(g,"name",{value:J}),g.displayName=J)}}),E},Bpe.isValidElement=k,Bpe.lazy=function(g){g={_status:-1,_result:g};var E={$$typeof:_e,_payload:g,_init:W},D={name:"lazy",start:-1,end:-1,value:null,owner:null,debugStack:Error("react-stack-top-frame"),debugTask:console.createTask?console.createTask("lazy()"):null};return g._ioInfo=D,E._debugInfo=[{awaited:D}],E},Bpe.memo=function(g,E){g==null&&console.error("memo: The first argument must be a component. Instead received: %s",g===null?"null":typeof g),E={$$typeof:Ie,type:g,compare:E===void 0?null:E};var D;return Object.defineProperty(E,"displayName",{enumerable:!1,configurable:!0,get:function(){return D},set:function(J){D=J,g.name||g.displayName||(Object.defineProperty(g,"name",{value:J}),g.displayName=J)}}),E},Bpe.startTransition=function(g){var E=Le.T,D={};D._updatedFibers=new Set,Le.T=D;try{var J=g(),M=Le.S;M!==null&&M(D,J),typeof J==="object"&&J!==null&&typeof J.then==="function"&&(Le.asyncTransitions++,J.then(j,j),J.then(s,Ia))}catch(te){Ia(te)}finally{E===null&&D._updatedFibers&&(g=D._updatedFibers.size,D._updatedFibers.clear(),10<g&&console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")),E!==null&&D.types!==null&&(E.types!==null&&E.types!==D.types&&console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."),E.types=D.types),Le.T=E}},Bpe.unstable_useCacheRefresh=function(){return ee().useCacheRefresh()},Bpe.use=function(g){return ee().use(g)},Bpe.useActionState=function(g,E,D){return ee().useActionState(g,E,D)},Bpe.useCallback=function(g,E){return ee().useCallback(g,E)},Bpe.useContext=function(g){var E=ee();return g.$$typeof===ae&&console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"),E.useContext(g)},Bpe.useDebugValue=function(g,E){return ee().useDebugValue(g,E)},Bpe.useDeferredValue=function(g,E){return ee().useDeferredValue(g,E)},Bpe.useEffect=function(g,E){return g==null&&console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useEffect(g,E)},Bpe.useEffectEvent=function(g){return ee().useEffectEvent(g)},Bpe.useId=function(){return ee().useId()},Bpe.useImperativeHandle=function(g,E,D){return ee().useImperativeHandle(g,E,D)},Bpe.useInsertionEffect=function(g,E){return g==null&&console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useInsertionEffect(g,E)},Bpe.useLayoutEffect=function(g,E){return g==null&&console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useLayoutEffect(g,E)},Bpe.useMemo=function(g,E){return ee().useMemo(g,E)},Bpe.useOptimistic=function(g,E){return ee().useOptimistic(g,E)},Bpe.useReducer=function(g,E,D){return ee().useReducer(g,E,D)},Bpe.useRef=function(g){return ee().useRef(g)},Bpe.useState=function(g){return ee().useState(g)},Bpe.useSyncExternalStore=function(g,E,D){return ee().useSyncExternalStore(g,E,D)},Bpe.useTransition=function(){return ee().useTransition()},Bpe.version="19.2.7",typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop==="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()});var D6,L6;var qR=b(()=>{D6=Vl(MR(),1),L6=D6.createContext(void 0)});var Upe;var Z6=b(()=>{jR();N6();qR();ue();Upe=Vl(MR(),1)});var Mpe,qpe;var j6=b(()=>{wt();ue();DR();Mpe=il.omit({url:!0,analyticsScript:!0}),qpe=Mpe.extend({title:c.string().optional().describe("Optional site title override"),description:c.string().optional().describe("Optional site description override")})});function FR(e,t={}){let r=B6(e),o=B6(t.sharedDomain??"rizom.ai").replace(/^\./,""),n=`.${o}`;if(r.endsWith(n)){let i=r.slice(0,-n.length);if(i.length>0&&!i.includes("."))return`${i}-preview.${o}`}return`preview.${r}`}function B6(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}var U6=b(()=>{vg()});var Kpe,Hpe;var M6=b(()=>{ue();yy();BR();Kpe=c.string(),Hpe=c.custom((e)=>Ws(e)&&e6.safeParse(e).success)});var Vpe;var q6=b(()=>{vg();ue();Vpe=c.object({title:c.string().min(1),slug:c.string().min(1),description:c.string(),content:c.string(),author:c.string(),publishedAt:c.iso.datetime({offset:!0}),category:c.string().min(1).optional()})});var F6=b(()=>{NR();p6();DR();k6();BR();Z6();j6();U6();M6();qR();q6()});function J6(e,t={}){return FR(e,t)}var K6=b(()=>{F6()});var Y6={};Lt(Y6,{assertPilotUsersRemoved:()=>Q6,createPilotOffboardDriver:()=>V6,offboardPilotUsers:()=>Xpe});import{readdir as Wpe,readFile as Gpe,rm as fp,writeFile as Qpe}from"fs/promises";import{basename as Ype,join as Do}from"path";async function Xpe(e,t){let r=[...new Set(t.handles.map((p)=>br.parse(p)))].sort((p,m)=>p.localeCompare(m));if(r.length===0)throw Error("At least one pilot handle is required");let o=t.dryRun??!0,n=`sunset:${r.join(",")}`;if(!o&&t.confirmation!==n)throw Error(`Exact confirmation required: ${n}`);let i=t.env??process.env,s=t.logger??console.info,a=await xt(e),l=r.map((p)=>efe(a,p,i)),u=t.driver??V6({env:i,fetchImpl:t.fetchImpl,contentRepoTokenName:a.pilot.contentRepoAdminToken}),d=await Promise.all(l.map(async(p)=>({target:p,inspection:await u.inspect(p)})));if(rfe(d),nfe(d,o,s),!o){for(let p of d)if(!p.inspection.contentRepoArchived)await u.archiveContentRepo(p.target),s(`[${p.target.handle}] archived ${p.target.contentRepo}`);for(let p of d)for(let m of p.inspection.dnsRecords)await u.deleteDnsRecord(p.target,m),s(`[${p.target.handle}] deleted DNS ${m.name}`);for(let p of d)if(p.inspection.server)await u.deleteServer(p.target,p.inspection.server),s(`[${p.target.handle}] deleted ${p.target.instanceName}`);await tfe(l,u,t.sleep??((p)=>new Promise((m)=>setTimeout(m,p)))),await ofe(e,r),await Pi(e),await Q6(e,r),s(`Removed desired state for ${r.length} pilot user(s)`)}return{dryRun:o,handles:r,confirmation:n,plans:d}}function efe(e,t,r){let o=e.users.find((d)=>d.handle===t),n=`${t}${e.pilot.domainSuffix}`,i=o?.domain??n,s=J6(i,{sharedDomain:e.pilot.domainSuffix}),a=o?.cloudflareZoneId??Ry(r,"CF_ZONE_ID"),l=o?.contentRepo??`${e.pilot.contentRepoPrefix}${t}-content`,u=l.includes("/")?l:`${e.pilot.githubOrg}/${l}`;return{handle:t,instanceName:`rover-${t}`,domain:i,previewDomain:s,...i===n?{}:{wwwDomain:`www.${i}`},contentRepo:u,cloudflareZoneId:a}}async function tfe(e,t,r){for(let o of e)for(let n=1;n<=20;n+=1){let i=await t.inspect(o);if(!i.server&&i.dnsRecords.length===0&&i.contentRepoArchived)break;if(n===20)throw Error(`[${o.handle}] provider cleanup did not converge`);await r(1500)}}function rfe(e){for(let{target:t,inspection:r}of e){if(r.server&&r.server.name!==t.instanceName)throw Error(`[${t.handle}] unexpected server name: ${r.server.name}`);let o=new Set([t.domain,t.previewDomain,...t.wwwDomain?[t.wwwDomain]:[]]);for(let n of r.dnsRecords){if(!o.has(n.name))throw Error(`[${t.handle}] refusing unexpected DNS record ${n.name}`);if(n.type==="A"&&r.server?.ip&&n.content!==r.server.ip)throw Error(`[${t.handle}] ${n.name} does not point to the retiring server`)}}}function nfe(e,t,r){r(`${t?"Dry run":"Apply"}: ${e.map(({target:o})=>o.handle).join(", ")}`);for(let{target:o,inspection:n}of e){let i=n.server?`delete ${o.instanceName}`:"already absent",s=n.dnsRecords.length>0?n.dnsRecords.map((l)=>`${l.type} ${l.name}`).join(", "):"already absent",a=n.contentRepoArchived?"already archived":`archive ${o.contentRepo}`;r(`[${o.handle}] server: ${i}; DNS: ${s}; repo: ${a}`)}r("Runtime backups: none")}async function ofe(e,t){let r=new Set(t),o=Do(e,"cohorts");for(let n of(await Wpe(o)).filter((i)=>i.endsWith(".yaml"))){let i=Do(o,n),s=await Gpe(i,"utf8"),a=tn(s);if(a.errors.length>0)throw Error(`${n}: ${a.errors[0]?.message??"invalid YAML"}`);let l=a.get("members",!0);if(!kR(l))throw Error(`${n}: members must be a sequence`);let u=l.items.filter((d)=>!Po(d)||typeof d.value!=="string"||!r.has(d.value));if(u.length===l.items.length)continue;if(u.length===0){await fp(i);continue}l.items=u,hn.parse(a.toJS()),await Qpe(i,a.toString())}for(let n of t)await Promise.all([fp(Do(e,"users",`${n}.yaml`),{force:!0}),fp(Do(e,"users",`${n}.secrets.yaml`),{force:!0}),fp(Do(e,"users",`${n}.secrets.yaml.age`),{force:!0}),fp(Do(e,"users",n),{recursive:!0,force:!0})])}function V6(e){let t=e.fetchImpl??fetch,r=Ry(e.env,"HCLOUD_TOKEN"),o=Ry(e.env,"CF_API_TOKEN"),n=Ry(e.env,e.contentRepoTokenName);return{async inspect(i){let[s,a,l]=await Promise.all([ife(t,r,i.instanceName),Promise.all([i.domain,i.previewDomain,...i.wwwDomain?[i.wwwDomain]:[]].map((u)=>sfe(t,o,i.cloudflareZoneId,u))).then((u)=>u.flat()),afe(t,n,i.contentRepo)]);if(s.length>1)throw Error(`[${i.handle}] expected at most one server, found ${s.length}`);return{...s[0]?{server:s[0]}:{},dnsRecords:a,contentRepoArchived:l.archived}},async archiveContentRepo(i){await al(t,`https://api.github.com/repos/${i.contentRepo}`,{method:"PATCH",headers:W6(n),body:JSON.stringify({archived:!0})},"GitHub repository archive")},async deleteDnsRecord(i,s){if(cl(await al(t,`https://api.cloudflare.com/client/v4/zones/${i.cloudflareZoneId}/dns_records/${s.id}`,{method:"DELETE",headers:G6(o)},"Cloudflare DNS delete")).success!==!0)throw Error(`Cloudflare DNS delete failed for ${s.name}`)},async deleteServer(i,s){await al(t,`https://api.hetzner.cloud/v1/servers/${s.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}},"Hetzner server delete",!0)}}}async function ife(e,t,r){let o=new URL("https://api.hetzner.cloud/v1/servers");o.searchParams.set("label_selector",`brain=${r}`);let i=cl(await al(e,o.toString(),{headers:{Authorization:`Bearer ${t}`}},"Hetzner server lookup")).servers;if(!Array.isArray(i))throw Error("Hetzner server lookup returned an invalid payload");return i.map((s)=>{let a=cl(s),l=H6(a.public_net),u=H6(l?.ipv4);return{id:cfe(a.id,"Hetzner server id"),name:mp(a.name,"Hetzner server name"),...typeof u?.ip==="string"?{ip:u.ip}:{}}})}async function sfe(e,t,r,o){let n=new URL(`https://api.cloudflare.com/client/v4/zones/${r}/dns_records`);n.searchParams.set("name",o);let i=cl(await al(e,n.toString(),{headers:G6(t)},"Cloudflare DNS lookup")),s=i.result;if(i.success!==!0||!Array.isArray(s))throw Error(`Cloudflare DNS lookup failed for ${o}`);return s.map((a)=>{let l=cl(a),u=mp(l.type,"Cloudflare record type");if(u!=="A"&&u!=="CNAME")throw Error(`Unsupported Cloudflare record type ${u} for ${o}`);return{id:mp(l.id,"Cloudflare record id"),name:mp(l.name,"Cloudflare record name"),type:u,content:mp(l.content,"Cloudflare record content")}})}async function afe(e,t,r){let o=cl(await al(e,`https://api.github.com/repos/${r}`,{headers:W6(t)},"GitHub repository lookup"));if(typeof o.archived!=="boolean")throw Error(`Invalid repository archive state for ${r}`);return{archived:o.archived}}async function al(e,t,r,o,n=!1){let i=await e(t,r),s=await i.text();if(!i.ok)throw Error(`${o} failed (${i.status}): ${s}`);if(!s&&n)return{};try{return JSON.parse(s)}catch{throw Error(`${o} returned an invalid JSON response`)}}function W6(e){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"}}function G6(e){return{Authorization:`Bearer ${e}`}}function Ry(e,t){let r=e[t];if(!r)throw Error(`Missing required environment variable: ${t}`);return r}function cl(e){if(!Ws(e))throw Error("Provider returned an unexpected payload");return e}function H6(e){return Ws(e)?e:void 0}function mp(e,t){if(typeof e!=="string"||e.length===0)throw Error(`Missing ${t}`);return e}function cfe(e,t){if(typeof e!=="number")throw Error(`Missing ${t}`);return e}async function Q6(e,t){for(let r of t)for(let o of[Do(e,"users",`${r}.yaml`),Do(e,"users",`${r}.secrets.yaml.age`),Do(e,"users",r)])if(await Ir(o))throw Error(`Offboarded user state remains: ${Ype(o)}`)}var X6=b(()=>{rl();gn();K6();Pd();$o();Xs()});var e4="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as t4}from"crypto";function ufe(e){if(e<0)throw RangeError("Wrong ID size");try{if(!Ji||Ji.length<e)Ji=Buffer.allocUnsafe(e*lfe),t4.getRandomValues(Ji),ll=0;else if(ll+e>Ji.length)t4.getRandomValues(Ji),ll=0}catch(t){throw Ji=void 0,t}ll+=e}function r4(e=21){ufe(e|=0);let t="";for(let r=ll-e;r<ll;r++)t+=e4[Ji[r]&63];return t}var lfe=128,Ji,ll;var n4=()=>{};function Lo(e=12){return r4(e)}var hp=b(()=>{n4()});import{openSync as dfe,writeSync as pfe}from"fs";function ffe(e){return ul?`[${ul}] ${e}`:e}class Rr{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??ca.INFO,this.context=e.context??void 0,this.useStderr=e.useStderr??!1,this.format=e.format??"text",this.logFile=e.logFile,t!==void 0)this.fileHandle=t;else if(this.logFile)try{this.fileHandle=dfe(this.logFile,"a")}catch{}}static getInstance(e){if(!Rr.instance)Rr.instance=new Rr(e);else{if(e?.useStderr!==void 0)Rr.instance.useStderr=e.useStderr;if(e?.level!==void 0)Rr.instance.level=e.level}return Rr.instance}static resetInstance(){Rr.instance=null,ul=void 0}static setProcessRole(e){ul=e}static createFresh(e){return new Rr(e)}formatEntry(e,t,r){if(this.format==="json")return this.formatJsonEntry(e,t,r);return ffe([`[${new Date().toISOString()}]`,...this.context?[`[${this.context}]`]:[],t].join(" "))}write(e,t,r,o){if(this.format==="json")e(this.formatEntry(t,r,o));else if(o.length>0)e(this.formatEntry(t,r,[]),...o);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,o);try{pfe(this.fileHandle,n+`
|
|
445
|
-
`)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,...ul&&{role:ul},msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}debugStream(){return this.useStderr?console.error.bind(console):console.debug.bind(console)}silly(e,...t){if(this.level<=ca.SILLY)this.write(this.debugStream(),"silly",e,t)}verbose(e,...t){if(this.level<=ca.VERBOSE)this.write(this.debugStream(),"verbose",e,t)}debug(e,...t){if(this.level<=ca.DEBUG)this.write(this.debugStream(),"debug",e,t)}info(e,...t){if(this.level<=ca.INFO){let r=this.useStderr?console.error.bind(console):console.info.bind(console);this.write(r,"info",e,t)}}warn(e,...t){if(this.level<=ca.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=ca.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new Rr({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var ca,ul,rZe;var JR=b(()=>{ca={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};rZe=Rr.getInstance()});var KR,mfe,dl,sZe;var gp=b(()=>{wt();ue();KR=c.enum(["file_operations","content_operations","data_processing","batch_processing"]),mfe=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:KR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Wn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:To.optional()}),dl=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:KR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Wn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:To.optional(),rootJobId:c.string()}),sZe=c.enum(["none","skip","replace","coalesce"])});var hfe,Ki=15000;var yp=b(()=>{gp();ue();hfe=c.object({id:c.string(),type:c.string(),data:c.string(),status:c.enum(["pending","processing","completed","failed"]),source:c.string().nullable(),priority:c.number(),retryCount:c.number(),maxRetries:c.number(),lastError:c.string().nullable(),lastErrorPublic:c.unknown(),createdAt:c.number(),scheduledFor:c.number(),startedAt:c.number().nullable(),completedAt:c.number().nullable(),attemptId:c.string().nullable(),workerSlotId:c.string().nullable(),workerSessionId:c.string().nullable(),leaseExpiresAt:c.number().nullable(),attemptHeartbeatAt:c.number().nullable(),runtimeUpdatedAt:c.number().nullable(),metadata:dl,progress:c.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:c.unknown().nullable().optional()})});var HR,o4,Oe,gfe,yfe,i4,s4,a4;var Zo=b(()=>{wt();ue();gp();HR=c.enum(["pending","processing","completed","failed"]),o4=c.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},gfe=c.object({id:c.string(),type:c.string(),status:HR,data:c.unknown(),result:c.unknown().optional(),lastError:c.string().optional().nullable(),attempts:c.number(),maxRetries:c.number(),priority:c.number(),createdAt:c.date(),updatedAt:c.date(),processedAt:c.date().optional().nullable(),completedAt:c.date().optional().nullable(),failedAt:c.date().optional().nullable()}),yfe=c.object({jobId:c.string(),type:c.string(),status:o4,result:c.unknown().optional(),error:c.string().optional()}),i4=c.object({success:c.literal(!1),error:c.string().optional()}),s4=c.object({id:c.string(),type:c.enum(["job","batch"]),status:HR,message:c.string().optional(),progress:c.object({current:c.number(),total:c.number(),percentage:c.number()}).optional(),aggregationKey:c.string().optional(),batchDetails:c.object({totalOperations:c.number(),completedOperations:c.number(),failedOperations:c.number(),currentOperation:c.string().optional(),errors:c.array(c.string()).optional()}).optional(),jobDetails:c.object({jobType:c.string(),priority:c.number(),retryCount:c.number()}).optional(),metadata:dl}),a4=Gn(LI.progress,s4)});var Ce,Wt;var wn=b(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Wt=class Wt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function c4(e){let t=bfe.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?Sfe(r.authority):void 0,i=la(r.path),s=r.query!==void 0?wfe(r.query):void 0,a=r.fragment!==void 0?la(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function Sfe(e){let t=vfe.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=la(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:la(r.username),password:r.password!==void 0?la(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function wfe(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:la(n.replaceAll("+"," ")),value:la(i.replaceAll("+"," "))})}return{pairs:r}}function la(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function bp(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=xfe(t.host),i=_fe(t.port),a=`//${Efe(t.userinfo)}${n}${i}`,l=r.split("/").map(encodeURIComponent).join("/");if(l!==""&&!l.startsWith("/"))l="/"+l;return new URL(`${o}${a}${l}`)}function xfe(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function _fe(e){return e!==void 0?`:${e}`:""}function Efe(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var bfe,vfe;var Ty=b(()=>{wn();bfe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();vfe=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var fl,l4,u4,Sp,$y,Afe,Gt,d4,m4=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),h4=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),g4=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=Sp[t>>18&63]+Sp[t>>12&63]+Sp[t>>6&63]+Sp[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},GR,VR,Oy=(e,t=!1)=>t?m4(VR(e)):VR(e),Ife=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Gt(192|t>>>6)+Gt(128|t&63):Gt(224|t>>>12&15)+Gt(128|t>>>6&63)+Gt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Gt(240|t>>>18&7)+Gt(128|t>>>12&63)+Gt(128|t>>>6&63)+Gt(128|t&63)}},kfe,y4=(e)=>e.replace(kfe,Ife),p4,pl=(e,t=!1)=>t?m4(p4(e)):p4(e),f4=(e)=>pl(e,!0),Rfe,Tfe=(e)=>{switch(e.length){case 4:var t=(7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3),r=t-65536;return Gt((r>>>10)+55296)+Gt((r&1023)+56320);case 3:return Gt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Gt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},b4=(e)=>e.replace(Rfe,Tfe),S4=(e)=>{if(e=e.replace(/\s+/g,""),!Afe.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=$y[e.charAt(i++)]<<18|$y[e.charAt(i++)]<<12|(r=$y[e.charAt(i++)])<<6|(o=$y[e.charAt(i++)]),r===64)n.push(Gt(t>>16&255));else if(o===64)n.push(Gt(t>>16&255,t>>8&255));else n.push(Gt(t>>16&255,t>>8&255,t&255));return n.join("")},QR,v4,w4=(e)=>v4(x4(e)),$fe,x4=(e)=>h4(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),WR=(e)=>$fe(x4(e)),Ofe=(e)=>{if(typeof e!=="string")return!1;let t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},_4=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),E4=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,_4(r));e("fromBase64",function(){return WR(this)}),e("toBase64",function(t){return pl(this,t)}),e("toBase64URI",function(){return pl(this,!0)}),e("toBase64URL",function(){return pl(this,!0)}),e("toUint8Array",function(){return w4(this)})},A4=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,_4(r));e("toBase64",function(t){return Oy(this,t)}),e("toBase64URI",function(){return Oy(this,!0)}),e("toBase64URL",function(){return Oy(this,!0)})},Cfe=()=>{E4(),A4()},ml;var Cy=b(()=>{fl=typeof Buffer==="function",l4=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,u4=typeof TextEncoder==="function"?new TextEncoder:void 0,Sp=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),$y=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(Sp),Afe=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Gt=String.fromCharCode.bind(String),d4=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),GR=typeof btoa==="function"?(e)=>btoa(e):fl?(e)=>Buffer.from(e,"binary").toString("base64"):g4,VR=fl?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Gt.apply(null,e.subarray(o,o+4096)));return GR(r.join(""))},kfe=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,p4=fl?(e)=>Buffer.from(e,"utf8").toString("base64"):u4?(e)=>VR(u4.encode(e)):(e)=>GR(y4(e)),Rfe=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,QR=typeof atob==="function"?(e)=>atob(h4(e)):fl?(e)=>Buffer.from(e,"base64").toString("binary"):S4,v4=fl?(e)=>d4(Buffer.from(e,"base64")):(e)=>d4(QR(e).split("").map((t)=>t.charCodeAt(0))),$fe=fl?(e)=>Buffer.from(e,"base64").toString("utf8"):l4?(e)=>l4.decode(v4(e)):(e)=>b4(QR(e)),ml={version:"3.8.0",VERSION:"3.8.0",atob:QR,atobPolyfill:S4,btoa:GR,btoaPolyfill:g4,fromBase64:WR,toBase64:pl,encode:pl,encodeURI:f4,encodeURL:f4,utob:y4,btou:b4,decode:WR,isValid:Ofe,fromUint8Array:Oy,toUint8Array:w4,extendString:E4,extendUint8Array:A4,extendBuiltins:Cfe}});function Hi(e){if(e==="write")return"BEGIN IMMEDIATE";else if(e==="read")return"BEGIN TRANSACTION READONLY";else if(e==="deferred")return"BEGIN DEFERRED";else throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}class hl{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(zfe),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function zfe(e){return Array.prototype.map.call(e,Pfe)}function Pfe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return ml.fromUint8Array(new Uint8Array(e));else return e}var ro="https://github.com/libsql/libsql-client-ts#supported-urls";var gl=b(()=>{Cy()});function k4(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function vp(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===I4)r="file::memory:";let l=c4(r),u=l.scheme.toLowerCase(),d=u==="file"&&l.path===I4&&l.authority===void 0,p;if(d)p={cache:{values:["shared","private"],update:(y,v)=>a.push(`${y}=${v}`)}};else p={tls:{values:["0","1"],update:(y,v)=>n=v==="1"},authToken:{update:(y,v)=>o=v}};for(let{key:y,value:v}of l.query?.pairs??[]){if(!Object.hasOwn(p,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=p[y];if(x.values!==void 0&&!x.values.includes(v))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(v)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,v)}let m=a.length===0?"":`?${a.join("&")}`,h=l.path+m,S;if(u==="libsql")if(n===!1){if(l.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");S=t?"http":"ws"}else S=t?"https":"wss";else S=u;if(S==="http"||S==="ws")n??=!1;else n??=!0;if(S!=="http"&&S!=="ws"&&S!=="https"&&S!=="wss"&&S!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(l.scheme+":")}. For more information, please read ${ro}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(l.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+l.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:S,tls:n,authority:l.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var I4=":memory:";var wp=b(()=>{wn();Ty();gl()});var T4=ye(function(rn){var Nfe=rn&&rn.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),Dfe=rn&&rn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),R4=rn&&rn.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null){for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))Nfe(t,e,r)}return Dfe(t,e),t};Object.defineProperty(rn,"__esModule",{value:!0});rn.load=rn.currentTarget=void 0;var Lfe=R4(Fr("path")),Zfe=R4(Fr("fs"));function jfe(){let e=null;switch(process.platform){case"android":switch(process.arch){case"arm":return"android-arm-eabi";case"arm64":return"android-arm64"}e="Android";break;case"win32":switch(process.arch){case"x64":return"win32-x64-msvc";case"arm64":return"win32-arm64-msvc";case"ia32":return"win32-ia32-msvc"}e="Windows";break;case"darwin":switch(process.arch){case"x64":return"darwin-x64";case"arm64":return"darwin-arm64"}e="macOS";break;case"linux":switch(process.arch){case"x64":case"arm64":return Bfe()?`linux-${process.arch}-gnu`:`linux-${process.arch}-musl`;case"arm":return"linux-arm-gnueabihf"}e="Linux";break;case"freebsd":if(process.arch==="x64")return"freebsd-x64";e="FreeBSD";break}if(e)throw Error(`Neon: unsupported ${e} architecture: ${process.arch}`);throw Error(`Neon: unsupported system: ${process.platform}`)}rn.currentTarget=jfe;function Bfe(){let e=process.report?.getReport();if(typeof e!=="object"||!e||!("header"in e))return!1;let t=e.header;return typeof t==="object"&&!!t&&"glibcVersionRuntime"in t}function Ufe(e){let t=Lfe.join(e,"index.node");return Zfe.existsSync(t)?Fr(t):null}rn.load=Ufe});var C4=ye(function(kZe,O4){var $4=()=>process.platform==="linux",YR=null,Mfe=()=>{if(!YR)YR=$4()&&process.report?process.report.getReport():{};return YR};O4.exports={isLinux:$4,getReport:Mfe}});var N4=ye(function(RZe,P4){var z4=Fr("fs"),qfe=(e)=>z4.readFileSync(e,"utf-8"),Ffe=(e)=>new Promise((t,r)=>{z4.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});P4.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:qfe,readFile:Ffe}});var Y4=ye(function(TZe,Q4){var L4=Fr("child_process"),{isLinux:yl,getReport:Z4}=C4(),{LDD_PATH:zy,readFile:j4,readFileSync:B4}=N4(),no,oo,Vi="",U4=()=>{if(!Vi)return new Promise((e)=>{L4.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Vi=t?" ":r,e(Vi)})});return Vi},M4=()=>{if(!Vi)try{Vi=L4.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Vi=" "}return Vi},jo="glibc",q4=/GLIBC\s(\d+\.\d+)/,ua="musl",Jfe=jo.toUpperCase(),Kfe=ua.toLowerCase(),Hfe=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),F4=()=>{let e=Z4();if(e.header&&e.header.glibcVersionRuntime)return jo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Hfe))return ua}return null},J4=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(jo))return jo;if(r&&r.includes(ua))return ua;return null},K4=(e)=>{if(e.includes(Kfe))return ua;if(e.includes(Jfe))return jo;return null},Vfe=async()=>{if(no!==void 0)return no;no=null;try{let e=await j4(zy);no=K4(e)}catch(e){}return no},Wfe=()=>{if(no!==void 0)return no;no=null;try{let e=B4(zy);no=K4(e)}catch(e){}return no},H4=async()=>{let e=null;if(yl()){if(e=await Vfe(),!e)e=F4();if(!e){let t=await U4();e=J4(t)}}return e},V4=()=>{let e=null;if(yl()){if(e=Wfe(),!e)e=F4();if(!e){let t=M4();e=J4(t)}}return e},Gfe=async()=>yl()&&await H4()!==jo,Qfe=()=>yl()&&V4()!==jo,Yfe=async()=>{if(oo!==void 0)return oo;oo=null;try{let t=(await j4(zy)).match(q4);if(t)oo=t[1]}catch(e){}return oo},Xfe=()=>{if(oo!==void 0)return oo;oo=null;try{let t=B4(zy).match(q4);if(t)oo=t[1]}catch(e){}return oo},W4=()=>{let e=Z4();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},D4=(e)=>e.trim().split(/\s+/)[1],G4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(jo))return D4(t);if(r&&o&&r.includes(ua))return D4(o);return null},eme=async()=>{let e=null;if(yl()){if(e=await Yfe(),!e)e=W4();if(!e){let t=await U4();e=G4(t)}}return e},tme=()=>{let e=null;if(yl()){if(e=Xfe(),!e)e=W4();if(!e){let t=M4();e=G4(t)}}return e};Q4.exports={GLIBC:jo,MUSL:ua,family:H4,familySync:V4,isNonGlibcLinux:Gfe,isNonGlibcLinuxSync:Qfe,version:eme,versionSync:tme}});var eF=ye(function($Ze,X4){var rme={ALLOW:0,DENY:1};X4.exports=rme});var rF=ye(function(OZe,tF){var XR={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function da(e,t,r){if(new.target!==da)return new da(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),XR.value=""+e,Object.defineProperty(this,"message",XR),Error.captureStackTrace(this,da),this.code=t,this.rawCode=r}Object.setPrototypeOf(da,Error);Object.setPrototypeOf(da.prototype,Error.prototype);Object.defineProperty(da.prototype,"name",XR);tF.exports=da});var uF=ye(function(CZe,Py){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:nme,currentTarget:ome}=T4(),{familySync:nF,GLIBC:ime,MUSL:sme}=Y4();function ame(){if(process.env.LIBSQL_JS_DEV)return nme(__dirname);let e=ome();if(nF()==ime)switch(e){case"linux-x64-musl":e="linux-x64-gnu";break;case"linux-arm64-musl":e="linux-arm64-gnu";break}if(e==="linux-arm-gnueabihf"&&nF()==sme)e="linux-arm-musleabihf";return Fr(`@libsql/${e}`)}var{databaseOpen:cme,databaseOpenWithSync:lme,databaseInTransaction:ume,databaseInterrupt:dme,databaseClose:pme,databaseSyncSync:fme,databaseSyncUntilSync:mme,databaseExecSync:hme,databasePrepareSync:gme,databaseDefaultSafeIntegers:yme,databaseAuthorizer:bme,databaseLoadExtension:Sme,databaseMaxWriteReplicationIndex:vme,statementRaw:wme,statementIsReader:xme,statementGet:oF,statementRun:iF,statementInterrupt:_me,statementRowsSync:sF,statementColumns:Eme,statementSafeIntegers:Ame,rowsNext:Ime}=ame(),kme=eF(),aF=rF();function bl(e){if(e.libsqlError)return new aF(e.message,e.code,e.rawCode);return e}class cF{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,l=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=lme(e,t.syncUrl,o,r,i,s,a,l,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,l=t?.remoteEncryptionKey??"";this.db=cme(e,i,r,s,a,l)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return ume(n)}}})}sync(){return fme.call(this.db)}syncUntil(e){return mme.call(this.db,e)}prepare(e){try{let t=gme.call(this.db,e);return new lF(t)}catch(t){throw bl(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){bme.call(this.db,e)}loadExtension(...e){Sme.call(this.db,...e)}maxWriteReplicationIndex(){return vme.call(this.db)}exec(e){try{hme.call(this.db,e)}catch(t){throw bl(t)}}interrupt(){dme.call(this.db)}close(){pme.call(this.db),this.open=!1}defaultSafeIntegers(e){return yme.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class lF{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return wme.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return xme.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return iF.call(this.stmt,e[0]);else return iF.call(this.stmt,e.flat())}catch(t){throw bl(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return oF.call(this.stmt,e[0]);else return oF.call(this.stmt,e.flat())}catch(t){throw bl(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=sF.call(this.stmt,e[0]);else t=sF.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)Ime.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw bl(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw bl(t)}}interrupt(){_me.call(this.stmt)}columns(){return Eme.call(this.stmt)}safeIntegers(e){return Ame.call(this.stmt,e??!0),this}}Py.exports=cF;Py.exports.Authorization=kme;Py.exports.SqliteError=aF});import{Buffer as pF}from"buffer";function fF(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${ro}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${ro}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=k4(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new xp.default(o,n);return Pt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new mF(o,n,i,e.intMode)}class mF{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),Pt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{Pt(r,Hi(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Wt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(Pt(r,s,this.#n))}catch(i){if(i instanceof Wt)throw i;if(i instanceof Ce)throw new Wt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return Pt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)Pt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{Pt(t,"PRAGMA foreign_keys=off",this.#n),Pt(t,Hi("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Wt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(Pt(t,e[o],this.#n))}catch(n){if(n instanceof Wt)throw n;if(n instanceof Ce)throw new Wt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Pt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Pt(t,"ROLLBACK",this.#n);Pt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return Pt(t,Hi(e),this.#n),this.#r=null,new hF(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return gF(t,e)}finally{if(t.inTransaction)Pt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new xp.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new xp.default(this.#e,this.#t);return this.#r}}class hF{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),Pt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(Pt(this.#e,n,this.#t))}catch(o){if(o instanceof Wt)throw o;if(o instanceof Ce)throw new Wt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),gF(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Pt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Pt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Pt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function Pt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>dF(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=dF(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),l=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>Rme(m,a,r)),d=0,p=void 0;return new hl(a,l,u,0,void 0)}else{let a=i.run(n),l=a.changes,u=BigInt(a.lastInsertRowid);return new hl([],[],[],l,u)}}catch(i){throw yF(i)}}function Rme(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=Tme(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Tme(e,t){if(typeof e==="bigint")if(t==="number"){if(e<$me||e>Ome)throw RangeError("Received integer which cannot be safely represented as a JavaScript number");return Number(e)}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw Error("Invalid value for IntMode");else if(e instanceof pF)return e.buffer;return e}function dF(e,t){if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<Cme||e>zme)throw RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")switch(t){case"bigint":return e?1n:0n;case"string":return e?"1":"0";default:return e?1:0}else if(e instanceof ArrayBuffer)return pF.from(e);else if(e instanceof Date)return e.valueOf();else if(e===void 0)throw TypeError("undefined cannot be passed as argument to the database");else return e}function gF(e,t){try{e.exec(t)}catch(r){throw yF(r)}}function yF(e){if(e instanceof xp.default.SqliteError){let t=e.code,r=Pme(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function Pme(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return Nme[t]??`SQLITE_UNKNOWN_${t.toString()}`}var xp,$me,Ome=9007199254740991n,Cme,zme=9223372036854775807n,Nme;var bF=b(()=>{wn();wp();gl();xp=Vl(uF(),1);wn();$me=-9007199254740991n;Cme=-9223372036854775808n;Nme={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"}});var Wi;var eT=b(()=>{if(typeof WebSocket<"u")Wi=WebSocket;else if(typeof global<"u")Wi=global.WebSocket;else if(typeof window<"u")Wi=window.WebSocket;else if(typeof self<"u")Wi=self.WebSocket});class Sl{constructor(){this.intMode="number"}intMode}var Ge,ze,_p,_t,Ep,vl,pa,xn,or,io;var Et=b(()=>{Ge=class Ge extends Error{constructor(e){super(e);this.name="ClientError"}};ze=class ze extends Ge{constructor(e){super(e);this.name="ProtoError"}};_p=class _p extends Ge{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};_t=class _t extends Ge{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Ep=class Ep extends Ge{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};vl=class vl extends Ge{constructor(e){super(e);this.name="WebSocketError"}};pa=class pa extends Ge{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};xn=class xn extends Ge{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends Ge{constructor(e){super(e);this.name="InternalError"}};io=class io extends Ge{constructor(e){super(e);this.name="MisuseError"}}});function Tr(e){if(typeof e==="string")return e;throw wl(e,"string")}function Ur(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw wl(e,"string or null")}function Bo(e){if(typeof e==="number")return e;throw wl(e,"number")}function Gi(e){if(typeof e==="boolean")return e;throw wl(e,"boolean")}function Ap(e){if(Array.isArray(e))return e;throw wl(e,"array")}function kt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw wl(e,"object")}function _n(e,t){return Ap(e).map((r)=>t(kt(r)))}function wl(e,t){if(e===void 0)return new ze(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new ze(`Expected ${t}, received ${r}`)}function fa(e,t){return t(kt(e))}var xl=b(()=>{Et()});class SF{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function Ip(e,t){let r=[],o=new SF(r);return o.begin(),t(o,e),o.end(),r.join("")}var ma=0,kp=1,Rp=2,vF=5;class wF{#e;#t;#r;constructor(e){this.#e=e,this.#t=new DataView(e.buffer,e.byteOffset,e.byteLength),this.#r=0}varint(){let e=0;for(let t=0;;t+=7){let r=this.#e[this.#r++];if(e|=(r&127)<<t,!(r&128))break}return e}varintBig(){let e=0n;for(let t=0n;;t+=7n){let r=this.#e[this.#r++];if(e|=BigInt(r&127)<<t,!(r&128))break}return e}bytes(e){let t=new Uint8Array(this.#e.buffer,this.#e.byteOffset+this.#r,e);return this.#r+=e,t}double(){let e=this.#t.getFloat64(this.#r,!0);return this.#r+=8,e}skipVarint(){for(;;)if(!(this.#e[this.#r++]&128))break}skip(e){this.#r+=e}eof(){return this.#r>=this.#e.byteLength}}class xF{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new ze(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(Rp);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Qi(this.bytes(),e)}int32(){return this.#r(ma),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(ma),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(kp),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===ma)this.#e.skipVarint();else if(this.#t===kp)this.#e.skip(8);else if(this.#t===Rp){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===vF)this.#e.skip(4);else throw new ze(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Qi(e,t){let r=new wF(e),o=new xF(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let l=t[s];if(l!==void 0){let u=l(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var tT=b(()=>{Et()});class rT{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,Rp),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new rT;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,ma),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,ma),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,kp),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Tp(e,t){let r=new rT;return t(r,e),r.data()}var _F=()=>{};var nT=b(()=>{xl();tT();_F()});class Yi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var oT=b(()=>{Et()});function Ke(e,t){throw new or(t)}var nn=b(()=>{Et()});function _l(e){if(e===null)return null;else if(typeof e==="string")return e;else if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<Lme||e>Zme)throw RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")return e?1n:0n;else if(e instanceof ArrayBuffer)return new Uint8Array(e);else if(e instanceof Uint8Array)return e;else if(e instanceof Date)return+e.valueOf();else if(typeof e==="object")return""+e.toString();else throw TypeError("Unsupported type of value")}function iT(e,t){if(e===null)return null;else if(typeof e==="number")return e;else if(typeof e==="string")return e;else if(typeof e==="bigint")if(t==="number"){let r=Number(e);if(!Number.isSafeInteger(r))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return r}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw new io("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new ze("Received unrecognized type of Value");else throw Ke(e,"Impossible type of Value")}var Lme,Zme=9223372036854775807n;var sT=b(()=>{Et();nn();Lme=-9223372036854775808n});function ha(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function Dy(e,t){let r=ha(e),o=e.rows.map((n)=>EF(r.columnNames,n,t));return{...r,rows:o}}function Ly(e,t){let r=ha(e),o;if(e.rows.length>0)o=EF(r.columnNames,e.rows[0],t);return{...r,row:o}}function Zy(e,t){let r=ha(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=iT(e.rows[0][0],t);return{...r,value:o}}function EF(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=iT(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Uo(e){return new _p(e.message,e)}var $p=b(()=>{Et();sT()});class ga{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new io("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new _t("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new Ge("SQL text was manually closed"))}_setClosed(e){if(this.#r===void 0)this.#r=e,this.#e._closeSql(this.#t)}get closed(){return this.#r!==void 0}}function Op(e,t){if(t instanceof ga)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var El=b(()=>{Et()});class Xi{#e;#t;constructor(){this.#e=[],this.#t=[]}get length(){return this.#e.length+this.#t.length}push(e){this.#e.push(e)}shift(){if(this.#t.length===0&&this.#e.length>0)this.#t=this.#e.reverse(),this.#e=[];return this.#t.pop()}first(){return this.#t.length!==0?this.#t[this.#t.length-1]:this.#e[0]}}class Cp{sql;_args;_namedArgs;constructor(e){this.sql=e,this._args=[],this._namedArgs=new Map}bindIndexes(e){this._args.length=0;for(let t of e)this._args.push(_l(t));return this}bindIndex(e,t){if(e!==(e|0)||e<=0)throw RangeError("Index of a positional argument must be positive integer");while(this._args.length<e)this._args.push(null);return this._args[e-1]=_l(t),this}bindName(e,t){return this._namedArgs.set(e,_l(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function jy(e,t,r){let o,n=[],i=[];if(t instanceof Cp){o=t.sql,n=t._args;for(let[l,u]of t._namedArgs.entries())i.push({name:l,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((l)=>_l(l));else i=Object.entries(t[1]).map(([l,u])=>({name:l,value:_l(u)}));else o=t;let{sql:s,sqlId:a}=Op(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var By=b(()=>{El();sT()});class Uy{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new aT(this)}execute(){if(this.#t)throw new io("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return Bme(this._stream,this._steps,e);else return jme(this._stream,this._steps,e)}}function jme(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function Bme(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new ze("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new ze("Server produced StepBeginEntry before terminating previous step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new ze("Server produced StepEndEntry but no step is active");let l={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(l,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new ze("Server produced StepErrorEntry for unexpected step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0)}else{if(a.step!==i.step)throw new ze("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new ze("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Uo(a.error);else if(a.type==="none")throw new ze("Server produced unrecognized CursorEntry");else throw Ke(a,"Impossible CursorEntry")}if(i!==void 0)throw new ze("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class aT{_batch;#e;_index;constructor(e){this._batch=e,this.#e=[],this._index=void 0}condition(e){return this.#e.push(e._proto),this}query(e){return this.#t(e,!0,Dy)}queryRow(e){return this.#t(e,!0,Ly)}queryValue(e){return this.#t(e,!0,Zy)}run(e){return this.#t(e,!1,ha)}#t(e,t,r){if(this._index!==void 0)throw new io("This BatchStep has already been added to the batch");let o=jy(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let l=(u,d)=>{if(u!==void 0&&d!==void 0)a(new ze("Server returned both result and error"));else if(d!==void 0)a(Uo(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:l})})}}class ut{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new ut(e._batch,{type:"ok",step:AF(e)})}static error(e){return new ut(e._batch,{type:"error",step:AF(e)})}static not(e){return new ut(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)IF(e,r);return new ut(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)IF(e,r);return new ut(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new ut(e,{type:"is_autocommit"})}}function AF(e){if(e._index===void 0)throw new io("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function IF(e,t){if(t._batch!==e)throw new io("Cannot mix BatchCond objects for different Batch objects")}var cT=b(()=>{Et();$p();By();nn()});function kF(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class Al{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,Dy)}queryRow(e){return this.#e(e,!0,Ly)}queryValue(e){return this.#e(e,!0,Zy)}run(e){return this.#e(e,!1,ha)}#e(e,t,r){let o=jy(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new Uy(this,e)}describe(e){let t=Op(this._sqlOwner(),e);return this._describe(t).then(kF)}sequence(e){let t=Op(this._sqlOwner(),e);return this._sequence(t)}intMode}var My=b(()=>{cT();$p();El();By()});class zp{}var Ume=1000,Mme=10,lT;var RF=b(()=>{Et();lT=class lT extends zp{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new Xi,this.#o=new Xi,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new _t("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<Mme)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:Ume}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new Ge("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var Pp;var uT=b(()=>{Et();My();RF();Pp=class Pp extends Al{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new Pp(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new Xi,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new _t("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new _t("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new _t("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new Ge("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new lT(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(l)=>n._setClosed(l);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new Ge("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function Np(e,t){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId);e.arrayObjects("args",t.args,TF),e.arrayObjects("named_args",t.namedArgs,qme),e.boolean("want_rows",t.wantRows)}function qme(e,t){e.string("name",t.name),e.object("value",t.value,TF)}function Il(e,t){e.arrayObjects("steps",t.steps,Fme)}function Fme(e,t){if(t.condition!==void 0)e.object("condition",t.condition,dT);e.object("stmt",t.stmt,Np)}function dT(e,t){if(e.stringRaw("type",t.type),t.type==="ok"||t.type==="error")e.number("step",t.step);else if(t.type==="not")e.object("cond",t.cond,dT);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,dT);else if(t.type==="is_autocommit");else throw Ke(t,"Impossible type of BatchCond")}function TF(e,t){if(t===null)e.stringRaw("type","null");else if(typeof t==="bigint")e.stringRaw("type","integer"),e.stringRaw("value",""+t);else if(typeof t==="number")e.stringRaw("type","float"),e.number("value",t);else if(typeof t==="string")e.stringRaw("type","text"),e.string("value",t);else if(t instanceof Uint8Array)e.stringRaw("type","blob"),e.stringRaw("base64",ml.fromUint8Array(t));else if(t===void 0);else throw Ke(t,"Impossible type of Value")}var pT=b(()=>{Cy();nn()});function $F(e,t){if(e.stringRaw("type",t.type),t.type==="hello"){if(t.jwt!==void 0)e.string("jwt",t.jwt)}else if(t.type==="request")e.number("request_id",t.requestId),e.object("request",t.request,Jme);else throw Ke(t,"Impossible type of ClientMsg")}function Jme(e,t){if(e.stringRaw("type",t.type),t.type==="open_stream")e.number("stream_id",t.streamId);else if(t.type==="close_stream")e.number("stream_id",t.streamId);else if(t.type==="execute")e.number("stream_id",t.streamId),e.object("stmt",t.stmt,Np);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,Il);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,Il);else if(t.type==="close_cursor")e.number("cursor_id",t.cursorId);else if(t.type==="fetch_cursor")e.number("cursor_id",t.cursorId),e.number("max_count",t.maxCount);else if(t.type==="sequence"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit")e.number("stream_id",t.streamId);else throw Ke(t,"Impossible type of Request")}var OF=b(()=>{pT();nn()});function Dp(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId);for(let r of t.args)e.message(3,r,zF);for(let r of t.namedArgs)e.message(4,r,Kme);e.bool(5,t.wantRows)}function Kme(e,t){e.string(1,t.name),e.message(2,t.value,zF)}function kl(e,t){for(let r of t.steps)e.message(1,r,Hme)}function Hme(e,t){if(t.condition!==void 0)e.message(1,t.condition,fT);e.message(2,t.stmt,Dp)}function fT(e,t){if(t.type==="ok")e.uint32(1,t.step);else if(t.type==="error")e.uint32(2,t.step);else if(t.type==="not")e.message(3,t.cond,fT);else if(t.type==="and")e.message(4,t.conds,CF);else if(t.type==="or")e.message(5,t.conds,CF);else if(t.type==="is_autocommit")e.message(6,void 0,PF);else throw Ke(t,"Impossible type of BatchCond")}function CF(e,t){for(let r of t)e.message(1,r,fT)}function zF(e,t){if(t===null)e.message(1,void 0,PF);else if(typeof t==="bigint")e.sint64(2,t);else if(typeof t==="number")e.double(3,t);else if(typeof t==="string")e.string(4,t);else if(t instanceof Uint8Array)e.bytes(5,t);else if(t===void 0);else throw Ke(t,"Impossible type of Value")}function PF(e,t){}var mT=b(()=>{nn()});function NF(e,t){if(t.type==="hello")e.message(1,t,Vme);else if(t.type==="request")e.message(2,t,Wme);else throw Ke(t,"Impossible type of ClientMsg")}function Vme(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Wme(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Gme);else if(r.type==="close_stream")e.message(3,r,Qme);else if(r.type==="execute")e.message(4,r,Yme);else if(r.type==="batch")e.message(5,r,Xme);else if(r.type==="open_cursor")e.message(6,r,ehe);else if(r.type==="close_cursor")e.message(7,r,the);else if(r.type==="fetch_cursor")e.message(8,r,rhe);else if(r.type==="sequence")e.message(9,r,nhe);else if(r.type==="describe")e.message(10,r,ohe);else if(r.type==="store_sql")e.message(11,r,ihe);else if(r.type==="close_sql")e.message(12,r,she);else if(r.type==="get_autocommit")e.message(13,r,ahe);else throw Ke(r,"Impossible type of Request")}function Gme(e,t){e.int32(1,t.streamId)}function Qme(e,t){e.int32(1,t.streamId)}function Yme(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Dp)}function Xme(e,t){e.int32(1,t.streamId),e.message(2,t.batch,kl)}function ehe(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,kl)}function the(e,t){e.int32(1,t.cursorId)}function rhe(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function nhe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function ohe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function ihe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function she(e,t){e.int32(1,t.sqlId)}function ahe(e,t){e.int32(1,t.streamId)}var DF=b(()=>{mT();nn()});function es(e){let t=Tr(e.message),r=Ur(e.code);return{message:t,code:r}}function Lp(e){let t=_n(e.cols,LF),r=Ap(e.rows).map((s)=>_n(s,ZF)),o=Bo(e.affected_row_count),n=Ur(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function LF(e){let t=Ur(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function qy(e){let t=new Map;Ap(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,Lp(kt(o)))});let r=new Map;return Ap(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,es(kt(o)))}),{stepResults:t,stepErrors:r}}function Fy(e){let t=Tr(e.type);if(t==="step_begin"){let r=Bo(e.step),o=_n(e.cols,LF);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=Bo(e.affected_row_count),o=Ur(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Bo(e.step),o=es(kt(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:_n(e.row,ZF)};else if(t==="error")return{type:"error",error:es(kt(e.error))};else throw new ze("Unexpected type of CursorEntry")}function Jy(e){let t=_n(e.params,che),r=_n(e.cols,lhe),o=Gi(e.is_explain),n=Gi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function che(e){return{name:Ur(e.name)}}function lhe(e){let t=Tr(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function ZF(e){let t=Tr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Tr(e.value);return BigInt(r)}else if(t==="float")return Bo(e.value);else if(t==="text")return Tr(e.value);else if(t==="blob")return ml.toUint8Array(Tr(e.base64));else throw new ze("Unexpected type of Value")}var Ky=b(()=>{Cy();Et();xl()});function jF(e){let t=Tr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:es(kt(e.error))};else if(t==="response_ok"){let r=Bo(e.request_id),o=uhe(kt(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=Bo(e.request_id),o=es(kt(e.error));return{type:"response_error",requestId:r,error:o}}else throw new ze("Unexpected type of ServerMsg")}function uhe(e){let t=Tr(e.type);if(t==="open_stream")return{type:"open_stream"};else if(t==="close_stream")return{type:"close_stream"};else if(t==="execute")return{type:"execute",result:Lp(kt(e.result))};else if(t==="batch")return{type:"batch",result:qy(kt(e.result))};else if(t==="open_cursor")return{type:"open_cursor"};else if(t==="close_cursor")return{type:"close_cursor"};else if(t==="fetch_cursor"){let r=_n(e.entries,Fy),o=Gi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Jy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Gi(e.is_autocommit)};else throw new ze("Unexpected type of Response")}var BF=b(()=>{Et();xl();Ky()});var on,ts,UF,MF,Rl,dhe,phe,Hy,fhe,mhe,hhe,Tl,ghe,yhe,bhe;var Vy=b(()=>{on={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},ts={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(UF))},2(e,t){t.rows.push(e.message(MF))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},UF={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},MF={default(){return[]},1(e,t){t.push(e.message(bhe))}},Rl={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(dhe);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(phe);t.stepErrors.set(r,o)}},dhe={default(){return[0,ts.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(ts)}},phe={default(){return[0,on.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(on)}},Hy={default(){return{type:"none"}},1(e){return e.message(fhe)},2(e){return e.message(mhe)},3(e){return e.message(hhe)},4(e){return{type:"row",row:e.message(MF)}},5(e){return{type:"error",error:e.message(on)}}},fhe={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(UF))}},mhe={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},hhe={default(){return{type:"step_error",step:0,error:on.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(on)}},Tl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(ghe))},2(e,t){t.cols.push(e.message(yhe))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},ghe={default(){return{name:void 0}},1(e,t){t.name=e.string()}},yhe={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},bhe={default(){return},1(e){return null},2(e){return e.sint64()},3(e){return e.double()},4(e){return e.string()},5(e){return e.bytes()}}});var qF,She,vhe,whe,xhe,_he,Ehe,Ahe,Ihe;var FF=b(()=>{Vy();qF={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(She)},3(e){return e.message(whe)},4(e){return e.message(vhe)}},She={default(){return{type:"hello_error",error:on.default()}},1(e,t){t.error=e.message(on)}},vhe={default(){return{type:"response_error",requestId:0,error:on.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(on)}},whe={default(){return{type:"response_ok",requestId:0,response:{type:"none"}}},1(e,t){t.requestId=e.int32()},2(e,t){t.response={type:"open_stream"}},3(e,t){t.response={type:"close_stream"}},4(e,t){t.response=e.message(xhe)},5(e,t){t.response=e.message(_he)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(Ehe)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(Ahe)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(Ihe)}},xhe={default(){return{type:"execute",result:ts.default()}},1(e,t){t.result=e.message(ts)}},_he={default(){return{type:"batch",result:Rl.default()}},1(e,t){t.result=e.message(Rl)}},Ehe={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Hy))},2(e,t){t.done=e.bool()}},Ahe={default(){return{type:"describe",result:Tl.default()}},1(e,t){t.result=e.message(Tl)}},Ihe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var JF,hT,Wy;var Gy=b(()=>{nT();Et();oT();$p();El();nn();uT();OF();DF();BF();FF();JF=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),hT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Wy=class Wy extends Sl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Yi,this._streamIdAlloc=new Yi,this._cursorIdAlloc=new Yi,this.#l=new Yi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#p()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#f(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#p(){let e=this.#e.protocol;if(e===void 0){this.#u(new Ge("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=hT.get(e),this.#i===void 0){this.#u(new ze(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=Ip(e,$F);this.#e.send(r)}else if(t==="protobuf"){let r=Tp(e,NF);this.#e.send(r)}else throw Ke(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new xn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new _t("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#f(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new vl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new vl(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new ze("Received non-text message from server with JSON encoding"));return}t=fa(JSON.parse(e.data),jF)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new ze("Received non-binary message from server with Protobuf encoding"));return}t=Qi(new Uint8Array(e.data),qF)}else throw Ke(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new ze("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new ze("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw Uo(e.error);return}else if(!this.#o)throw new ze("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new ze("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new ze("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new ze("Received unexpected error response");this.#c.free(t),r.errorCallback(Uo(e.error))}else throw Ke(e,"Impossible ServerMsg type")}openStream(){return Pp.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new ga(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new Ge("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var ya;var KF=b(()=>{if(typeof queueMicrotask<"u")ya=queueMicrotask;else{let e=Promise.resolve();ya=(t)=>{e.then(t)}}});class gT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function HF(e){let t=Ur(e.baton),r=Ur(e.base_url),o=_n(e.results,khe);return{baton:t,baseUrl:r,results:o}}function khe(e){let t=Tr(e.type);if(t==="ok")return{type:"ok",response:Rhe(kt(e.response))};else if(t==="error")return{type:"error",error:es(kt(e.error))};else throw new ze("Unexpected type of StreamResult")}function Rhe(e){let t=Tr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Lp(kt(e.result))};else if(t==="batch")return{type:"batch",result:qy(kt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Jy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Gi(e.is_autocommit)};else throw new ze("Unexpected type of StreamResponse")}function VF(e){let t=Ur(e.baton),r=Ur(e.base_url);return{baton:t,baseUrl:r}}var yT=b(()=>{Et();xl();Ky()});var WF,The,$he,Ohe,Che,zhe,Phe,GF;var bT=b(()=>{Vy();WF={default(){return{baton:void 0,baseUrl:void 0,results:[]}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()},3(e,t){t.results.push(e.message(The))}},The={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message($he)}},2(e){return{type:"error",error:e.message(on)}}},$he={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(Ohe)},3(e){return e.message(Che)},4(e){return{type:"sequence"}},5(e){return e.message(zhe)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(Phe)}},Ohe={default(){return{type:"execute",result:ts.default()}},1(e,t){t.result=e.message(ts)}},Che={default(){return{type:"batch",result:Rl.default()}},1(e,t){t.result=e.message(Rl)}},zhe={default(){return{type:"describe",result:Tl.default()}},1(e,t){t.result=e.message(Tl)}},Phe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},GF={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var ST;var QF=b(()=>{xl();tT();Et();nn();yT();bT();Ky();Vy();ST=class ST extends zp{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new gT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new ze("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(VF,GF);if(t===void 0)throw new ze("Empty response to cursor request");return t}next(){return this.#a(Fy,Hy)}close(){this._setClosed(new Ge("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new _t("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return fa(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Qi(n,t)}else throw Ke(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new ze("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function YF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,Nhe)}function Nhe(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Np);else if(t.type==="batch")e.object("batch",t.batch,Il);else if(t.type==="sequence"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit");else throw Ke(t,"Impossible type of StreamRequest")}function XF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,Il)}var vT=b(()=>{pT();nn()});function e3(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,Dhe)}function Dhe(e,t){if(t.type==="close")e.message(1,t,Lhe);else if(t.type==="execute")e.message(2,t,Zhe);else if(t.type==="batch")e.message(3,t,jhe);else if(t.type==="sequence")e.message(4,t,Bhe);else if(t.type==="describe")e.message(5,t,Uhe);else if(t.type==="store_sql")e.message(6,t,Mhe);else if(t.type==="close_sql")e.message(7,t,qhe);else if(t.type==="get_autocommit")e.message(8,t,Fhe);else throw Ke(t,"Impossible type of StreamRequest")}function Lhe(e,t){}function Zhe(e,t){e.message(1,t.stmt,Dp)}function jhe(e,t){e.message(1,t.batch,kl)}function Bhe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Uhe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Mhe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function qhe(e,t){e.int32(1,t.sqlId)}function Fhe(e,t){}function t3(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,kl)}var wT=b(()=>{mT();nn()});function Jhe(e,t){if(t.results.length!==e.length)throw new ze("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new ze("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(Uo(o.error));else if(o.type==="none")throw new ze("Received unrecognized type of StreamResult");else throw Ke(o,"Received impossible type of StreamResult")}}async function Khe(e,t){if(t==="json"){let r=await e.json();return fa(r,HF)}if(t==="protobuf"){let r=await e.arrayBuffer();return Qi(new Uint8Array(r),WF)}throw await e.body?.cancel(),Ke(t,"Impossible encoding")}async function Hhe(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return Uo(o);return new pa(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new pa(r,e.status)}return await e.body?.cancel(),new pa(r,e.status)}var Qy;var xT=b(()=>{Et();nT();oT();KF();$p();El();My();nn();QF();vT();wT();vT();wT();yT();bT();Qy=class Qy extends Al{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#p;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new Xi,this.#s=!1,this.#l=!1,this.#d=!1,this.#p=void 0,this.#m=new Yi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#f({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new ga(this,t)}_closeSql(e){if(this.#p!==void 0)return;this.#f({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#f({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#f({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#f(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,ya(()=>this.#u())}close(){this._setClosed(new Ge("Stream was manually closed"))}closeGracefully(){this.#l=!0,ya(()=>this.#u())}get closed(){return this.#p!==void 0||this.#l}_setClosed(e){if(this.#p!==void 0)return;if(this.#p=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,ya(()=>this.#u())}#g(e){if(this.#p!==void 0)throw new _t("Stream is closed",this.#p);else if(this.#l)throw new _t("Stream is closing",void 0);else this.#a.push(e),ya(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new Ge("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Ke(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>Khe(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Jhe(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new ST(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),l=this.#n;s=l(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Hhe(a).then((l)=>{throw l});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,YF,e3)}#v(e,t){if(t.cursorPath===void 0)throw new xn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,XF,t3)}#w(e,t,r,o,n){let i,s;if(r==="json")i=Ip(t,o),s="application/json";else if(r==="protobuf")i=Tp(t,n),s="application/x-protobuf";else throw Ke(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function Whe(e,t){let r=e;for(let o of Vhe){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return _T}var Vhe,_T,Yy;var ET=b(()=>{Et();xT();Vhe=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],_T={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};Yy=class Yy extends Sl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=Whe(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(_T),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=_T.version)return;else if(this._endpoint===void 0)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the HTTP server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this._endpoint.version<e)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new _t("Client is closed",this.#o);let e=new Qy(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new Ge("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new _t("Client was closed",e))}}});var r3=b(()=>{Et()});function AT(e,t,r=2){if(typeof Wi>"u")throw new Ep("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(hT.keys());else o=Array.from(JF.keys());let n=new Wi(e,o);return new Wy(n,t)}function IT(e,t,r,o,n=2){return new Yy(e instanceof URL?e:new URL(e),t,r,o,n)}var Xy=b(()=>{eT();Gy();Et();ET();Gy();eT();cT();r3();El();By();My();ET();xT();Gy();uT();Et()});class Zp{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Mo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Hi(this.#e)),l=s;o=r.map((u)=>{let d=i.step().condition(ut.ok(l));if(this.#t>=3)d.condition(ut.not(ut.isAutocommit(i)));let p=d.query(u);return p.catch(()=>{return}),l=d,p}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let l=i.step();if(s!==void 0)l.condition(ut.ok(s));if(this.#t>=3)l.condition(ut.not(ut.isAutocommit(i)));let u=l.query(a);return u.catch(()=>{return}),s=l,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Wt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push(Ol(s))}catch(s){if(s instanceof Wt)throw s;let a=st(s);if(a instanceof Ce)throw new Wt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Hi(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function $l(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Hi(e)),a=i,l=o.map((h)=>{let S=r.step().condition(ut.ok(a));if(t>=3)S.condition(ut.not(ut.isAutocommit(r)));let y=S.query(h);return a=S,y}),u=r.step().condition(ut.ok(a));if(t>=3)u.condition(ut.not(ut.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(ut.not(ut.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<l.length;h++)try{let S=await l[h];if(S===void 0)throw new Wt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push(Ol(S))}catch(S){if(S instanceof Wt)throw S;let y=st(S);if(y instanceof Ce)throw new Wt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function Mo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new Cp(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function Ol(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new hl(t,r,o,n,i)}function st(e){if(e instanceof Ge){let t=n3(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function n3(e){if(e instanceof _p&&e.code!==void 0)return e.code;else if(e instanceof ze)return"HRANA_PROTO_ERROR";else if(e instanceof _t)return e.cause instanceof Ge?n3(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof vl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof pa)return"SERVER_ERROR";else if(e instanceof xn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var RT=b(()=>{Xy();wn();gl()});class Cl{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new o3,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class o3{#e;constructor(){this.#e=new Map}get(e){let t=this.#e.get(e);if(t!==void 0)this.#e.delete(e),this.#e.set(e,t);return t}set(e,t){this.#e.set(e,t)}peekLru(){for(let e of this.#e.entries())return e;return}delete(e){this.#e.delete(e)}get size(){return this.#e.size}}var TT=ye(function(CUe,s3){function Ghe(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var l=r.shift();if(a.queue=r.length,l)s(l.fn).then(l.resolve).catch(l.reject)}function i(l){return new Promise(function(u,d){r.push({fn:l,resolve:u,reject:d}),a.queue=r.length})}function s(l){t++;try{return Promise.resolve(l()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(l){if(t>=e)return i(l);else return s(l)};return a}function Qhe(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function i3(e){return e.queue=0,e.map=Qhe,e}s3.exports=function(e){if(e)return i3(Ghe(e));else return i3(function(t){return t()})}});function l3(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${ro}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=bp(e.scheme,e.authority,e.path),r;try{r=AT(t,e.authToken)}catch(o){if(o instanceof Ep){let n=e.scheme==="wss"?"https":"http",i=bp(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${ro}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new u3(r,t,e.authToken,e.intMode,e.concurrency)}class u3{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=c3.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=Mo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return Ol(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(Mo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await $l(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Mo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await $l("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new d3(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Yhe&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=a3}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=AT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Cl(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=a3;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var c3,Yhe=60000,a3=100,d3;var p3=b(()=>{Xy();wn();wp();RT();Ty();gl();c3=Vl(TT(),1);wn();d3=class d3 extends Zp{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function m3(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${ro}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=bp(e.scheme,e.authority,e.path);return new g3(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class g3{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=IT(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=f3.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=Mo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return Ol(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Mo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new Cl(s,h3).apply(o);let u=s.batch(!1);i=$l(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Mo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=$l("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new y3(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=IT(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var f3,h3=30,y3;var b3=b(()=>{Xy();wn();wp();RT();Ty();gl();f3=Vl(TT(),1);wn();y3=class y3 extends Zp{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Cl(e,h3)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function zl(e){return Xhe(vp(e,!0))}function Xhe(e){if(e.scheme==="wss"||e.scheme==="ws")return l3(e);else if(e.scheme==="https"||e.scheme==="http")return m3(e);else return fF(e)}var $T=b(()=>{wp();bF();p3();b3();wn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var $e=b(()=>{F=Symbol.for("drizzle:entityKind")});var He;var En=b(()=>{$e();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var jp;var eb=b(()=>{$e();jp=class jp{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var Pl=b(()=>{ir=Symbol.for("drizzle:Name")});var OT,S3;var v3=b(()=>{$e();Pl();OT=class OT{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new S3(e,this)}};S3=class S3{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function tb(e,...t){return e(...t)}var CT=()=>{};function zT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var w3,ege,x3;var _3=b(()=>{$e();Pl();w3=class w3{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new x3(e,this.columns,this.nullsNotDistinctConfig,this.name)}};ege=class ege{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new w3(e,this.name)}};x3=class x3{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??zT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function E3(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function A3(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[l,u]=E3(e,o+1,!0);r.push(l),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[l,u]=A3(e,o+1);r.push(l),o=u;continue}let[s,a]=E3(e,o,!1);r.push(s),o=a}return[r,o]}function I3(e){let[t]=A3(e,1);return t}function PT(e){return`{${e.map((t)=>{if(Array.isArray(t))return PT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var k3=()=>{};var Bp,Nl,R3,tge,T3,NT;var $3=b(()=>{eb();En();$e();v3();CT();_3();k3();Bp=class Bp extends jp{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new T3(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>tb((n,i)=>{let s=new OT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new R3(e,this.config)}};Nl=class Nl extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=zT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};R3=class R3 extends Nl{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};tge=class tge{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};T3=class T3 extends Bp{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new NT(e,this.config,t)}};NT=class NT extends Nl{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=I3(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,NT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return PT(r)}}});function z3(e){return!!e&&typeof e==="function"&&O3 in e&&e[O3]===!0}var rge,C3,O3,nge,P3;var N3=b(()=>{$e();$3();rge=class rge extends Bp{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new C3(e,this.config)}};C3=class C3 extends Nl{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};O3=Symbol.for("drizzle:isPgEnum");nge=class nge extends Bp{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new P3(e,this.config)}};P3=class P3 extends Nl{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var dt,Up;var An=b(()=>{$e();dt=class dt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};Up=class Up extends dt{static[F]="WithSubquery"}});var D3="0.45.2";var L3=()=>{};var DT,LT,Z3;var j3=b(()=>{CT();L3();Z3={startActiveSpan(e,t){if(!DT)return t();if(!LT)LT=DT.trace.getTracer("drizzle-orm",D3);return tb((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),DT,LT)}}});var pt;var qo=b(()=>{pt=Symbol.for("drizzle:ViewBaseConfig")});function rs(e){return e[ir]}function ba(e){return`${e[rb]??"public"}.${e[ir]}`}var rb,nb,B3,ZT,jT,Mp,U3,oge,ge;var sr=b(()=>{$e();Pl();rb=Symbol.for("drizzle:Schema"),nb=Symbol.for("drizzle:Columns"),B3=Symbol.for("drizzle:ExtraConfigColumns"),ZT=Symbol.for("drizzle:OriginalName"),jT=Symbol.for("drizzle:BaseName"),Mp=Symbol.for("drizzle:IsAlias"),U3=Symbol.for("drizzle:ExtraConfigBuilder"),oge=Symbol.for("drizzle:IsDrizzleTable");ge=class ge{static[F]="Table";static Symbol={Name:ir,Schema:rb,OriginalName:ZT,Columns:nb,ExtraConfigColumns:B3,BaseName:jT,IsAlias:Mp,ExtraConfigBuilder:U3};[ir];[ZT];[rb];[nb];[B3];[jT];[Mp]=!1;[oge]=!0;[U3]=void 0;constructor(e,t,r){this[ir]=this[ZT]=e,this[rb]=t,this[jT]=r}}});function BT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function sge(e){let t={sql:"",params:[]};for(let r of e)if(t.sql+=r.sql,t.params.push(...r.params),r.typings?.length){if(!t.typings)t.typings=[];t.typings.push(...r.typings)}return t}function M3(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Nt(e[0]));for(let[o,n]of t.entries())r.push(n,new Nt(e[o+1]));return new Ee(r)}function qp(e,t){return e.map((r)=>{if(oe(r,ns)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Mr)&&oe(r.value,ns)){if(!(r.value.name in t))throw Error(`No value for placeholder "${r.value.name}" was provided`);return r.encoder.mapToDriverValue(t[r.value.name])}return r})}var ige,Nt,Ee,ob,q3,F3,qMe,Mr,ns,age,sn;var Qt=b(()=>{$e();N3();An();j3();qo();En();sr();ige=class ige{static[F]="FakePrimitiveParam"};Nt=class Nt{static[F]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Ee([this])}};Ee=class Ee{constructor(e){this.queryChunks=e;for(let t of e)if(oe(t,ge)){let r=t[ge.Symbol.Schema];this.usedTables.push(r===void 0?t[ge.Symbol.Name]:r+"."+t[ge.Symbol.Name])}}static[F]="SQL";decoder=q3;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return Z3.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:l}=r;return sge(e.map((u)=>{if(oe(u,Nt))return{sql:u.value.join(""),params:[]};if(oe(u,ob))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new Nt("(")];for(let[p,m]of u.entries())if(d.push(m),p<u.length-1)d.push(new Nt(", "));return d.push(new Nt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,Ee))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,ge)){let d=u[ge.Symbol.Schema],p=u[ge.Symbol.Name];return{sql:d===void 0||u[Mp]?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let p=u.table[ge.Symbol.Schema];return{sql:u.table[Mp]||p===void 0?n(u.table[ge.Symbol.Name])+"."+n(d):n(p)+"."+n(u.table[ge.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,sn)){let d=u[pt].schema,p=u[pt].name;return{sql:d===void 0||u[pt].isAlias?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Mr)){if(oe(u.value,ns))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,Ee))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let p=["none"];if(s)p=[s(u.encoder)];return{sql:i(l.value++,d),params:[d],typings:p}}if(oe(u,ns))return{sql:i(l.value++,u),params:[u],typings:["none"]};if(oe(u,Ee.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,dt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new Nt("("),u._.sql,new Nt(") "),new ob(u._.alias)],r)}if(z3(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(BT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new Nt("("),u.getSQL(),new Nt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new Ee.Aliased(this,e)}mapWith(e){return this.decoder=typeof e==="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}};ob=class ob{constructor(e){this.value=e}static[F]="Name";brand;getSQL(){return new Ee([this])}};q3={mapFromDriverValue:(e)=>e},F3={mapToDriverValue:(e)=>e},qMe={...q3,...F3};Mr=class Mr{constructor(e,t=F3){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new Ee([this])}};((e)=>{function t(){return new Ee([])}e.empty=t;function r(l){return new Ee(l)}e.fromList=r;function o(l){return new Ee([new Nt(l)])}e.raw=o;function n(l,u){let d=[];for(let[p,m]of l.entries()){if(p>0&&u!==void 0)d.push(u);d.push(m)}return new Ee(d)}e.join=n;function i(l){return new ob(l)}e.identifier=i;function s(l){return new ns(l)}e.placeholder=s;function a(l,u){return new Mr(l,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Ee||(Ee={}));ns=class ns{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new Ee([this])}};age=Symbol.for("drizzle:IsDrizzleView");sn=class sn{static[F]="View";[pt];[age]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[pt]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new Ee([this])}};He.prototype.getSQL=function(){return new Ee([this])};ge.prototype.getSQL=function(){return new Ee([this])};dt.prototype.getSQL=function(){return new Ee([this])}});function UT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},l)=>{let u;if(oe(a,He))u=a;else if(oe(a,Ee))u=a.decoder;else if(oe(a,dt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[p,m]of s.entries())if(p<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[l],S=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=S===null?rs(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==rs(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function an(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,Ee)||oe(n,Ee.Aliased)||oe(n,dt))r.push({path:i,field:n});else if(oe(n,ge))r.push(...an(n[ge.Symbol.Columns],i));else r.push(...an(n,i));return r},[])}function Fp(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function ib(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,Ee)||oe(n,He))return[o,n];else return[o,new Mr(n,e[ge.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function J3(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function sb(e){return e[ge.Symbol.Columns]}function Jp(e){return oe(e,dt)?e._.alias:oe(e,sn)?e[pt].name:oe(e,Ee)?void 0:e[ge.Symbol.IsAlias]?e[ge.Symbol.Name]:e[ge.Symbol.BaseName]}function so(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function K3(e){if(typeof e!=="object"||e===null)return!1;if(e.constructor.name!=="Object")return!1;if("logger"in e){let t=typeof e.logger;if(t!=="boolean"&&(t!=="object"||typeof e.logger.logQuery!=="function")&&t!=="undefined")return!1;return!0}if("schema"in e){let t=typeof e.schema;if(t!=="object"&&t!=="undefined")return!1;return!0}if("casing"in e){let t=typeof e.casing;if(t!=="string"&&t!=="undefined")return!1;return!0}if("mode"in e){if(e.mode!=="default"||e.mode!=="planetscale"||e.mode!==void 0)return!1;return!0}if("connection"in e){let t=typeof e.connection;if(t!=="string"&&t!=="object"&&t!=="undefined")return!1;return!0}if("client"in e){let t=typeof e.client;if(t!=="object"&&t!=="function"&&t!=="undefined")return!1;return!0}if(Object.keys(e).length===0)return!0;return!1}var MT;var Sr=b(()=>{En();$e();Qt();An();sr();qo();MT=typeof TextDecoder>"u"?null:new TextDecoder});var H3,qT,FT;var ab=b(()=>{$e();H3=class H3{static[F]="ConsoleLogWriter";write(e){console.log(e)}};qT=class qT{static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new H3}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};FT=class FT{static[F]="NoopLogger";logQuery(){}}});var V3,W3,JT;var G3=b(()=>{$e();sr();V3=Symbol.for("drizzle:PgInlineForeignKeys"),W3=Symbol.for("drizzle:EnableRLS");JT=class JT extends ge{static[F]="PgTable";static Symbol=Object.assign({},ge.Symbol,{InlineForeignKeys:V3,EnableRLS:W3});[V3]=[];[W3]=!1;[ge.Symbol.ExtraConfigBuilder]=void 0;[ge.Symbol.ExtraConfigColumns]={}}});var KT,Q3;var Y3=b(()=>{$e();G3();KT=class KT{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new Q3(e,this.columns,this.name)}};Q3=class Q3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[JT.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function $r(e,t){if(M3(t)&&!BT(e)&&!oe(e,Mr)&&!oe(e,ns)&&!oe(e,He)&&!oe(e,ge)&&!oe(e,sn))return new Mr(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" and ")),new Nt(")")])}function cn(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" or ")),new Nt(")")])}function e5(e){return C`not ${e}`}function is(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>$r(r,e))}`}return C`${e} in ${$r(t,e)}`}function cb(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>$r(r,e))}`}return C`${e} not in ${$r(t,e)}`}function qr(e){return C`${e} is null`}function n5(e){return C`${e} is not null`}function lb(e){return C`exists ${e}`}function ss(e){return C`not exists ${e}`}function o5(e,t,r){return C`${e} between ${$r(t,e)} and ${$r(r,e)}`}function i5(e,t,r){return C`${e} not between ${$r(t,e)} and ${$r(r,e)}`}function s5(e,t){return C`${e} like ${t}`}function a5(e,t){return C`${e} not like ${t}`}function c5(e,t){return C`${e} ilike ${t}`}function l5(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${$r(t,e)}`,X3=(e,t)=>C`${e} <> ${$r(t,e)}`,In=(e,t)=>C`${e} > ${$r(t,e)}`,t5=(e,t)=>C`${e} >= ${$r(t,e)}`,r5=(e,t)=>C`${e} < ${$r(t,e)}`,os=(e,t)=>C`${e} <= ${$r(t,e)}`;var u5=b(()=>{En();$e();sr();Qt()});function Fo(e){return C`${e} asc`}function Sa(e){return C`${e} desc`}var d5=b(()=>{Qt()});var HT=b(()=>{u5();d5()});function f5(){return{and:tt,between:o5,eq:je,exists:lb,gt:In,gte:t5,ilike:c5,inArray:is,isNull:qr,isNotNull:n5,like:s5,lt:r5,lte:os,ne:X3,not:e5,notBetween:i5,notExists:ss,notLike:a5,notIlike:l5,notInArray:cb,or:cn,sql:C}}function m5(){return{sql:C,asc:Fo,desc:Sa}}function h5(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,ge))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,ge)){let a=ba(s),l=o[a];r[a]=i,n[i]={tsName:i,dbName:s[ge.Symbol.Name],schema:s[ge.Symbol.Schema],columns:s[ge.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let d of Object.values(s[ge.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[ge.Symbol.ExtraConfigBuilder]?.(s[ge.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,KT))n[i].primaryKey.push(...d.columns)}}else if(oe(s,p5)){let a=ba(s.table),l=r[a],u=s.config(t(s.table)),d;for(let[p,m]of Object.entries(u))if(l){let h=n[l];if(h.relations[p]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[p]=m}}return{tables:n,tableNamesMap:r}}function cge(e){return function(r,o){return new as(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function lge(e){return function(r,o){return new Kp(e,r,o)}}function g5(e,t,r){if(oe(r,as)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ba(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[ge.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ba(i)];if(!s)throw Error(`Table "${i[ge.Symbol.Name]}" not found in schema`);let a=[];for(let l of Object.values(n.relations))if(r.relationName&&r!==l&&l.relationName===r.relationName||!r.relationName&&l.referencedTable===r.sourceTable)a.push(l);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[ge.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],as)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function y5(e){return{one:cge(e),many:lge(e)}}function ub(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let l=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(l,as)?d&&ub(e,e[a.relationTableTsKey],d,a.selection,n):d.map((p)=>ub(e,e[a.relationTableTsKey],p,a.selection,n))}else{let l=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,Ee))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=l===null?null:d.mapFromDriverValue(l)}return i}var VT,p5,as,Kp;var Hp=b(()=>{sr();En();$e();Y3();HT();Qt();VT=class VT{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[ge.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};p5=class p5{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};as=class as extends VT{constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new as(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Kp=class Kp extends VT{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new Kp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function Vp(e,t){return new Proxy(e,new va(t,!1))}function ao(e,t){return new Proxy(e,new Dl(new Proxy(e.table,new va(t,!1))))}function WT(e,t){return new Ee.Aliased(Wp(e.sql,t),e.fieldAlias)}function Wp(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return ao(r,t);if(oe(r,Ee))return Wp(r,t);if(oe(r,Ee.Aliased))return WT(r,t);return r}))}var Dl,va,uge;var Gp=b(()=>{En();$e();Qt();sr();qo();Dl=class Dl{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};va=class va{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===ge.Symbol.IsAlias)return!0;if(t===ge.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===ge.Symbol.OriginalName)return this.alias;if(t===pt)return{...e[pt],name:this.alias,isAlias:!0};if(t===ge.Symbol.Columns){let o=e[ge.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new Dl(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new Dl(new Proxy(e,this)));return r}};uge=class uge{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return Vp(e.sourceTable,this.alias);return e[t]}}});var at;var wa=b(()=>{Gp();En();$e();Qt();An();qo();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===pt)return{...e[pt],selectedFields:new Proxy(e[pt].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,dt)?e._.selectedFields:oe(e,sn)?e[pt].selectedFields:e)[t];if(oe(o,Ee.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,Ee)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new Dl(new Proxy(o.table,new va(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var vr;var Jo=b(()=>{$e();vr=class vr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var GT,b5;var QT=b(()=>{$e();Pl();GT=class GT{static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new b5(e,this)}};b5=class b5{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function YT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var S5,dge,v5;var XT=b(()=>{$e();Pl();S5=class S5{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new v5(e,this.columns,this.name)}};dge=class dge{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new S5(e,this.name)}};v5=class v5{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??YT(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Bt,yt;var cs=b(()=>{eb();En();$e();QT();XT();Bt=class Bt extends jp{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new GT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};yt=class yt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=YT(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function k5(e,t){let{name:r,config:o}=so(e,t);if(o?.mode==="json")return new _5(r);if(o?.mode==="bigint")return new w5(r);return new A5(r)}var w5,x5,_5,E5,A5,I5;var e$=b(()=>{$e();Sr();cs();w5=class w5 extends Bt{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new x5(e,this.config)}};x5=class x5 extends yt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(MT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};_5=class _5 extends Bt{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new E5(e,this.config)}};E5=class E5 extends yt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(MT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};A5=class A5 extends Bt{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new I5(e,this.config)}};I5=class I5 extends yt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function $5(e){return(t,r)=>{let{name:o,config:n}=so(t,r);return new R5(o,n,e)}}var R5,T5;var t$=b(()=>{$e();Sr();cs();R5=class R5 extends Bt{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new T5(e,this.config)}};T5=class T5 extends yt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=so(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new z5(r,o.mode);if(o?.mode==="boolean")return new N5(r,o.mode);return new O5(r)}var db,pb,O5,C5,z5,P5,N5,D5;var r$=b(()=>{$e();Qt();Sr();cs();db=class db extends Bt{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};pb=class pb extends yt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};O5=class O5 extends db{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new C5(e,this.config)}};C5=class C5 extends pb{static[F]="SQLiteInteger"};z5=class z5 extends db{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new P5(e,this.config)}};P5=class P5 extends pb{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};N5=class N5 extends db{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new D5(e,this.config)}};D5=class D5 extends pb{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function q5(e,t){let{name:r,config:o}=so(e,t),n=o?.mode;return n==="number"?new j5(r):n==="bigint"?new U5(r):new L5(r)}var L5,Z5,j5,B5,U5,M5;var n$=b(()=>{$e();Sr();cs();L5=class L5 extends Bt{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new Z5(e,this.config)}};Z5=class Z5 extends yt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};j5=class j5 extends Bt{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new B5(e,this.config)}};B5=class B5 extends yt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};U5=class U5 extends Bt{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new M5(e,this.config)}};M5=class M5 extends yt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function K5(e){return new F5(e??"")}var F5,J5;var o$=b(()=>{$e();cs();F5=class F5 extends Bt{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new J5(e,this.config)}};J5=class J5 extends yt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function ft(e,t={}){let{name:r,config:o}=so(e,t);if(o.mode==="json")return new W5(r);return new H5(r,o)}var H5,V5,W5,G5;var i$=b(()=>{$e();Sr();cs();H5=class H5 extends Bt{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new V5(e,this.config)}};V5=class V5 extends yt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};W5=class W5 extends Bt{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new G5(e,this.config)}};G5=class G5 extends yt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function Q5(){return{blob:k5,customType:$5,integer:ar,numeric:q5,real:K5,text:ft}}var Y5=b(()=>{e$();t$();r$();n$();o$();i$()});function pge(e,t,r,o,n=e){let i=new Rt(e,o,n),s=typeof t==="function"?t(Q5()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let p=d;p.setName(u);let m=p.build(i);return i[s$].push(...p.buildForeignKeys(m,i)),[u,m]})),l=Object.assign(i,a);if(l[ge.Symbol.Columns]=a,l[ge.Symbol.ExtraConfigColumns]=a,r)l[Rt.Symbol.ExtraConfigBuilder]=r;return l}var s$,Rt,Qp=(e,t,r)=>pge(e,t,r);var Ko=b(()=>{$e();sr();Y5();s$=Symbol.for("drizzle:SQLiteInlineForeignKeys");Rt=class Rt extends ge{static[F]="SQLiteTable";static Symbol=Object.assign({},ge.Symbol,{InlineForeignKeys:s$});[ge.Symbol.Columns];[s$]=[];[ge.Symbol.ExtraConfigBuilder]=void 0}});var fge,X5;var e8=b(()=>{$e();fge=class fge{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new X5(e,this)}};X5=class X5{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function Ho(e){return new t8(e,!1)}var t8,r8,n8;var o8=b(()=>{$e();t8=class t8{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new r8(this.name,e,this.unique)}};r8=class r8{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new n8(this.config,e)}};n8=class n8{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var mge,i8;var s8=b(()=>{$e();Ko();mge=class mge{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new i8(e,this.columns,this.name)}};i8=class i8{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[Rt.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function kn(e){if(oe(e,Rt))return[`${e[ge.Symbol.BaseName]}`];if(oe(e,dt))return e._.usedTables??[];if(oe(e,Ee))return e.usedTables??[];return[]}var Ll=b(()=>{$e();Qt();An();sr();Ko()});var fb;var a8=b(()=>{$e();Jo();wa();Ko();sr();Sr();Ll();fb=class fb extends vr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[ge.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[Rt.Symbol.Columns]){return this.config.returning=an(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:kn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}});function hge(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function gge(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function yge(e){return e}var a$;var c8=b(()=>{$e();sr();a$=class a${static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?hge:e==="camelCase"?gge:yge}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[ge.Symbol.Schema]??"public",r=e.table[ge.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[ge.Symbol.Schema]??"public",r=e[ge.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[ge.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Zl,Vo,c$;var mb=b(()=>{$e();Zl=class Zl extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Vo=class Vo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
445
|
+
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`),g}function j(){Le.asyncTransitions--}function T(g){if(U===null)try{var E=("require"+Math.random()).slice(0,7);U=(ky&&ky[E]).call(ky,"timers").setImmediate}catch(D){U=function(J){f===!1&&(f=!0,typeof MessageChannel>"u"&&console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var M=new MessageChannel;M.port1.onmessage=J,M.port2.postMessage(void 0)}}return U(g)}function Z(g){return 1<g.length&&typeof AggregateError==="function"?AggregateError(g):g[0]}function A(g,E){E!==ne-1&&console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),ne=E}function R(g,E,D){var J=Le.actQueue;if(J!==null)if(J.length!==0)try{I(J),T(function(){return R(g,E,D)});return}catch(M){Le.thrownErrors.push(M)}else Le.actQueue=null;0<Le.thrownErrors.length?(J=Z(Le.thrownErrors),Le.thrownErrors.length=0,D(J)):E(g)}function I(g){if(!X){X=!0;var E=0;try{for(;E<g.length;E++){var D=g[E];do{Le.didUsePromise=!1;var J=D(!1);if(J!==null){if(Le.didUsePromise){g[E]=D,g.splice(0,E);return}D=J}else break}while(1)}g.length=0}catch(M){g.splice(0,E+1),Le.thrownErrors.push(M)}finally{X=!1}}}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart==="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var q=Symbol.for("react.transitional.element"),N=Symbol.for("react.portal"),H=Symbol.for("react.fragment"),G=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),ae=Symbol.for("react.consumer"),me=Symbol.for("react.context"),Se=Symbol.for("react.forward_ref"),xe=Symbol.for("react.suspense"),ke=Symbol.for("react.suspense_list"),Ie=Symbol.for("react.memo"),_e=Symbol.for("react.lazy"),Ue=Symbol.for("react.activity"),De=Symbol.iterator,Qe={},bt={isMounted:function(){return!1},enqueueForceUpdate:function(g){r(g,"forceUpdate")},enqueueReplaceState:function(g){r(g,"replaceState")},enqueueSetState:function(g){r(g,"setState")}},Tt=Object.assign,Dt={};Object.freeze(Dt),o.prototype.isReactComponent={},o.prototype.setState=function(g,E){if(typeof g!=="object"&&typeof g!=="function"&&g!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,g,E,"setState")},o.prototype.forceUpdate=function(g){this.updater.enqueueForceUpdate(this,g,"forceUpdate")};var lt={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]};for(V in lt)lt.hasOwnProperty(V)&&e(V,lt[V]);n.prototype=o.prototype,lt=i.prototype=new n,lt.constructor=i,Tt(lt,o.prototype),lt.isPureReactComponent=!0;var Or=Array.isArray,$n=Symbol.for("react.client.reference"),Le={H:null,A:null,T:null,S:null,actQueue:null,asyncTransitions:0,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1,didUsePromise:!1,thrownErrors:[],getCurrentStack:null,recentlyCreatedOwnerStacks:0},uo=Object.prototype.hasOwnProperty,ls=console.createTask?console.createTask:function(){return null};lt={react_stack_bottom_frame:function(g){return g()}};var us,Ea,ds={},On=lt.react_stack_bottom_frame.bind(lt,m)(),Kl=ls(d(m)),Qo=!1,Aa=/\/+/g,Ia=typeof reportError==="function"?reportError:function(g){if(typeof window==="object"&&typeof window.ErrorEvent==="function"){var E=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof g==="object"&&g!==null&&typeof g.message==="string"?String(g.message):String(g),error:g});if(!window.dispatchEvent(E))return}else if(typeof process==="object"&&typeof process.emit==="function"){process.emit("uncaughtException",g);return}console.error(g)},f=!1,U=null,ne=0,ie=!1,X=!1,w=typeof queueMicrotask==="function"?function(g){queueMicrotask(function(){return queueMicrotask(g)})}:T;lt=Object.freeze({__proto__:null,c:function(g){return ee().useMemoCache(g)}});var V={map:z,forEach:function(g,E,D){z(g,function(){E.apply(this,arguments)},D)},count:function(g){var E=0;return z(g,function(){E++}),E},toArray:function(g){return z(g,function(E){return E})||[]},only:function(g){if(!k(g))throw Error("React.Children.only expected to receive a single React element child.");return g}};Upe.Activity=Ue,Upe.Children=V,Upe.Component=o,Upe.Fragment=H,Upe.Profiler=re,Upe.PureComponent=i,Upe.StrictMode=G,Upe.Suspense=xe,Upe.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Le,Upe.__COMPILER_RUNTIME=lt,Upe.act=function(g){var E=Le.actQueue,D=ne;ne++;var J=Le.actQueue=E!==null?E:[],M=!1;try{var te=g()}catch(fe){Le.thrownErrors.push(fe)}if(0<Le.thrownErrors.length)throw A(E,D),g=Z(Le.thrownErrors),Le.thrownErrors.length=0,g;if(te!==null&&typeof te==="object"&&typeof te.then==="function"){var se=te;return w(function(){M||ie||(ie=!0,console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),{then:function(fe,Te){M=!0,se.then(function(Pe){if(A(E,D),D===0){try{I(J),T(function(){return R(Pe,fe,Te)})}catch(ps){Le.thrownErrors.push(ps)}if(0<Le.thrownErrors.length){var Cn=Z(Le.thrownErrors);Le.thrownErrors.length=0,Te(Cn)}}else fe(Pe)},function(Pe){A(E,D),0<Le.thrownErrors.length?(Pe=Z(Le.thrownErrors),Le.thrownErrors.length=0,Te(Pe)):Te(Pe)})}}}var be=te;if(A(E,D),D===0&&(I(J),J.length!==0&&w(function(){M||ie||(ie=!0,console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"))}),Le.actQueue=null),0<Le.thrownErrors.length)throw g=Z(Le.thrownErrors),Le.thrownErrors.length=0,g;return{then:function(fe,Te){M=!0,D===0?(Le.actQueue=J,T(function(){return R(be,fe,Te)})):fe(be)}}},Upe.cache=function(g){return function(){return g.apply(null,arguments)}},Upe.cacheSignal=function(){return null},Upe.captureOwnerStack=function(){var g=Le.getCurrentStack;return g===null?null:g()},Upe.cloneElement=function(g,E,D){if(g===null||g===void 0)throw Error("The argument must be a React element, but you passed "+g+".");var J=Tt({},g.props),M=g.key,te=g._owner;if(E!=null){var se;e:{if(uo.call(E,"ref")&&(se=Object.getOwnPropertyDescriptor(E,"ref").get)&&se.isReactWarning){se=!1;break e}se=E.ref!==void 0}se&&(te=p()),h(E)&&(l(E.key),M=""+E.key);for(be in E)!uo.call(E,be)||be==="key"||be==="__self"||be==="__source"||be==="ref"&&E.ref===void 0||(J[be]=E[be])}var be=arguments.length-2;if(be===1)J.children=D;else if(1<be){se=Array(be);for(var fe=0;fe<be;fe++)se[fe]=arguments[fe+2];J.children=se}J=v(g.type,M,J,te,g._debugStack,g._debugTask);for(M=2;M<arguments.length;M++)_(arguments[M]);return J},Upe.createContext=function(g){return g={$$typeof:me,_currentValue:g,_currentValue2:g,_threadCount:0,Provider:null,Consumer:null},g.Provider=g,g.Consumer={$$typeof:ae,_context:g},g._currentRenderer=null,g._currentRenderer2=null,g},Upe.createElement=function(g,E,D){for(var J=2;J<arguments.length;J++)_(arguments[J]);J={};var M=null;if(E!=null)for(fe in Ea||!("__self"in E)||"key"in E||(Ea=!0,console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")),h(E)&&(l(E.key),M=""+E.key),E)uo.call(E,fe)&&fe!=="key"&&fe!=="__self"&&fe!=="__source"&&(J[fe]=E[fe]);var te=arguments.length-2;if(te===1)J.children=D;else if(1<te){for(var se=Array(te),be=0;be<te;be++)se[be]=arguments[be+2];Object.freeze&&Object.freeze(se),J.children=se}if(g&&g.defaultProps)for(fe in te=g.defaultProps,te)J[fe]===void 0&&(J[fe]=te[fe]);M&&S(J,typeof g==="function"?g.displayName||g.name||"Unknown":g);var fe=1e4>Le.recentlyCreatedOwnerStacks++;return v(g,M,J,p(),fe?Error("react-stack-top-frame"):On,fe?ls(d(g)):Kl)},Upe.createRef=function(){var g={current:null};return Object.seal(g),g},Upe.forwardRef=function(g){g!=null&&g.$$typeof===Ie?console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof g!=="function"?console.error("forwardRef requires a render function but was given %s.",g===null?"null":typeof g):g.length!==0&&g.length!==2&&console.error("forwardRef render functions accept exactly two parameters: props and ref. %s",g.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),g!=null&&g.defaultProps!=null&&console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");var E={$$typeof:Se,render:g},D;return Object.defineProperty(E,"displayName",{enumerable:!1,configurable:!0,get:function(){return D},set:function(J){D=J,g.name||g.displayName||(Object.defineProperty(g,"name",{value:J}),g.displayName=J)}}),E},Upe.isValidElement=k,Upe.lazy=function(g){g={_status:-1,_result:g};var E={$$typeof:_e,_payload:g,_init:W},D={name:"lazy",start:-1,end:-1,value:null,owner:null,debugStack:Error("react-stack-top-frame"),debugTask:console.createTask?console.createTask("lazy()"):null};return g._ioInfo=D,E._debugInfo=[{awaited:D}],E},Upe.memo=function(g,E){g==null&&console.error("memo: The first argument must be a component. Instead received: %s",g===null?"null":typeof g),E={$$typeof:Ie,type:g,compare:E===void 0?null:E};var D;return Object.defineProperty(E,"displayName",{enumerable:!1,configurable:!0,get:function(){return D},set:function(J){D=J,g.name||g.displayName||(Object.defineProperty(g,"name",{value:J}),g.displayName=J)}}),E},Upe.startTransition=function(g){var E=Le.T,D={};D._updatedFibers=new Set,Le.T=D;try{var J=g(),M=Le.S;M!==null&&M(D,J),typeof J==="object"&&J!==null&&typeof J.then==="function"&&(Le.asyncTransitions++,J.then(j,j),J.then(s,Ia))}catch(te){Ia(te)}finally{E===null&&D._updatedFibers&&(g=D._updatedFibers.size,D._updatedFibers.clear(),10<g&&console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")),E!==null&&D.types!==null&&(E.types!==null&&E.types!==D.types&&console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."),E.types=D.types),Le.T=E}},Upe.unstable_useCacheRefresh=function(){return ee().useCacheRefresh()},Upe.use=function(g){return ee().use(g)},Upe.useActionState=function(g,E,D){return ee().useActionState(g,E,D)},Upe.useCallback=function(g,E){return ee().useCallback(g,E)},Upe.useContext=function(g){var E=ee();return g.$$typeof===ae&&console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"),E.useContext(g)},Upe.useDebugValue=function(g,E){return ee().useDebugValue(g,E)},Upe.useDeferredValue=function(g,E){return ee().useDeferredValue(g,E)},Upe.useEffect=function(g,E){return g==null&&console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useEffect(g,E)},Upe.useEffectEvent=function(g){return ee().useEffectEvent(g)},Upe.useId=function(){return ee().useId()},Upe.useImperativeHandle=function(g,E,D){return ee().useImperativeHandle(g,E,D)},Upe.useInsertionEffect=function(g,E){return g==null&&console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useInsertionEffect(g,E)},Upe.useLayoutEffect=function(g,E){return g==null&&console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useLayoutEffect(g,E)},Upe.useMemo=function(g,E){return ee().useMemo(g,E)},Upe.useOptimistic=function(g,E){return ee().useOptimistic(g,E)},Upe.useReducer=function(g,E,D){return ee().useReducer(g,E,D)},Upe.useRef=function(g){return ee().useRef(g)},Upe.useState=function(g){return ee().useState(g)},Upe.useSyncExternalStore=function(g,E,D){return ee().useSyncExternalStore(g,E,D)},Upe.useTransition=function(){return ee().useTransition()},Upe.version="19.2.7",typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop==="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()});var D6,L6;var qR=b(()=>{D6=Vl(MR(),1),L6=D6.createContext(void 0)});var Mpe;var Z6=b(()=>{jR();N6();qR();ue();Mpe=Vl(MR(),1)});var qpe,Fpe;var j6=b(()=>{wt();ue();DR();qpe=il.omit({url:!0,analyticsScript:!0}),Fpe=qpe.extend({title:c.string().optional().describe("Optional site title override"),description:c.string().optional().describe("Optional site description override")})});function FR(e,t={}){let r=B6(e),o=B6(t.sharedDomain??"rizom.ai").replace(/^\./,""),n=`.${o}`;if(r.endsWith(n)){let i=r.slice(0,-n.length);if(i.length>0&&!i.includes("."))return`${i}-preview.${o}`}return`preview.${r}`}function B6(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}var U6=b(()=>{vg()});var Hpe,Vpe;var M6=b(()=>{ue();yy();BR();Hpe=c.string(),Vpe=c.custom((e)=>Ws(e)&&e6.safeParse(e).success)});var Wpe;var q6=b(()=>{vg();ue();Wpe=c.object({title:c.string().min(1),slug:c.string().min(1),description:c.string(),content:c.string(),author:c.string(),publishedAt:c.iso.datetime({offset:!0}),category:c.string().min(1).optional()})});var F6=b(()=>{NR();p6();DR();k6();BR();Z6();j6();U6();M6();qR();q6()});function J6(e,t={}){return FR(e,t)}var K6=b(()=>{F6()});var Y6={};Lt(Y6,{assertPilotUsersRemoved:()=>Q6,createPilotOffboardDriver:()=>V6,offboardPilotUsers:()=>efe});import{readdir as Gpe,readFile as Qpe,rm as fp,writeFile as Ype}from"fs/promises";import{basename as Xpe,join as Do}from"path";async function efe(e,t){let r=[...new Set(t.handles.map((p)=>br.parse(p)))].sort((p,m)=>p.localeCompare(m));if(r.length===0)throw Error("At least one pilot handle is required");let o=t.dryRun??!0,n=`sunset:${r.join(",")}`;if(!o&&t.confirmation!==n)throw Error(`Exact confirmation required: ${n}`);let i=t.env??process.env,s=t.logger??console.info,a=await xt(e),l=r.map((p)=>tfe(a,p,i)),u=t.driver??V6({env:i,fetchImpl:t.fetchImpl,contentRepoTokenName:a.pilot.contentRepoAdminToken}),d=await Promise.all(l.map(async(p)=>({target:p,inspection:await u.inspect(p)})));if(nfe(d),ofe(d,o,s),!o){for(let p of d)if(!p.inspection.contentRepoArchived)await u.archiveContentRepo(p.target),s(`[${p.target.handle}] archived ${p.target.contentRepo}`);for(let p of d)for(let m of p.inspection.dnsRecords)await u.deleteDnsRecord(p.target,m),s(`[${p.target.handle}] deleted DNS ${m.name}`);for(let p of d)if(p.inspection.server)await u.deleteServer(p.target,p.inspection.server),s(`[${p.target.handle}] deleted ${p.target.instanceName}`);await rfe(l,u,t.sleep??((p)=>new Promise((m)=>setTimeout(m,p)))),await ife(e,r),await Pi(e),await Q6(e,r),s(`Removed desired state for ${r.length} pilot user(s)`)}return{dryRun:o,handles:r,confirmation:n,plans:d}}function tfe(e,t,r){let o=e.users.find((d)=>d.handle===t),n=`${t}${e.pilot.domainSuffix}`,i=o?.domain??n,s=J6(i,{sharedDomain:e.pilot.domainSuffix}),a=o?.cloudflareZoneId??Ry(r,"CF_ZONE_ID"),l=o?.contentRepo??`${e.pilot.contentRepoPrefix}${t}-content`,u=l.includes("/")?l:`${e.pilot.githubOrg}/${l}`;return{handle:t,instanceName:`rover-${t}`,domain:i,previewDomain:s,...i===n?{}:{wwwDomain:`www.${i}`},contentRepo:u,cloudflareZoneId:a}}async function rfe(e,t,r){for(let o of e)for(let n=1;n<=20;n+=1){let i=await t.inspect(o);if(!i.server&&i.dnsRecords.length===0&&i.contentRepoArchived)break;if(n===20)throw Error(`[${o.handle}] provider cleanup did not converge`);await r(1500)}}function nfe(e){for(let{target:t,inspection:r}of e){if(r.server&&r.server.name!==t.instanceName)throw Error(`[${t.handle}] unexpected server name: ${r.server.name}`);let o=new Set([t.domain,t.previewDomain,...t.wwwDomain?[t.wwwDomain]:[]]);for(let n of r.dnsRecords){if(!o.has(n.name))throw Error(`[${t.handle}] refusing unexpected DNS record ${n.name}`);if(n.type==="A"&&r.server?.ip&&n.content!==r.server.ip)throw Error(`[${t.handle}] ${n.name} does not point to the retiring server`)}}}function ofe(e,t,r){r(`${t?"Dry run":"Apply"}: ${e.map(({target:o})=>o.handle).join(", ")}`);for(let{target:o,inspection:n}of e){let i=n.server?`delete ${o.instanceName}`:"already absent",s=n.dnsRecords.length>0?n.dnsRecords.map((l)=>`${l.type} ${l.name}`).join(", "):"already absent",a=n.contentRepoArchived?"already archived":`archive ${o.contentRepo}`;r(`[${o.handle}] server: ${i}; DNS: ${s}; repo: ${a}`)}r("Runtime backups: none")}async function ife(e,t){let r=new Set(t),o=Do(e,"cohorts");for(let n of(await Gpe(o)).filter((i)=>i.endsWith(".yaml"))){let i=Do(o,n),s=await Qpe(i,"utf8"),a=tn(s);if(a.errors.length>0)throw Error(`${n}: ${a.errors[0]?.message??"invalid YAML"}`);let l=a.get("members",!0);if(!kR(l))throw Error(`${n}: members must be a sequence`);let u=l.items.filter((d)=>!Po(d)||typeof d.value!=="string"||!r.has(d.value));if(u.length===l.items.length)continue;if(u.length===0){await fp(i);continue}l.items=u,hn.parse(a.toJS()),await Ype(i,a.toString())}for(let n of t)await Promise.all([fp(Do(e,"users",`${n}.yaml`),{force:!0}),fp(Do(e,"users",`${n}.secrets.yaml`),{force:!0}),fp(Do(e,"users",`${n}.secrets.yaml.age`),{force:!0}),fp(Do(e,"users",n),{recursive:!0,force:!0})])}function V6(e){let t=e.fetchImpl??fetch,r=Ry(e.env,"HCLOUD_TOKEN"),o=Ry(e.env,"CF_API_TOKEN"),n=Ry(e.env,e.contentRepoTokenName);return{async inspect(i){let[s,a,l]=await Promise.all([sfe(t,r,i.instanceName),Promise.all([i.domain,i.previewDomain,...i.wwwDomain?[i.wwwDomain]:[]].map((u)=>afe(t,o,i.cloudflareZoneId,u))).then((u)=>u.flat()),cfe(t,n,i.contentRepo)]);if(s.length>1)throw Error(`[${i.handle}] expected at most one server, found ${s.length}`);return{...s[0]?{server:s[0]}:{},dnsRecords:a,contentRepoArchived:l.archived}},async archiveContentRepo(i){await al(t,`https://api.github.com/repos/${i.contentRepo}`,{method:"PATCH",headers:W6(n),body:JSON.stringify({archived:!0})},"GitHub repository archive")},async deleteDnsRecord(i,s){if(cl(await al(t,`https://api.cloudflare.com/client/v4/zones/${i.cloudflareZoneId}/dns_records/${s.id}`,{method:"DELETE",headers:G6(o)},"Cloudflare DNS delete")).success!==!0)throw Error(`Cloudflare DNS delete failed for ${s.name}`)},async deleteServer(i,s){await al(t,`https://api.hetzner.cloud/v1/servers/${s.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}},"Hetzner server delete",!0)}}}async function sfe(e,t,r){let o=new URL("https://api.hetzner.cloud/v1/servers");o.searchParams.set("label_selector",`brain=${r}`);let i=cl(await al(e,o.toString(),{headers:{Authorization:`Bearer ${t}`}},"Hetzner server lookup")).servers;if(!Array.isArray(i))throw Error("Hetzner server lookup returned an invalid payload");return i.map((s)=>{let a=cl(s),l=H6(a.public_net),u=H6(l?.ipv4);return{id:lfe(a.id,"Hetzner server id"),name:mp(a.name,"Hetzner server name"),...typeof u?.ip==="string"?{ip:u.ip}:{}}})}async function afe(e,t,r,o){let n=new URL(`https://api.cloudflare.com/client/v4/zones/${r}/dns_records`);n.searchParams.set("name",o);let i=cl(await al(e,n.toString(),{headers:G6(t)},"Cloudflare DNS lookup")),s=i.result;if(i.success!==!0||!Array.isArray(s))throw Error(`Cloudflare DNS lookup failed for ${o}`);return s.map((a)=>{let l=cl(a),u=mp(l.type,"Cloudflare record type");if(u!=="A"&&u!=="CNAME")throw Error(`Unsupported Cloudflare record type ${u} for ${o}`);return{id:mp(l.id,"Cloudflare record id"),name:mp(l.name,"Cloudflare record name"),type:u,content:mp(l.content,"Cloudflare record content")}})}async function cfe(e,t,r){let o=cl(await al(e,`https://api.github.com/repos/${r}`,{headers:W6(t)},"GitHub repository lookup"));if(typeof o.archived!=="boolean")throw Error(`Invalid repository archive state for ${r}`);return{archived:o.archived}}async function al(e,t,r,o,n=!1){let i=await e(t,r),s=await i.text();if(!i.ok)throw Error(`${o} failed (${i.status}): ${s}`);if(!s&&n)return{};try{return JSON.parse(s)}catch{throw Error(`${o} returned an invalid JSON response`)}}function W6(e){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"}}function G6(e){return{Authorization:`Bearer ${e}`}}function Ry(e,t){let r=e[t];if(!r)throw Error(`Missing required environment variable: ${t}`);return r}function cl(e){if(!Ws(e))throw Error("Provider returned an unexpected payload");return e}function H6(e){return Ws(e)?e:void 0}function mp(e,t){if(typeof e!=="string"||e.length===0)throw Error(`Missing ${t}`);return e}function lfe(e,t){if(typeof e!=="number")throw Error(`Missing ${t}`);return e}async function Q6(e,t){for(let r of t)for(let o of[Do(e,"users",`${r}.yaml`),Do(e,"users",`${r}.secrets.yaml.age`),Do(e,"users",r)])if(await Ir(o))throw Error(`Offboarded user state remains: ${Xpe(o)}`)}var X6=b(()=>{rl();gn();K6();Pd();$o();Xs()});var e4="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as t4}from"crypto";function dfe(e){if(e<0)throw RangeError("Wrong ID size");try{if(!Ji||Ji.length<e)Ji=Buffer.allocUnsafe(e*ufe),t4.getRandomValues(Ji),ll=0;else if(ll+e>Ji.length)t4.getRandomValues(Ji),ll=0}catch(t){throw Ji=void 0,t}ll+=e}function r4(e=21){dfe(e|=0);let t="";for(let r=ll-e;r<ll;r++)t+=e4[Ji[r]&63];return t}var ufe=128,Ji,ll;var n4=()=>{};function Lo(e=12){return r4(e)}var hp=b(()=>{n4()});import{openSync as pfe,writeSync as ffe}from"fs";function mfe(e){return ul?`[${ul}] ${e}`:e}class Rr{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??ca.INFO,this.context=e.context??void 0,this.useStderr=e.useStderr??!1,this.format=e.format??"text",this.logFile=e.logFile,t!==void 0)this.fileHandle=t;else if(this.logFile)try{this.fileHandle=pfe(this.logFile,"a")}catch{}}static getInstance(e){if(!Rr.instance)Rr.instance=new Rr(e);else{if(e?.useStderr!==void 0)Rr.instance.useStderr=e.useStderr;if(e?.level!==void 0)Rr.instance.level=e.level}return Rr.instance}static resetInstance(){Rr.instance=null,ul=void 0}static setProcessRole(e){ul=e}static createFresh(e){return new Rr(e)}formatEntry(e,t,r){if(this.format==="json")return this.formatJsonEntry(e,t,r);return mfe([`[${new Date().toISOString()}]`,...this.context?[`[${this.context}]`]:[],t].join(" "))}write(e,t,r,o){if(this.format==="json")e(this.formatEntry(t,r,o));else if(o.length>0)e(this.formatEntry(t,r,[]),...o);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,o);try{ffe(this.fileHandle,n+`
|
|
446
|
+
`)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,...ul&&{role:ul},msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}debugStream(){return this.useStderr?console.error.bind(console):console.debug.bind(console)}silly(e,...t){if(this.level<=ca.SILLY)this.write(this.debugStream(),"silly",e,t)}verbose(e,...t){if(this.level<=ca.VERBOSE)this.write(this.debugStream(),"verbose",e,t)}debug(e,...t){if(this.level<=ca.DEBUG)this.write(this.debugStream(),"debug",e,t)}info(e,...t){if(this.level<=ca.INFO){let r=this.useStderr?console.error.bind(console):console.info.bind(console);this.write(r,"info",e,t)}}warn(e,...t){if(this.level<=ca.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=ca.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new Rr({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var ca,ul,nZe;var JR=b(()=>{ca={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};nZe=Rr.getInstance()});var KR,hfe,dl,aZe;var gp=b(()=>{wt();ue();KR=c.enum(["file_operations","content_operations","data_processing","batch_processing"]),hfe=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:KR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Wn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:To.optional()}),dl=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:KR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Wn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:To.optional(),rootJobId:c.string()}),aZe=c.enum(["none","skip","replace","coalesce"])});var gfe,Ki=15000;var yp=b(()=>{gp();ue();gfe=c.object({id:c.string(),type:c.string(),data:c.string(),status:c.enum(["pending","processing","completed","failed"]),source:c.string().nullable(),priority:c.number(),retryCount:c.number(),maxRetries:c.number(),lastError:c.string().nullable(),lastErrorPublic:c.unknown(),createdAt:c.number(),scheduledFor:c.number(),startedAt:c.number().nullable(),completedAt:c.number().nullable(),attemptId:c.string().nullable(),workerSlotId:c.string().nullable(),workerSessionId:c.string().nullable(),leaseExpiresAt:c.number().nullable(),attemptHeartbeatAt:c.number().nullable(),runtimeUpdatedAt:c.number().nullable(),metadata:dl,progress:c.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:c.unknown().nullable().optional()})});var HR,o4,Oe,yfe,bfe,i4,s4,a4;var Zo=b(()=>{wt();ue();gp();HR=c.enum(["pending","processing","completed","failed"]),o4=c.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},yfe=c.object({id:c.string(),type:c.string(),status:HR,data:c.unknown(),result:c.unknown().optional(),lastError:c.string().optional().nullable(),attempts:c.number(),maxRetries:c.number(),priority:c.number(),createdAt:c.date(),updatedAt:c.date(),processedAt:c.date().optional().nullable(),completedAt:c.date().optional().nullable(),failedAt:c.date().optional().nullable()}),bfe=c.object({jobId:c.string(),type:c.string(),status:o4,result:c.unknown().optional(),error:c.string().optional()}),i4=c.object({success:c.literal(!1),error:c.string().optional()}),s4=c.object({id:c.string(),type:c.enum(["job","batch"]),status:HR,message:c.string().optional(),progress:c.object({current:c.number(),total:c.number(),percentage:c.number()}).optional(),aggregationKey:c.string().optional(),batchDetails:c.object({totalOperations:c.number(),completedOperations:c.number(),failedOperations:c.number(),currentOperation:c.string().optional(),errors:c.array(c.string()).optional()}).optional(),jobDetails:c.object({jobType:c.string(),priority:c.number(),retryCount:c.number()}).optional(),metadata:dl}),a4=Gn(LI.progress,s4)});var Ce,Wt;var wn=b(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Wt=class Wt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function c4(e){let t=Sfe.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?vfe(r.authority):void 0,i=la(r.path),s=r.query!==void 0?xfe(r.query):void 0,a=r.fragment!==void 0?la(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function vfe(e){let t=wfe.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=la(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:la(r.username),password:r.password!==void 0?la(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function xfe(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:la(n.replaceAll("+"," ")),value:la(i.replaceAll("+"," "))})}return{pairs:r}}function la(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function bp(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=_fe(t.host),i=Efe(t.port),a=`//${Afe(t.userinfo)}${n}${i}`,l=r.split("/").map(encodeURIComponent).join("/");if(l!==""&&!l.startsWith("/"))l="/"+l;return new URL(`${o}${a}${l}`)}function _fe(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function Efe(e){return e!==void 0?`:${e}`:""}function Afe(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var Sfe,wfe;var Ty=b(()=>{wn();Sfe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();wfe=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var fl,l4,u4,Sp,$y,Ife,Gt,d4,m4=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),h4=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),g4=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=Sp[t>>18&63]+Sp[t>>12&63]+Sp[t>>6&63]+Sp[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},GR,VR,Oy=(e,t=!1)=>t?m4(VR(e)):VR(e),kfe=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Gt(192|t>>>6)+Gt(128|t&63):Gt(224|t>>>12&15)+Gt(128|t>>>6&63)+Gt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Gt(240|t>>>18&7)+Gt(128|t>>>12&63)+Gt(128|t>>>6&63)+Gt(128|t&63)}},Rfe,y4=(e)=>e.replace(Rfe,kfe),p4,pl=(e,t=!1)=>t?m4(p4(e)):p4(e),f4=(e)=>pl(e,!0),Tfe,$fe=(e)=>{switch(e.length){case 4:var t=(7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3),r=t-65536;return Gt((r>>>10)+55296)+Gt((r&1023)+56320);case 3:return Gt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Gt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},b4=(e)=>e.replace(Tfe,$fe),S4=(e)=>{if(e=e.replace(/\s+/g,""),!Ife.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=$y[e.charAt(i++)]<<18|$y[e.charAt(i++)]<<12|(r=$y[e.charAt(i++)])<<6|(o=$y[e.charAt(i++)]),r===64)n.push(Gt(t>>16&255));else if(o===64)n.push(Gt(t>>16&255,t>>8&255));else n.push(Gt(t>>16&255,t>>8&255,t&255));return n.join("")},QR,v4,w4=(e)=>v4(x4(e)),Ofe,x4=(e)=>h4(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),WR=(e)=>Ofe(x4(e)),Cfe=(e)=>{if(typeof e!=="string")return!1;let t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},_4=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),E4=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,_4(r));e("fromBase64",function(){return WR(this)}),e("toBase64",function(t){return pl(this,t)}),e("toBase64URI",function(){return pl(this,!0)}),e("toBase64URL",function(){return pl(this,!0)}),e("toUint8Array",function(){return w4(this)})},A4=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,_4(r));e("toBase64",function(t){return Oy(this,t)}),e("toBase64URI",function(){return Oy(this,!0)}),e("toBase64URL",function(){return Oy(this,!0)})},zfe=()=>{E4(),A4()},ml;var Cy=b(()=>{fl=typeof Buffer==="function",l4=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,u4=typeof TextEncoder==="function"?new TextEncoder:void 0,Sp=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),$y=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(Sp),Ife=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Gt=String.fromCharCode.bind(String),d4=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),GR=typeof btoa==="function"?(e)=>btoa(e):fl?(e)=>Buffer.from(e,"binary").toString("base64"):g4,VR=fl?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Gt.apply(null,e.subarray(o,o+4096)));return GR(r.join(""))},Rfe=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,p4=fl?(e)=>Buffer.from(e,"utf8").toString("base64"):u4?(e)=>VR(u4.encode(e)):(e)=>GR(y4(e)),Tfe=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,QR=typeof atob==="function"?(e)=>atob(h4(e)):fl?(e)=>Buffer.from(e,"base64").toString("binary"):S4,v4=fl?(e)=>d4(Buffer.from(e,"base64")):(e)=>d4(QR(e).split("").map((t)=>t.charCodeAt(0))),Ofe=fl?(e)=>Buffer.from(e,"base64").toString("utf8"):l4?(e)=>l4.decode(v4(e)):(e)=>b4(QR(e)),ml={version:"3.8.0",VERSION:"3.8.0",atob:QR,atobPolyfill:S4,btoa:GR,btoaPolyfill:g4,fromBase64:WR,toBase64:pl,encode:pl,encodeURI:f4,encodeURL:f4,utob:y4,btou:b4,decode:WR,isValid:Cfe,fromUint8Array:Oy,toUint8Array:w4,extendString:E4,extendUint8Array:A4,extendBuiltins:zfe}});function Hi(e){if(e==="write")return"BEGIN IMMEDIATE";else if(e==="read")return"BEGIN TRANSACTION READONLY";else if(e==="deferred")return"BEGIN DEFERRED";else throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}class hl{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(Pfe),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function Pfe(e){return Array.prototype.map.call(e,Nfe)}function Nfe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return ml.fromUint8Array(new Uint8Array(e));else return e}var ro="https://github.com/libsql/libsql-client-ts#supported-urls";var gl=b(()=>{Cy()});function k4(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function vp(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===I4)r="file::memory:";let l=c4(r),u=l.scheme.toLowerCase(),d=u==="file"&&l.path===I4&&l.authority===void 0,p;if(d)p={cache:{values:["shared","private"],update:(y,v)=>a.push(`${y}=${v}`)}};else p={tls:{values:["0","1"],update:(y,v)=>n=v==="1"},authToken:{update:(y,v)=>o=v}};for(let{key:y,value:v}of l.query?.pairs??[]){if(!Object.hasOwn(p,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=p[y];if(x.values!==void 0&&!x.values.includes(v))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(v)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,v)}let m=a.length===0?"":`?${a.join("&")}`,h=l.path+m,S;if(u==="libsql")if(n===!1){if(l.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");S=t?"http":"ws"}else S=t?"https":"wss";else S=u;if(S==="http"||S==="ws")n??=!1;else n??=!0;if(S!=="http"&&S!=="ws"&&S!=="https"&&S!=="wss"&&S!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(l.scheme+":")}. For more information, please read ${ro}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(l.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+l.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:S,tls:n,authority:l.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var I4=":memory:";var wp=b(()=>{wn();Ty();gl()});var T4=ye(function(rn){var Dfe=rn&&rn.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),Lfe=rn&&rn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),R4=rn&&rn.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null){for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))Dfe(t,e,r)}return Lfe(t,e),t};Object.defineProperty(rn,"__esModule",{value:!0});rn.load=rn.currentTarget=void 0;var Zfe=R4(Fr("path")),jfe=R4(Fr("fs"));function Bfe(){let e=null;switch(process.platform){case"android":switch(process.arch){case"arm":return"android-arm-eabi";case"arm64":return"android-arm64"}e="Android";break;case"win32":switch(process.arch){case"x64":return"win32-x64-msvc";case"arm64":return"win32-arm64-msvc";case"ia32":return"win32-ia32-msvc"}e="Windows";break;case"darwin":switch(process.arch){case"x64":return"darwin-x64";case"arm64":return"darwin-arm64"}e="macOS";break;case"linux":switch(process.arch){case"x64":case"arm64":return Ufe()?`linux-${process.arch}-gnu`:`linux-${process.arch}-musl`;case"arm":return"linux-arm-gnueabihf"}e="Linux";break;case"freebsd":if(process.arch==="x64")return"freebsd-x64";e="FreeBSD";break}if(e)throw Error(`Neon: unsupported ${e} architecture: ${process.arch}`);throw Error(`Neon: unsupported system: ${process.platform}`)}rn.currentTarget=Bfe;function Ufe(){let e=process.report?.getReport();if(typeof e!=="object"||!e||!("header"in e))return!1;let t=e.header;return typeof t==="object"&&!!t&&"glibcVersionRuntime"in t}function Mfe(e){let t=Zfe.join(e,"index.node");return jfe.existsSync(t)?Fr(t):null}rn.load=Mfe});var C4=ye(function(RZe,O4){var $4=()=>process.platform==="linux",YR=null,qfe=()=>{if(!YR)YR=$4()&&process.report?process.report.getReport():{};return YR};O4.exports={isLinux:$4,getReport:qfe}});var N4=ye(function(TZe,P4){var z4=Fr("fs"),Ffe=(e)=>z4.readFileSync(e,"utf-8"),Jfe=(e)=>new Promise((t,r)=>{z4.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});P4.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:Ffe,readFile:Jfe}});var Y4=ye(function($Ze,Q4){var L4=Fr("child_process"),{isLinux:yl,getReport:Z4}=C4(),{LDD_PATH:zy,readFile:j4,readFileSync:B4}=N4(),no,oo,Vi="",U4=()=>{if(!Vi)return new Promise((e)=>{L4.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Vi=t?" ":r,e(Vi)})});return Vi},M4=()=>{if(!Vi)try{Vi=L4.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Vi=" "}return Vi},jo="glibc",q4=/GLIBC\s(\d+\.\d+)/,ua="musl",Kfe=jo.toUpperCase(),Hfe=ua.toLowerCase(),Vfe=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),F4=()=>{let e=Z4();if(e.header&&e.header.glibcVersionRuntime)return jo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Vfe))return ua}return null},J4=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(jo))return jo;if(r&&r.includes(ua))return ua;return null},K4=(e)=>{if(e.includes(Hfe))return ua;if(e.includes(Kfe))return jo;return null},Wfe=async()=>{if(no!==void 0)return no;no=null;try{let e=await j4(zy);no=K4(e)}catch(e){}return no},Gfe=()=>{if(no!==void 0)return no;no=null;try{let e=B4(zy);no=K4(e)}catch(e){}return no},H4=async()=>{let e=null;if(yl()){if(e=await Wfe(),!e)e=F4();if(!e){let t=await U4();e=J4(t)}}return e},V4=()=>{let e=null;if(yl()){if(e=Gfe(),!e)e=F4();if(!e){let t=M4();e=J4(t)}}return e},Qfe=async()=>yl()&&await H4()!==jo,Yfe=()=>yl()&&V4()!==jo,Xfe=async()=>{if(oo!==void 0)return oo;oo=null;try{let t=(await j4(zy)).match(q4);if(t)oo=t[1]}catch(e){}return oo},eme=()=>{if(oo!==void 0)return oo;oo=null;try{let t=B4(zy).match(q4);if(t)oo=t[1]}catch(e){}return oo},W4=()=>{let e=Z4();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},D4=(e)=>e.trim().split(/\s+/)[1],G4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(jo))return D4(t);if(r&&o&&r.includes(ua))return D4(o);return null},tme=async()=>{let e=null;if(yl()){if(e=await Xfe(),!e)e=W4();if(!e){let t=await U4();e=G4(t)}}return e},rme=()=>{let e=null;if(yl()){if(e=eme(),!e)e=W4();if(!e){let t=M4();e=G4(t)}}return e};Q4.exports={GLIBC:jo,MUSL:ua,family:H4,familySync:V4,isNonGlibcLinux:Qfe,isNonGlibcLinuxSync:Yfe,version:tme,versionSync:rme}});var eF=ye(function(OZe,X4){var nme={ALLOW:0,DENY:1};X4.exports=nme});var rF=ye(function(CZe,tF){var XR={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function da(e,t,r){if(new.target!==da)return new da(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),XR.value=""+e,Object.defineProperty(this,"message",XR),Error.captureStackTrace(this,da),this.code=t,this.rawCode=r}Object.setPrototypeOf(da,Error);Object.setPrototypeOf(da.prototype,Error.prototype);Object.defineProperty(da.prototype,"name",XR);tF.exports=da});var uF=ye(function(zZe,Py){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:ome,currentTarget:ime}=T4(),{familySync:nF,GLIBC:sme,MUSL:ame}=Y4();function cme(){if(process.env.LIBSQL_JS_DEV)return ome(__dirname);let e=ime();if(nF()==sme)switch(e){case"linux-x64-musl":e="linux-x64-gnu";break;case"linux-arm64-musl":e="linux-arm64-gnu";break}if(e==="linux-arm-gnueabihf"&&nF()==ame)e="linux-arm-musleabihf";return Fr(`@libsql/${e}`)}var{databaseOpen:lme,databaseOpenWithSync:ume,databaseInTransaction:dme,databaseInterrupt:pme,databaseClose:fme,databaseSyncSync:mme,databaseSyncUntilSync:hme,databaseExecSync:gme,databasePrepareSync:yme,databaseDefaultSafeIntegers:bme,databaseAuthorizer:Sme,databaseLoadExtension:vme,databaseMaxWriteReplicationIndex:wme,statementRaw:xme,statementIsReader:_me,statementGet:oF,statementRun:iF,statementInterrupt:Eme,statementRowsSync:sF,statementColumns:Ame,statementSafeIntegers:Ime,rowsNext:kme}=cme(),Rme=eF(),aF=rF();function bl(e){if(e.libsqlError)return new aF(e.message,e.code,e.rawCode);return e}class cF{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,l=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=ume(e,t.syncUrl,o,r,i,s,a,l,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,l=t?.remoteEncryptionKey??"";this.db=lme(e,i,r,s,a,l)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return dme(n)}}})}sync(){return mme.call(this.db)}syncUntil(e){return hme.call(this.db,e)}prepare(e){try{let t=yme.call(this.db,e);return new lF(t)}catch(t){throw bl(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){Sme.call(this.db,e)}loadExtension(...e){vme.call(this.db,...e)}maxWriteReplicationIndex(){return wme.call(this.db)}exec(e){try{gme.call(this.db,e)}catch(t){throw bl(t)}}interrupt(){pme.call(this.db)}close(){fme.call(this.db),this.open=!1}defaultSafeIntegers(e){return bme.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class lF{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return xme.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return _me.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return iF.call(this.stmt,e[0]);else return iF.call(this.stmt,e.flat())}catch(t){throw bl(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return oF.call(this.stmt,e[0]);else return oF.call(this.stmt,e.flat())}catch(t){throw bl(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=sF.call(this.stmt,e[0]);else t=sF.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)kme.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw bl(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw bl(t)}}interrupt(){Eme.call(this.stmt)}columns(){return Ame.call(this.stmt)}safeIntegers(e){return Ime.call(this.stmt,e??!0),this}}Py.exports=cF;Py.exports.Authorization=Rme;Py.exports.SqliteError=aF});import{Buffer as pF}from"buffer";function fF(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${ro}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${ro}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=k4(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new xp.default(o,n);return Pt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new mF(o,n,i,e.intMode)}class mF{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),Pt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{Pt(r,Hi(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Wt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(Pt(r,s,this.#n))}catch(i){if(i instanceof Wt)throw i;if(i instanceof Ce)throw new Wt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return Pt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)Pt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{Pt(t,"PRAGMA foreign_keys=off",this.#n),Pt(t,Hi("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Wt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(Pt(t,e[o],this.#n))}catch(n){if(n instanceof Wt)throw n;if(n instanceof Ce)throw new Wt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Pt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Pt(t,"ROLLBACK",this.#n);Pt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return Pt(t,Hi(e),this.#n),this.#r=null,new hF(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return gF(t,e)}finally{if(t.inTransaction)Pt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new xp.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new xp.default(this.#e,this.#t);return this.#r}}class hF{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),Pt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(Pt(this.#e,n,this.#t))}catch(o){if(o instanceof Wt)throw o;if(o instanceof Ce)throw new Wt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),gF(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Pt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Pt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Pt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function Pt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>dF(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=dF(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),l=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>Tme(m,a,r)),d=0,p=void 0;return new hl(a,l,u,0,void 0)}else{let a=i.run(n),l=a.changes,u=BigInt(a.lastInsertRowid);return new hl([],[],[],l,u)}}catch(i){throw yF(i)}}function Tme(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=$me(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function $me(e,t){if(typeof e==="bigint")if(t==="number"){if(e<Ome||e>Cme)throw RangeError("Received integer which cannot be safely represented as a JavaScript number");return Number(e)}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw Error("Invalid value for IntMode");else if(e instanceof pF)return e.buffer;return e}function dF(e,t){if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<zme||e>Pme)throw RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")switch(t){case"bigint":return e?1n:0n;case"string":return e?"1":"0";default:return e?1:0}else if(e instanceof ArrayBuffer)return pF.from(e);else if(e instanceof Date)return e.valueOf();else if(e===void 0)throw TypeError("undefined cannot be passed as argument to the database");else return e}function gF(e,t){try{e.exec(t)}catch(r){throw yF(r)}}function yF(e){if(e instanceof xp.default.SqliteError){let t=e.code,r=Nme(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function Nme(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return Dme[t]??`SQLITE_UNKNOWN_${t.toString()}`}var xp,Ome,Cme=9007199254740991n,zme,Pme=9223372036854775807n,Dme;var bF=b(()=>{wn();wp();gl();xp=Vl(uF(),1);wn();Ome=-9007199254740991n;zme=-9223372036854775808n;Dme={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"}});var Wi;var eT=b(()=>{if(typeof WebSocket<"u")Wi=WebSocket;else if(typeof global<"u")Wi=global.WebSocket;else if(typeof window<"u")Wi=window.WebSocket;else if(typeof self<"u")Wi=self.WebSocket});class Sl{constructor(){this.intMode="number"}intMode}var Ge,ze,_p,_t,Ep,vl,pa,xn,or,io;var Et=b(()=>{Ge=class Ge extends Error{constructor(e){super(e);this.name="ClientError"}};ze=class ze extends Ge{constructor(e){super(e);this.name="ProtoError"}};_p=class _p extends Ge{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};_t=class _t extends Ge{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Ep=class Ep extends Ge{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};vl=class vl extends Ge{constructor(e){super(e);this.name="WebSocketError"}};pa=class pa extends Ge{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};xn=class xn extends Ge{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends Ge{constructor(e){super(e);this.name="InternalError"}};io=class io extends Ge{constructor(e){super(e);this.name="MisuseError"}}});function Tr(e){if(typeof e==="string")return e;throw wl(e,"string")}function Ur(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw wl(e,"string or null")}function Bo(e){if(typeof e==="number")return e;throw wl(e,"number")}function Gi(e){if(typeof e==="boolean")return e;throw wl(e,"boolean")}function Ap(e){if(Array.isArray(e))return e;throw wl(e,"array")}function kt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw wl(e,"object")}function _n(e,t){return Ap(e).map((r)=>t(kt(r)))}function wl(e,t){if(e===void 0)return new ze(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new ze(`Expected ${t}, received ${r}`)}function fa(e,t){return t(kt(e))}var xl=b(()=>{Et()});class SF{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function Ip(e,t){let r=[],o=new SF(r);return o.begin(),t(o,e),o.end(),r.join("")}var ma=0,kp=1,Rp=2,vF=5;class wF{#e;#t;#r;constructor(e){this.#e=e,this.#t=new DataView(e.buffer,e.byteOffset,e.byteLength),this.#r=0}varint(){let e=0;for(let t=0;;t+=7){let r=this.#e[this.#r++];if(e|=(r&127)<<t,!(r&128))break}return e}varintBig(){let e=0n;for(let t=0n;;t+=7n){let r=this.#e[this.#r++];if(e|=BigInt(r&127)<<t,!(r&128))break}return e}bytes(e){let t=new Uint8Array(this.#e.buffer,this.#e.byteOffset+this.#r,e);return this.#r+=e,t}double(){let e=this.#t.getFloat64(this.#r,!0);return this.#r+=8,e}skipVarint(){for(;;)if(!(this.#e[this.#r++]&128))break}skip(e){this.#r+=e}eof(){return this.#r>=this.#e.byteLength}}class xF{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new ze(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(Rp);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Qi(this.bytes(),e)}int32(){return this.#r(ma),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(ma),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(kp),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===ma)this.#e.skipVarint();else if(this.#t===kp)this.#e.skip(8);else if(this.#t===Rp){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===vF)this.#e.skip(4);else throw new ze(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Qi(e,t){let r=new wF(e),o=new xF(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let l=t[s];if(l!==void 0){let u=l(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var tT=b(()=>{Et()});class rT{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,Rp),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new rT;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,ma),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,ma),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,kp),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Tp(e,t){let r=new rT;return t(r,e),r.data()}var _F=()=>{};var nT=b(()=>{xl();tT();_F()});class Yi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var oT=b(()=>{Et()});function Ke(e,t){throw new or(t)}var nn=b(()=>{Et()});function _l(e){if(e===null)return null;else if(typeof e==="string")return e;else if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<Zme||e>jme)throw RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")return e?1n:0n;else if(e instanceof ArrayBuffer)return new Uint8Array(e);else if(e instanceof Uint8Array)return e;else if(e instanceof Date)return+e.valueOf();else if(typeof e==="object")return""+e.toString();else throw TypeError("Unsupported type of value")}function iT(e,t){if(e===null)return null;else if(typeof e==="number")return e;else if(typeof e==="string")return e;else if(typeof e==="bigint")if(t==="number"){let r=Number(e);if(!Number.isSafeInteger(r))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return r}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw new io("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new ze("Received unrecognized type of Value");else throw Ke(e,"Impossible type of Value")}var Zme,jme=9223372036854775807n;var sT=b(()=>{Et();nn();Zme=-9223372036854775808n});function ha(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function Dy(e,t){let r=ha(e),o=e.rows.map((n)=>EF(r.columnNames,n,t));return{...r,rows:o}}function Ly(e,t){let r=ha(e),o;if(e.rows.length>0)o=EF(r.columnNames,e.rows[0],t);return{...r,row:o}}function Zy(e,t){let r=ha(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=iT(e.rows[0][0],t);return{...r,value:o}}function EF(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=iT(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Uo(e){return new _p(e.message,e)}var $p=b(()=>{Et();sT()});class ga{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new io("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new _t("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new Ge("SQL text was manually closed"))}_setClosed(e){if(this.#r===void 0)this.#r=e,this.#e._closeSql(this.#t)}get closed(){return this.#r!==void 0}}function Op(e,t){if(t instanceof ga)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var El=b(()=>{Et()});class Xi{#e;#t;constructor(){this.#e=[],this.#t=[]}get length(){return this.#e.length+this.#t.length}push(e){this.#e.push(e)}shift(){if(this.#t.length===0&&this.#e.length>0)this.#t=this.#e.reverse(),this.#e=[];return this.#t.pop()}first(){return this.#t.length!==0?this.#t[this.#t.length-1]:this.#e[0]}}class Cp{sql;_args;_namedArgs;constructor(e){this.sql=e,this._args=[],this._namedArgs=new Map}bindIndexes(e){this._args.length=0;for(let t of e)this._args.push(_l(t));return this}bindIndex(e,t){if(e!==(e|0)||e<=0)throw RangeError("Index of a positional argument must be positive integer");while(this._args.length<e)this._args.push(null);return this._args[e-1]=_l(t),this}bindName(e,t){return this._namedArgs.set(e,_l(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function jy(e,t,r){let o,n=[],i=[];if(t instanceof Cp){o=t.sql,n=t._args;for(let[l,u]of t._namedArgs.entries())i.push({name:l,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((l)=>_l(l));else i=Object.entries(t[1]).map(([l,u])=>({name:l,value:_l(u)}));else o=t;let{sql:s,sqlId:a}=Op(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var By=b(()=>{El();sT()});class Uy{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new aT(this)}execute(){if(this.#t)throw new io("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return Ume(this._stream,this._steps,e);else return Bme(this._stream,this._steps,e)}}function Bme(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function Ume(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new ze("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new ze("Server produced StepBeginEntry before terminating previous step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new ze("Server produced StepEndEntry but no step is active");let l={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(l,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new ze("Server produced StepErrorEntry for unexpected step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0)}else{if(a.step!==i.step)throw new ze("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new ze("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Uo(a.error);else if(a.type==="none")throw new ze("Server produced unrecognized CursorEntry");else throw Ke(a,"Impossible CursorEntry")}if(i!==void 0)throw new ze("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class aT{_batch;#e;_index;constructor(e){this._batch=e,this.#e=[],this._index=void 0}condition(e){return this.#e.push(e._proto),this}query(e){return this.#t(e,!0,Dy)}queryRow(e){return this.#t(e,!0,Ly)}queryValue(e){return this.#t(e,!0,Zy)}run(e){return this.#t(e,!1,ha)}#t(e,t,r){if(this._index!==void 0)throw new io("This BatchStep has already been added to the batch");let o=jy(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let l=(u,d)=>{if(u!==void 0&&d!==void 0)a(new ze("Server returned both result and error"));else if(d!==void 0)a(Uo(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:l})})}}class ut{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new ut(e._batch,{type:"ok",step:AF(e)})}static error(e){return new ut(e._batch,{type:"error",step:AF(e)})}static not(e){return new ut(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)IF(e,r);return new ut(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)IF(e,r);return new ut(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new ut(e,{type:"is_autocommit"})}}function AF(e){if(e._index===void 0)throw new io("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function IF(e,t){if(t._batch!==e)throw new io("Cannot mix BatchCond objects for different Batch objects")}var cT=b(()=>{Et();$p();By();nn()});function kF(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class Al{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,Dy)}queryRow(e){return this.#e(e,!0,Ly)}queryValue(e){return this.#e(e,!0,Zy)}run(e){return this.#e(e,!1,ha)}#e(e,t,r){let o=jy(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new Uy(this,e)}describe(e){let t=Op(this._sqlOwner(),e);return this._describe(t).then(kF)}sequence(e){let t=Op(this._sqlOwner(),e);return this._sequence(t)}intMode}var My=b(()=>{cT();$p();El();By()});class zp{}var Mme=1000,qme=10,lT;var RF=b(()=>{Et();lT=class lT extends zp{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new Xi,this.#o=new Xi,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new _t("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<qme)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:Mme}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new Ge("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var Pp;var uT=b(()=>{Et();My();RF();Pp=class Pp extends Al{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new Pp(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new Xi,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new _t("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new _t("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new _t("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new Ge("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new lT(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(l)=>n._setClosed(l);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new Ge("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function Np(e,t){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId);e.arrayObjects("args",t.args,TF),e.arrayObjects("named_args",t.namedArgs,Fme),e.boolean("want_rows",t.wantRows)}function Fme(e,t){e.string("name",t.name),e.object("value",t.value,TF)}function Il(e,t){e.arrayObjects("steps",t.steps,Jme)}function Jme(e,t){if(t.condition!==void 0)e.object("condition",t.condition,dT);e.object("stmt",t.stmt,Np)}function dT(e,t){if(e.stringRaw("type",t.type),t.type==="ok"||t.type==="error")e.number("step",t.step);else if(t.type==="not")e.object("cond",t.cond,dT);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,dT);else if(t.type==="is_autocommit");else throw Ke(t,"Impossible type of BatchCond")}function TF(e,t){if(t===null)e.stringRaw("type","null");else if(typeof t==="bigint")e.stringRaw("type","integer"),e.stringRaw("value",""+t);else if(typeof t==="number")e.stringRaw("type","float"),e.number("value",t);else if(typeof t==="string")e.stringRaw("type","text"),e.string("value",t);else if(t instanceof Uint8Array)e.stringRaw("type","blob"),e.stringRaw("base64",ml.fromUint8Array(t));else if(t===void 0);else throw Ke(t,"Impossible type of Value")}var pT=b(()=>{Cy();nn()});function $F(e,t){if(e.stringRaw("type",t.type),t.type==="hello"){if(t.jwt!==void 0)e.string("jwt",t.jwt)}else if(t.type==="request")e.number("request_id",t.requestId),e.object("request",t.request,Kme);else throw Ke(t,"Impossible type of ClientMsg")}function Kme(e,t){if(e.stringRaw("type",t.type),t.type==="open_stream")e.number("stream_id",t.streamId);else if(t.type==="close_stream")e.number("stream_id",t.streamId);else if(t.type==="execute")e.number("stream_id",t.streamId),e.object("stmt",t.stmt,Np);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,Il);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,Il);else if(t.type==="close_cursor")e.number("cursor_id",t.cursorId);else if(t.type==="fetch_cursor")e.number("cursor_id",t.cursorId),e.number("max_count",t.maxCount);else if(t.type==="sequence"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit")e.number("stream_id",t.streamId);else throw Ke(t,"Impossible type of Request")}var OF=b(()=>{pT();nn()});function Dp(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId);for(let r of t.args)e.message(3,r,zF);for(let r of t.namedArgs)e.message(4,r,Hme);e.bool(5,t.wantRows)}function Hme(e,t){e.string(1,t.name),e.message(2,t.value,zF)}function kl(e,t){for(let r of t.steps)e.message(1,r,Vme)}function Vme(e,t){if(t.condition!==void 0)e.message(1,t.condition,fT);e.message(2,t.stmt,Dp)}function fT(e,t){if(t.type==="ok")e.uint32(1,t.step);else if(t.type==="error")e.uint32(2,t.step);else if(t.type==="not")e.message(3,t.cond,fT);else if(t.type==="and")e.message(4,t.conds,CF);else if(t.type==="or")e.message(5,t.conds,CF);else if(t.type==="is_autocommit")e.message(6,void 0,PF);else throw Ke(t,"Impossible type of BatchCond")}function CF(e,t){for(let r of t)e.message(1,r,fT)}function zF(e,t){if(t===null)e.message(1,void 0,PF);else if(typeof t==="bigint")e.sint64(2,t);else if(typeof t==="number")e.double(3,t);else if(typeof t==="string")e.string(4,t);else if(t instanceof Uint8Array)e.bytes(5,t);else if(t===void 0);else throw Ke(t,"Impossible type of Value")}function PF(e,t){}var mT=b(()=>{nn()});function NF(e,t){if(t.type==="hello")e.message(1,t,Wme);else if(t.type==="request")e.message(2,t,Gme);else throw Ke(t,"Impossible type of ClientMsg")}function Wme(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Gme(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Qme);else if(r.type==="close_stream")e.message(3,r,Yme);else if(r.type==="execute")e.message(4,r,Xme);else if(r.type==="batch")e.message(5,r,ehe);else if(r.type==="open_cursor")e.message(6,r,the);else if(r.type==="close_cursor")e.message(7,r,rhe);else if(r.type==="fetch_cursor")e.message(8,r,nhe);else if(r.type==="sequence")e.message(9,r,ohe);else if(r.type==="describe")e.message(10,r,ihe);else if(r.type==="store_sql")e.message(11,r,she);else if(r.type==="close_sql")e.message(12,r,ahe);else if(r.type==="get_autocommit")e.message(13,r,che);else throw Ke(r,"Impossible type of Request")}function Qme(e,t){e.int32(1,t.streamId)}function Yme(e,t){e.int32(1,t.streamId)}function Xme(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Dp)}function ehe(e,t){e.int32(1,t.streamId),e.message(2,t.batch,kl)}function the(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,kl)}function rhe(e,t){e.int32(1,t.cursorId)}function nhe(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function ohe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function ihe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function she(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function ahe(e,t){e.int32(1,t.sqlId)}function che(e,t){e.int32(1,t.streamId)}var DF=b(()=>{mT();nn()});function es(e){let t=Tr(e.message),r=Ur(e.code);return{message:t,code:r}}function Lp(e){let t=_n(e.cols,LF),r=Ap(e.rows).map((s)=>_n(s,ZF)),o=Bo(e.affected_row_count),n=Ur(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function LF(e){let t=Ur(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function qy(e){let t=new Map;Ap(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,Lp(kt(o)))});let r=new Map;return Ap(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,es(kt(o)))}),{stepResults:t,stepErrors:r}}function Fy(e){let t=Tr(e.type);if(t==="step_begin"){let r=Bo(e.step),o=_n(e.cols,LF);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=Bo(e.affected_row_count),o=Ur(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Bo(e.step),o=es(kt(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:_n(e.row,ZF)};else if(t==="error")return{type:"error",error:es(kt(e.error))};else throw new ze("Unexpected type of CursorEntry")}function Jy(e){let t=_n(e.params,lhe),r=_n(e.cols,uhe),o=Gi(e.is_explain),n=Gi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function lhe(e){return{name:Ur(e.name)}}function uhe(e){let t=Tr(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function ZF(e){let t=Tr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Tr(e.value);return BigInt(r)}else if(t==="float")return Bo(e.value);else if(t==="text")return Tr(e.value);else if(t==="blob")return ml.toUint8Array(Tr(e.base64));else throw new ze("Unexpected type of Value")}var Ky=b(()=>{Cy();Et();xl()});function jF(e){let t=Tr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:es(kt(e.error))};else if(t==="response_ok"){let r=Bo(e.request_id),o=dhe(kt(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=Bo(e.request_id),o=es(kt(e.error));return{type:"response_error",requestId:r,error:o}}else throw new ze("Unexpected type of ServerMsg")}function dhe(e){let t=Tr(e.type);if(t==="open_stream")return{type:"open_stream"};else if(t==="close_stream")return{type:"close_stream"};else if(t==="execute")return{type:"execute",result:Lp(kt(e.result))};else if(t==="batch")return{type:"batch",result:qy(kt(e.result))};else if(t==="open_cursor")return{type:"open_cursor"};else if(t==="close_cursor")return{type:"close_cursor"};else if(t==="fetch_cursor"){let r=_n(e.entries,Fy),o=Gi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Jy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Gi(e.is_autocommit)};else throw new ze("Unexpected type of Response")}var BF=b(()=>{Et();xl();Ky()});var on,ts,UF,MF,Rl,phe,fhe,Hy,mhe,hhe,ghe,Tl,yhe,bhe,She;var Vy=b(()=>{on={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},ts={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(UF))},2(e,t){t.rows.push(e.message(MF))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},UF={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},MF={default(){return[]},1(e,t){t.push(e.message(She))}},Rl={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(phe);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(fhe);t.stepErrors.set(r,o)}},phe={default(){return[0,ts.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(ts)}},fhe={default(){return[0,on.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(on)}},Hy={default(){return{type:"none"}},1(e){return e.message(mhe)},2(e){return e.message(hhe)},3(e){return e.message(ghe)},4(e){return{type:"row",row:e.message(MF)}},5(e){return{type:"error",error:e.message(on)}}},mhe={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(UF))}},hhe={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},ghe={default(){return{type:"step_error",step:0,error:on.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(on)}},Tl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(yhe))},2(e,t){t.cols.push(e.message(bhe))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},yhe={default(){return{name:void 0}},1(e,t){t.name=e.string()}},bhe={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},She={default(){return},1(e){return null},2(e){return e.sint64()},3(e){return e.double()},4(e){return e.string()},5(e){return e.bytes()}}});var qF,vhe,whe,xhe,_he,Ehe,Ahe,Ihe,khe;var FF=b(()=>{Vy();qF={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(vhe)},3(e){return e.message(xhe)},4(e){return e.message(whe)}},vhe={default(){return{type:"hello_error",error:on.default()}},1(e,t){t.error=e.message(on)}},whe={default(){return{type:"response_error",requestId:0,error:on.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(on)}},xhe={default(){return{type:"response_ok",requestId:0,response:{type:"none"}}},1(e,t){t.requestId=e.int32()},2(e,t){t.response={type:"open_stream"}},3(e,t){t.response={type:"close_stream"}},4(e,t){t.response=e.message(_he)},5(e,t){t.response=e.message(Ehe)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(Ahe)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(Ihe)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(khe)}},_he={default(){return{type:"execute",result:ts.default()}},1(e,t){t.result=e.message(ts)}},Ehe={default(){return{type:"batch",result:Rl.default()}},1(e,t){t.result=e.message(Rl)}},Ahe={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Hy))},2(e,t){t.done=e.bool()}},Ihe={default(){return{type:"describe",result:Tl.default()}},1(e,t){t.result=e.message(Tl)}},khe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var JF,hT,Wy;var Gy=b(()=>{nT();Et();oT();$p();El();nn();uT();OF();DF();BF();FF();JF=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),hT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Wy=class Wy extends Sl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Yi,this._streamIdAlloc=new Yi,this._cursorIdAlloc=new Yi,this.#l=new Yi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#p()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#f(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#p(){let e=this.#e.protocol;if(e===void 0){this.#u(new Ge("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=hT.get(e),this.#i===void 0){this.#u(new ze(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=Ip(e,$F);this.#e.send(r)}else if(t==="protobuf"){let r=Tp(e,NF);this.#e.send(r)}else throw Ke(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new xn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new _t("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#f(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new vl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new vl(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new ze("Received non-text message from server with JSON encoding"));return}t=fa(JSON.parse(e.data),jF)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new ze("Received non-binary message from server with Protobuf encoding"));return}t=Qi(new Uint8Array(e.data),qF)}else throw Ke(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new ze("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new ze("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw Uo(e.error);return}else if(!this.#o)throw new ze("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new ze("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new ze("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new ze("Received unexpected error response");this.#c.free(t),r.errorCallback(Uo(e.error))}else throw Ke(e,"Impossible ServerMsg type")}openStream(){return Pp.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new ga(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new Ge("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var ya;var KF=b(()=>{if(typeof queueMicrotask<"u")ya=queueMicrotask;else{let e=Promise.resolve();ya=(t)=>{e.then(t)}}});class gT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function HF(e){let t=Ur(e.baton),r=Ur(e.base_url),o=_n(e.results,Rhe);return{baton:t,baseUrl:r,results:o}}function Rhe(e){let t=Tr(e.type);if(t==="ok")return{type:"ok",response:The(kt(e.response))};else if(t==="error")return{type:"error",error:es(kt(e.error))};else throw new ze("Unexpected type of StreamResult")}function The(e){let t=Tr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Lp(kt(e.result))};else if(t==="batch")return{type:"batch",result:qy(kt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Jy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Gi(e.is_autocommit)};else throw new ze("Unexpected type of StreamResponse")}function VF(e){let t=Ur(e.baton),r=Ur(e.base_url);return{baton:t,baseUrl:r}}var yT=b(()=>{Et();xl();Ky()});var WF,$he,Ohe,Che,zhe,Phe,Nhe,GF;var bT=b(()=>{Vy();WF={default(){return{baton:void 0,baseUrl:void 0,results:[]}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()},3(e,t){t.results.push(e.message($he))}},$he={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(Ohe)}},2(e){return{type:"error",error:e.message(on)}}},Ohe={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(Che)},3(e){return e.message(zhe)},4(e){return{type:"sequence"}},5(e){return e.message(Phe)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(Nhe)}},Che={default(){return{type:"execute",result:ts.default()}},1(e,t){t.result=e.message(ts)}},zhe={default(){return{type:"batch",result:Rl.default()}},1(e,t){t.result=e.message(Rl)}},Phe={default(){return{type:"describe",result:Tl.default()}},1(e,t){t.result=e.message(Tl)}},Nhe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},GF={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var ST;var QF=b(()=>{xl();tT();Et();nn();yT();bT();Ky();Vy();ST=class ST extends zp{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new gT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new ze("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(VF,GF);if(t===void 0)throw new ze("Empty response to cursor request");return t}next(){return this.#a(Fy,Hy)}close(){this._setClosed(new Ge("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new _t("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return fa(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Qi(n,t)}else throw Ke(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new ze("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function YF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,Dhe)}function Dhe(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Np);else if(t.type==="batch")e.object("batch",t.batch,Il);else if(t.type==="sequence"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit");else throw Ke(t,"Impossible type of StreamRequest")}function XF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,Il)}var vT=b(()=>{pT();nn()});function e3(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,Lhe)}function Lhe(e,t){if(t.type==="close")e.message(1,t,Zhe);else if(t.type==="execute")e.message(2,t,jhe);else if(t.type==="batch")e.message(3,t,Bhe);else if(t.type==="sequence")e.message(4,t,Uhe);else if(t.type==="describe")e.message(5,t,Mhe);else if(t.type==="store_sql")e.message(6,t,qhe);else if(t.type==="close_sql")e.message(7,t,Fhe);else if(t.type==="get_autocommit")e.message(8,t,Jhe);else throw Ke(t,"Impossible type of StreamRequest")}function Zhe(e,t){}function jhe(e,t){e.message(1,t.stmt,Dp)}function Bhe(e,t){e.message(1,t.batch,kl)}function Uhe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Mhe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function qhe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Fhe(e,t){e.int32(1,t.sqlId)}function Jhe(e,t){}function t3(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,kl)}var wT=b(()=>{mT();nn()});function Khe(e,t){if(t.results.length!==e.length)throw new ze("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new ze("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(Uo(o.error));else if(o.type==="none")throw new ze("Received unrecognized type of StreamResult");else throw Ke(o,"Received impossible type of StreamResult")}}async function Hhe(e,t){if(t==="json"){let r=await e.json();return fa(r,HF)}if(t==="protobuf"){let r=await e.arrayBuffer();return Qi(new Uint8Array(r),WF)}throw await e.body?.cancel(),Ke(t,"Impossible encoding")}async function Vhe(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return Uo(o);return new pa(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new pa(r,e.status)}return await e.body?.cancel(),new pa(r,e.status)}var Qy;var xT=b(()=>{Et();nT();oT();KF();$p();El();My();nn();QF();vT();wT();vT();wT();yT();bT();Qy=class Qy extends Al{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#p;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new Xi,this.#s=!1,this.#l=!1,this.#d=!1,this.#p=void 0,this.#m=new Yi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#f({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new ga(this,t)}_closeSql(e){if(this.#p!==void 0)return;this.#f({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#f({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#f({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#f(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,ya(()=>this.#u())}close(){this._setClosed(new Ge("Stream was manually closed"))}closeGracefully(){this.#l=!0,ya(()=>this.#u())}get closed(){return this.#p!==void 0||this.#l}_setClosed(e){if(this.#p!==void 0)return;if(this.#p=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,ya(()=>this.#u())}#g(e){if(this.#p!==void 0)throw new _t("Stream is closed",this.#p);else if(this.#l)throw new _t("Stream is closing",void 0);else this.#a.push(e),ya(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new Ge("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Ke(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>Hhe(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Khe(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new ST(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),l=this.#n;s=l(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Vhe(a).then((l)=>{throw l});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,YF,e3)}#v(e,t){if(t.cursorPath===void 0)throw new xn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,XF,t3)}#w(e,t,r,o,n){let i,s;if(r==="json")i=Ip(t,o),s="application/json";else if(r==="protobuf")i=Tp(t,n),s="application/x-protobuf";else throw Ke(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function Ghe(e,t){let r=e;for(let o of Whe){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return _T}var Whe,_T,Yy;var ET=b(()=>{Et();xT();Whe=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],_T={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};Yy=class Yy extends Sl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=Ghe(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(_T),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=_T.version)return;else if(this._endpoint===void 0)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the HTTP server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this._endpoint.version<e)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new _t("Client is closed",this.#o);let e=new Qy(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new Ge("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new _t("Client was closed",e))}}});var r3=b(()=>{Et()});function AT(e,t,r=2){if(typeof Wi>"u")throw new Ep("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(hT.keys());else o=Array.from(JF.keys());let n=new Wi(e,o);return new Wy(n,t)}function IT(e,t,r,o,n=2){return new Yy(e instanceof URL?e:new URL(e),t,r,o,n)}var Xy=b(()=>{eT();Gy();Et();ET();Gy();eT();cT();r3();El();By();My();ET();xT();Gy();uT();Et()});class Zp{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Mo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Hi(this.#e)),l=s;o=r.map((u)=>{let d=i.step().condition(ut.ok(l));if(this.#t>=3)d.condition(ut.not(ut.isAutocommit(i)));let p=d.query(u);return p.catch(()=>{return}),l=d,p}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let l=i.step();if(s!==void 0)l.condition(ut.ok(s));if(this.#t>=3)l.condition(ut.not(ut.isAutocommit(i)));let u=l.query(a);return u.catch(()=>{return}),s=l,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Wt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push(Ol(s))}catch(s){if(s instanceof Wt)throw s;let a=st(s);if(a instanceof Ce)throw new Wt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Hi(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function $l(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Hi(e)),a=i,l=o.map((h)=>{let S=r.step().condition(ut.ok(a));if(t>=3)S.condition(ut.not(ut.isAutocommit(r)));let y=S.query(h);return a=S,y}),u=r.step().condition(ut.ok(a));if(t>=3)u.condition(ut.not(ut.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(ut.not(ut.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<l.length;h++)try{let S=await l[h];if(S===void 0)throw new Wt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push(Ol(S))}catch(S){if(S instanceof Wt)throw S;let y=st(S);if(y instanceof Ce)throw new Wt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function Mo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new Cp(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function Ol(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new hl(t,r,o,n,i)}function st(e){if(e instanceof Ge){let t=n3(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function n3(e){if(e instanceof _p&&e.code!==void 0)return e.code;else if(e instanceof ze)return"HRANA_PROTO_ERROR";else if(e instanceof _t)return e.cause instanceof Ge?n3(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof vl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof pa)return"SERVER_ERROR";else if(e instanceof xn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var RT=b(()=>{Xy();wn();gl()});class Cl{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new o3,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class o3{#e;constructor(){this.#e=new Map}get(e){let t=this.#e.get(e);if(t!==void 0)this.#e.delete(e),this.#e.set(e,t);return t}set(e,t){this.#e.set(e,t)}peekLru(){for(let e of this.#e.entries())return e;return}delete(e){this.#e.delete(e)}get size(){return this.#e.size}}var TT=ye(function(zUe,s3){function Qhe(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var l=r.shift();if(a.queue=r.length,l)s(l.fn).then(l.resolve).catch(l.reject)}function i(l){return new Promise(function(u,d){r.push({fn:l,resolve:u,reject:d}),a.queue=r.length})}function s(l){t++;try{return Promise.resolve(l()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(l){if(t>=e)return i(l);else return s(l)};return a}function Yhe(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function i3(e){return e.queue=0,e.map=Yhe,e}s3.exports=function(e){if(e)return i3(Qhe(e));else return i3(function(t){return t()})}});function l3(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${ro}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=bp(e.scheme,e.authority,e.path),r;try{r=AT(t,e.authToken)}catch(o){if(o instanceof Ep){let n=e.scheme==="wss"?"https":"http",i=bp(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${ro}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new u3(r,t,e.authToken,e.intMode,e.concurrency)}class u3{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=c3.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=Mo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return Ol(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(Mo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await $l(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Mo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await $l("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new d3(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Xhe&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=a3}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=AT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Cl(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=a3;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var c3,Xhe=60000,a3=100,d3;var p3=b(()=>{Xy();wn();wp();RT();Ty();gl();c3=Vl(TT(),1);wn();d3=class d3 extends Zp{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function m3(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${ro}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=bp(e.scheme,e.authority,e.path);return new g3(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class g3{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=IT(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=f3.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=Mo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return Ol(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Mo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new Cl(s,h3).apply(o);let u=s.batch(!1);i=$l(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Mo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=$l("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new y3(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=IT(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var f3,h3=30,y3;var b3=b(()=>{Xy();wn();wp();RT();Ty();gl();f3=Vl(TT(),1);wn();y3=class y3 extends Zp{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Cl(e,h3)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function zl(e){return ege(vp(e,!0))}function ege(e){if(e.scheme==="wss"||e.scheme==="ws")return l3(e);else if(e.scheme==="https"||e.scheme==="http")return m3(e);else return fF(e)}var $T=b(()=>{wp();bF();p3();b3();wn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var $e=b(()=>{F=Symbol.for("drizzle:entityKind")});var He;var En=b(()=>{$e();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var jp;var eb=b(()=>{$e();jp=class jp{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var Pl=b(()=>{ir=Symbol.for("drizzle:Name")});var OT,S3;var v3=b(()=>{$e();Pl();OT=class OT{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new S3(e,this)}};S3=class S3{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function tb(e,...t){return e(...t)}var CT=()=>{};function zT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var w3,tge,x3;var _3=b(()=>{$e();Pl();w3=class w3{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new x3(e,this.columns,this.nullsNotDistinctConfig,this.name)}};tge=class tge{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new w3(e,this.name)}};x3=class x3{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??zT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function E3(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function A3(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[l,u]=E3(e,o+1,!0);r.push(l),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[l,u]=A3(e,o+1);r.push(l),o=u;continue}let[s,a]=E3(e,o,!1);r.push(s),o=a}return[r,o]}function I3(e){let[t]=A3(e,1);return t}function PT(e){return`{${e.map((t)=>{if(Array.isArray(t))return PT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var k3=()=>{};var Bp,Nl,R3,rge,T3,NT;var $3=b(()=>{eb();En();$e();v3();CT();_3();k3();Bp=class Bp extends jp{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new T3(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>tb((n,i)=>{let s=new OT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new R3(e,this.config)}};Nl=class Nl extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=zT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};R3=class R3 extends Nl{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};rge=class rge{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};T3=class T3 extends Bp{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new NT(e,this.config,t)}};NT=class NT extends Nl{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=I3(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,NT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return PT(r)}}});function z3(e){return!!e&&typeof e==="function"&&O3 in e&&e[O3]===!0}var nge,C3,O3,oge,P3;var N3=b(()=>{$e();$3();nge=class nge extends Bp{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new C3(e,this.config)}};C3=class C3 extends Nl{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};O3=Symbol.for("drizzle:isPgEnum");oge=class oge extends Bp{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new P3(e,this.config)}};P3=class P3 extends Nl{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var dt,Up;var An=b(()=>{$e();dt=class dt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};Up=class Up extends dt{static[F]="WithSubquery"}});var D3="0.45.2";var L3=()=>{};var DT,LT,Z3;var j3=b(()=>{CT();L3();Z3={startActiveSpan(e,t){if(!DT)return t();if(!LT)LT=DT.trace.getTracer("drizzle-orm",D3);return tb((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),DT,LT)}}});var pt;var qo=b(()=>{pt=Symbol.for("drizzle:ViewBaseConfig")});function rs(e){return e[ir]}function ba(e){return`${e[rb]??"public"}.${e[ir]}`}var rb,nb,B3,ZT,jT,Mp,U3,ige,ge;var sr=b(()=>{$e();Pl();rb=Symbol.for("drizzle:Schema"),nb=Symbol.for("drizzle:Columns"),B3=Symbol.for("drizzle:ExtraConfigColumns"),ZT=Symbol.for("drizzle:OriginalName"),jT=Symbol.for("drizzle:BaseName"),Mp=Symbol.for("drizzle:IsAlias"),U3=Symbol.for("drizzle:ExtraConfigBuilder"),ige=Symbol.for("drizzle:IsDrizzleTable");ge=class ge{static[F]="Table";static Symbol={Name:ir,Schema:rb,OriginalName:ZT,Columns:nb,ExtraConfigColumns:B3,BaseName:jT,IsAlias:Mp,ExtraConfigBuilder:U3};[ir];[ZT];[rb];[nb];[B3];[jT];[Mp]=!1;[ige]=!0;[U3]=void 0;constructor(e,t,r){this[ir]=this[ZT]=e,this[rb]=t,this[jT]=r}}});function BT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function age(e){let t={sql:"",params:[]};for(let r of e)if(t.sql+=r.sql,t.params.push(...r.params),r.typings?.length){if(!t.typings)t.typings=[];t.typings.push(...r.typings)}return t}function M3(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Nt(e[0]));for(let[o,n]of t.entries())r.push(n,new Nt(e[o+1]));return new Ee(r)}function qp(e,t){return e.map((r)=>{if(oe(r,ns)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Mr)&&oe(r.value,ns)){if(!(r.value.name in t))throw Error(`No value for placeholder "${r.value.name}" was provided`);return r.encoder.mapToDriverValue(t[r.value.name])}return r})}var sge,Nt,Ee,ob,q3,F3,FMe,Mr,ns,cge,sn;var Qt=b(()=>{$e();N3();An();j3();qo();En();sr();sge=class sge{static[F]="FakePrimitiveParam"};Nt=class Nt{static[F]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Ee([this])}};Ee=class Ee{constructor(e){this.queryChunks=e;for(let t of e)if(oe(t,ge)){let r=t[ge.Symbol.Schema];this.usedTables.push(r===void 0?t[ge.Symbol.Name]:r+"."+t[ge.Symbol.Name])}}static[F]="SQL";decoder=q3;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return Z3.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:l}=r;return age(e.map((u)=>{if(oe(u,Nt))return{sql:u.value.join(""),params:[]};if(oe(u,ob))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new Nt("(")];for(let[p,m]of u.entries())if(d.push(m),p<u.length-1)d.push(new Nt(", "));return d.push(new Nt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,Ee))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,ge)){let d=u[ge.Symbol.Schema],p=u[ge.Symbol.Name];return{sql:d===void 0||u[Mp]?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let p=u.table[ge.Symbol.Schema];return{sql:u.table[Mp]||p===void 0?n(u.table[ge.Symbol.Name])+"."+n(d):n(p)+"."+n(u.table[ge.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,sn)){let d=u[pt].schema,p=u[pt].name;return{sql:d===void 0||u[pt].isAlias?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Mr)){if(oe(u.value,ns))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,Ee))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let p=["none"];if(s)p=[s(u.encoder)];return{sql:i(l.value++,d),params:[d],typings:p}}if(oe(u,ns))return{sql:i(l.value++,u),params:[u],typings:["none"]};if(oe(u,Ee.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,dt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new Nt("("),u._.sql,new Nt(") "),new ob(u._.alias)],r)}if(z3(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(BT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new Nt("("),u.getSQL(),new Nt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new Ee.Aliased(this,e)}mapWith(e){return this.decoder=typeof e==="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}};ob=class ob{constructor(e){this.value=e}static[F]="Name";brand;getSQL(){return new Ee([this])}};q3={mapFromDriverValue:(e)=>e},F3={mapToDriverValue:(e)=>e},FMe={...q3,...F3};Mr=class Mr{constructor(e,t=F3){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new Ee([this])}};((e)=>{function t(){return new Ee([])}e.empty=t;function r(l){return new Ee(l)}e.fromList=r;function o(l){return new Ee([new Nt(l)])}e.raw=o;function n(l,u){let d=[];for(let[p,m]of l.entries()){if(p>0&&u!==void 0)d.push(u);d.push(m)}return new Ee(d)}e.join=n;function i(l){return new ob(l)}e.identifier=i;function s(l){return new ns(l)}e.placeholder=s;function a(l,u){return new Mr(l,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Ee||(Ee={}));ns=class ns{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new Ee([this])}};cge=Symbol.for("drizzle:IsDrizzleView");sn=class sn{static[F]="View";[pt];[cge]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[pt]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new Ee([this])}};He.prototype.getSQL=function(){return new Ee([this])};ge.prototype.getSQL=function(){return new Ee([this])};dt.prototype.getSQL=function(){return new Ee([this])}});function UT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},l)=>{let u;if(oe(a,He))u=a;else if(oe(a,Ee))u=a.decoder;else if(oe(a,dt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[p,m]of s.entries())if(p<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[l],S=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=S===null?rs(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==rs(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function an(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,Ee)||oe(n,Ee.Aliased)||oe(n,dt))r.push({path:i,field:n});else if(oe(n,ge))r.push(...an(n[ge.Symbol.Columns],i));else r.push(...an(n,i));return r},[])}function Fp(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function ib(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,Ee)||oe(n,He))return[o,n];else return[o,new Mr(n,e[ge.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function J3(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function sb(e){return e[ge.Symbol.Columns]}function Jp(e){return oe(e,dt)?e._.alias:oe(e,sn)?e[pt].name:oe(e,Ee)?void 0:e[ge.Symbol.IsAlias]?e[ge.Symbol.Name]:e[ge.Symbol.BaseName]}function so(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function K3(e){if(typeof e!=="object"||e===null)return!1;if(e.constructor.name!=="Object")return!1;if("logger"in e){let t=typeof e.logger;if(t!=="boolean"&&(t!=="object"||typeof e.logger.logQuery!=="function")&&t!=="undefined")return!1;return!0}if("schema"in e){let t=typeof e.schema;if(t!=="object"&&t!=="undefined")return!1;return!0}if("casing"in e){let t=typeof e.casing;if(t!=="string"&&t!=="undefined")return!1;return!0}if("mode"in e){if(e.mode!=="default"||e.mode!=="planetscale"||e.mode!==void 0)return!1;return!0}if("connection"in e){let t=typeof e.connection;if(t!=="string"&&t!=="object"&&t!=="undefined")return!1;return!0}if("client"in e){let t=typeof e.client;if(t!=="object"&&t!=="function"&&t!=="undefined")return!1;return!0}if(Object.keys(e).length===0)return!0;return!1}var MT;var Sr=b(()=>{En();$e();Qt();An();sr();qo();MT=typeof TextDecoder>"u"?null:new TextDecoder});var H3,qT,FT;var ab=b(()=>{$e();H3=class H3{static[F]="ConsoleLogWriter";write(e){console.log(e)}};qT=class qT{static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new H3}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};FT=class FT{static[F]="NoopLogger";logQuery(){}}});var V3,W3,JT;var G3=b(()=>{$e();sr();V3=Symbol.for("drizzle:PgInlineForeignKeys"),W3=Symbol.for("drizzle:EnableRLS");JT=class JT extends ge{static[F]="PgTable";static Symbol=Object.assign({},ge.Symbol,{InlineForeignKeys:V3,EnableRLS:W3});[V3]=[];[W3]=!1;[ge.Symbol.ExtraConfigBuilder]=void 0;[ge.Symbol.ExtraConfigColumns]={}}});var KT,Q3;var Y3=b(()=>{$e();G3();KT=class KT{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new Q3(e,this.columns,this.name)}};Q3=class Q3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[JT.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function $r(e,t){if(M3(t)&&!BT(e)&&!oe(e,Mr)&&!oe(e,ns)&&!oe(e,He)&&!oe(e,ge)&&!oe(e,sn))return new Mr(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" and ")),new Nt(")")])}function cn(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" or ")),new Nt(")")])}function e5(e){return C`not ${e}`}function is(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>$r(r,e))}`}return C`${e} in ${$r(t,e)}`}function cb(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>$r(r,e))}`}return C`${e} not in ${$r(t,e)}`}function qr(e){return C`${e} is null`}function n5(e){return C`${e} is not null`}function lb(e){return C`exists ${e}`}function ss(e){return C`not exists ${e}`}function o5(e,t,r){return C`${e} between ${$r(t,e)} and ${$r(r,e)}`}function i5(e,t,r){return C`${e} not between ${$r(t,e)} and ${$r(r,e)}`}function s5(e,t){return C`${e} like ${t}`}function a5(e,t){return C`${e} not like ${t}`}function c5(e,t){return C`${e} ilike ${t}`}function l5(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${$r(t,e)}`,X3=(e,t)=>C`${e} <> ${$r(t,e)}`,In=(e,t)=>C`${e} > ${$r(t,e)}`,t5=(e,t)=>C`${e} >= ${$r(t,e)}`,r5=(e,t)=>C`${e} < ${$r(t,e)}`,os=(e,t)=>C`${e} <= ${$r(t,e)}`;var u5=b(()=>{En();$e();sr();Qt()});function Fo(e){return C`${e} asc`}function Sa(e){return C`${e} desc`}var d5=b(()=>{Qt()});var HT=b(()=>{u5();d5()});function f5(){return{and:tt,between:o5,eq:je,exists:lb,gt:In,gte:t5,ilike:c5,inArray:is,isNull:qr,isNotNull:n5,like:s5,lt:r5,lte:os,ne:X3,not:e5,notBetween:i5,notExists:ss,notLike:a5,notIlike:l5,notInArray:cb,or:cn,sql:C}}function m5(){return{sql:C,asc:Fo,desc:Sa}}function h5(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,ge))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,ge)){let a=ba(s),l=o[a];r[a]=i,n[i]={tsName:i,dbName:s[ge.Symbol.Name],schema:s[ge.Symbol.Schema],columns:s[ge.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let d of Object.values(s[ge.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[ge.Symbol.ExtraConfigBuilder]?.(s[ge.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,KT))n[i].primaryKey.push(...d.columns)}}else if(oe(s,p5)){let a=ba(s.table),l=r[a],u=s.config(t(s.table)),d;for(let[p,m]of Object.entries(u))if(l){let h=n[l];if(h.relations[p]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[p]=m}}return{tables:n,tableNamesMap:r}}function lge(e){return function(r,o){return new as(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function uge(e){return function(r,o){return new Kp(e,r,o)}}function g5(e,t,r){if(oe(r,as)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ba(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[ge.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ba(i)];if(!s)throw Error(`Table "${i[ge.Symbol.Name]}" not found in schema`);let a=[];for(let l of Object.values(n.relations))if(r.relationName&&r!==l&&l.relationName===r.relationName||!r.relationName&&l.referencedTable===r.sourceTable)a.push(l);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[ge.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],as)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function y5(e){return{one:lge(e),many:uge(e)}}function ub(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let l=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(l,as)?d&&ub(e,e[a.relationTableTsKey],d,a.selection,n):d.map((p)=>ub(e,e[a.relationTableTsKey],p,a.selection,n))}else{let l=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,Ee))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=l===null?null:d.mapFromDriverValue(l)}return i}var VT,p5,as,Kp;var Hp=b(()=>{sr();En();$e();Y3();HT();Qt();VT=class VT{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[ge.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};p5=class p5{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};as=class as extends VT{constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new as(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Kp=class Kp extends VT{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new Kp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function Vp(e,t){return new Proxy(e,new va(t,!1))}function ao(e,t){return new Proxy(e,new Dl(new Proxy(e.table,new va(t,!1))))}function WT(e,t){return new Ee.Aliased(Wp(e.sql,t),e.fieldAlias)}function Wp(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return ao(r,t);if(oe(r,Ee))return Wp(r,t);if(oe(r,Ee.Aliased))return WT(r,t);return r}))}var Dl,va,dge;var Gp=b(()=>{En();$e();Qt();sr();qo();Dl=class Dl{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};va=class va{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===ge.Symbol.IsAlias)return!0;if(t===ge.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===ge.Symbol.OriginalName)return this.alias;if(t===pt)return{...e[pt],name:this.alias,isAlias:!0};if(t===ge.Symbol.Columns){let o=e[ge.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new Dl(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new Dl(new Proxy(e,this)));return r}};dge=class dge{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return Vp(e.sourceTable,this.alias);return e[t]}}});var at;var wa=b(()=>{Gp();En();$e();Qt();An();qo();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===pt)return{...e[pt],selectedFields:new Proxy(e[pt].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,dt)?e._.selectedFields:oe(e,sn)?e[pt].selectedFields:e)[t];if(oe(o,Ee.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,Ee)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new Dl(new Proxy(o.table,new va(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var vr;var Jo=b(()=>{$e();vr=class vr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var GT,b5;var QT=b(()=>{$e();Pl();GT=class GT{static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new b5(e,this)}};b5=class b5{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function YT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var S5,pge,v5;var XT=b(()=>{$e();Pl();S5=class S5{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new v5(e,this.columns,this.name)}};pge=class pge{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new S5(e,this.name)}};v5=class v5{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??YT(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Bt,yt;var cs=b(()=>{eb();En();$e();QT();XT();Bt=class Bt extends jp{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new GT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};yt=class yt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=YT(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function k5(e,t){let{name:r,config:o}=so(e,t);if(o?.mode==="json")return new _5(r);if(o?.mode==="bigint")return new w5(r);return new A5(r)}var w5,x5,_5,E5,A5,I5;var e$=b(()=>{$e();Sr();cs();w5=class w5 extends Bt{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new x5(e,this.config)}};x5=class x5 extends yt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(MT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};_5=class _5 extends Bt{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new E5(e,this.config)}};E5=class E5 extends yt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(MT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};A5=class A5 extends Bt{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new I5(e,this.config)}};I5=class I5 extends yt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function $5(e){return(t,r)=>{let{name:o,config:n}=so(t,r);return new R5(o,n,e)}}var R5,T5;var t$=b(()=>{$e();Sr();cs();R5=class R5 extends Bt{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new T5(e,this.config)}};T5=class T5 extends yt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=so(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new z5(r,o.mode);if(o?.mode==="boolean")return new N5(r,o.mode);return new O5(r)}var db,pb,O5,C5,z5,P5,N5,D5;var r$=b(()=>{$e();Qt();Sr();cs();db=class db extends Bt{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};pb=class pb extends yt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};O5=class O5 extends db{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new C5(e,this.config)}};C5=class C5 extends pb{static[F]="SQLiteInteger"};z5=class z5 extends db{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new P5(e,this.config)}};P5=class P5 extends pb{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};N5=class N5 extends db{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new D5(e,this.config)}};D5=class D5 extends pb{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function q5(e,t){let{name:r,config:o}=so(e,t),n=o?.mode;return n==="number"?new j5(r):n==="bigint"?new U5(r):new L5(r)}var L5,Z5,j5,B5,U5,M5;var n$=b(()=>{$e();Sr();cs();L5=class L5 extends Bt{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new Z5(e,this.config)}};Z5=class Z5 extends yt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};j5=class j5 extends Bt{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new B5(e,this.config)}};B5=class B5 extends yt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};U5=class U5 extends Bt{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new M5(e,this.config)}};M5=class M5 extends yt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function K5(e){return new F5(e??"")}var F5,J5;var o$=b(()=>{$e();cs();F5=class F5 extends Bt{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new J5(e,this.config)}};J5=class J5 extends yt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function ft(e,t={}){let{name:r,config:o}=so(e,t);if(o.mode==="json")return new W5(r);return new H5(r,o)}var H5,V5,W5,G5;var i$=b(()=>{$e();Sr();cs();H5=class H5 extends Bt{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new V5(e,this.config)}};V5=class V5 extends yt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};W5=class W5 extends Bt{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new G5(e,this.config)}};G5=class G5 extends yt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function Q5(){return{blob:k5,customType:$5,integer:ar,numeric:q5,real:K5,text:ft}}var Y5=b(()=>{e$();t$();r$();n$();o$();i$()});function fge(e,t,r,o,n=e){let i=new Rt(e,o,n),s=typeof t==="function"?t(Q5()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let p=d;p.setName(u);let m=p.build(i);return i[s$].push(...p.buildForeignKeys(m,i)),[u,m]})),l=Object.assign(i,a);if(l[ge.Symbol.Columns]=a,l[ge.Symbol.ExtraConfigColumns]=a,r)l[Rt.Symbol.ExtraConfigBuilder]=r;return l}var s$,Rt,Qp=(e,t,r)=>fge(e,t,r);var Ko=b(()=>{$e();sr();Y5();s$=Symbol.for("drizzle:SQLiteInlineForeignKeys");Rt=class Rt extends ge{static[F]="SQLiteTable";static Symbol=Object.assign({},ge.Symbol,{InlineForeignKeys:s$});[ge.Symbol.Columns];[s$]=[];[ge.Symbol.ExtraConfigBuilder]=void 0}});var mge,X5;var e8=b(()=>{$e();mge=class mge{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new X5(e,this)}};X5=class X5{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function Ho(e){return new t8(e,!1)}var t8,r8,n8;var o8=b(()=>{$e();t8=class t8{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new r8(this.name,e,this.unique)}};r8=class r8{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new n8(this.config,e)}};n8=class n8{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var hge,i8;var s8=b(()=>{$e();Ko();hge=class hge{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new i8(e,this.columns,this.name)}};i8=class i8{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[Rt.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function kn(e){if(oe(e,Rt))return[`${e[ge.Symbol.BaseName]}`];if(oe(e,dt))return e._.usedTables??[];if(oe(e,Ee))return e.usedTables??[];return[]}var Ll=b(()=>{$e();Qt();An();sr();Ko()});var fb;var a8=b(()=>{$e();Jo();wa();Ko();sr();Sr();Ll();fb=class fb extends vr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[ge.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[Rt.Symbol.Columns]){return this.config.returning=an(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:kn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}});function gge(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function yge(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function bge(e){return e}var a$;var c8=b(()=>{$e();sr();a$=class a${static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?gge:e==="camelCase"?yge:bge}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[ge.Symbol.Schema]??"public",r=e.table[ge.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[ge.Symbol.Schema]??"public",r=e[ge.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[ge.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Zl,Vo,c$;var mb=b(()=>{$e();Zl=class Zl extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Vo=class Vo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
446
447
|
params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,Vo),r)this.cause=r}};c$=class c$ extends Zl{static[F]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var l8=()=>{};var u8=()=>{};var d8=b(()=>{l8();u8()});var l$=b(()=>{HT();d8();Qt()});var u$=b(()=>{e$();cs();t$();r$();n$();o$();i$()});var Wo;var Yp=b(()=>{$e();Qt();Wo=class Wo extends sn{static[F]="SQLiteViewBase"}});var jl,d$,p$;var hb=b(()=>{Gp();c8();En();$e();mb();Hp();l$();Qt();u$();Ko();An();sr();Sr();qo();Yp();jl=class jl{static[F]="SQLiteDialect";casing;constructor(e){this.casing=new a$(e?.casing)}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[C`with `];for(let[r,o]of e.entries())if(t.push(C`${C.identifier(o._.alias)} as (${o._.sql})`),r<e.length-1)t.push(C`, `);return t.push(C` `),C.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:o,limit:n,orderBy:i}){let s=this.buildWithCTE(o),a=r?C` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,l=t?C` where ${t}`:void 0,u=this.buildOrderBy(i),d=this.buildLimit(n);return C`${s}delete from ${e}${l}${a}${u}${d}`}buildUpdateSet(e,t){let r=e[ge.Symbol.Columns],o=Object.keys(r).filter((i)=>t[i]!==void 0||r[i]?.onUpdateFn!==void 0),n=o.length;return C.join(o.flatMap((i,s)=>{let a=r[i],l=a.onUpdateFn?.(),u=t[i]??(oe(l,Ee)?l:C.param(l,a)),d=C`${C.identifier(this.casing.getColumnCasing(a))} = ${u}`;if(s<n-1)return[d,C.raw(", ")];return[d]}))}buildUpdateQuery({table:e,set:t,where:r,returning:o,withList:n,joins:i,from:s,limit:a,orderBy:l}){let u=this.buildWithCTE(n),d=this.buildUpdateSet(e,t),p=s&&C.join([C.raw(" from "),this.buildFromTable(s)]),m=this.buildJoins(i),h=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,S=r?C` where ${r}`:void 0,y=this.buildOrderBy(l),v=this.buildLimit(a);return C`${u}update ${e} set ${d}${p}${m}${S}${h}${y}${v}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,o=e.flatMap(({field:n},i)=>{let s=[];if(oe(n,Ee.Aliased)&&n.isSelectionField)s.push(C.identifier(n.fieldAlias));else if(oe(n,Ee.Aliased)||oe(n,Ee)){let a=oe(n,Ee.Aliased)?n.sql:n;if(t)s.push(new Ee(a.queryChunks.map((l)=>{if(oe(l,He))return C.identifier(this.casing.getColumnCasing(l));return l})));else s.push(a);if(oe(n,Ee.Aliased))s.push(C` as ${C.identifier(n.fieldAlias)}`)}else if(oe(n,He)){let a=n.table[ge.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(C`cast(${C.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(C`cast(${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(C.identifier(this.casing.getColumnCasing(n)));else s.push(C`${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))}`)}else if(oe(n,dt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let l=a[0][1],u=oe(l,Ee)?l.decoder:oe(l,He)?{mapFromDriverValue:(d)=>l.mapFromDriverValue(d)}:l.sql.decoder;if(u)n._.sql.decoder=u}s.push(n)}if(i<r-1)s.push(C`, `);return s});return C.join(o)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,o]of e.entries()){if(r===0)t.push(C` `);let n=o.table,i=o.on?C` on ${o.on}`:void 0;if(oe(n,Rt)){let s=n[Rt.Symbol.Name],a=n[Rt.Symbol.Schema],l=n[Rt.Symbol.OriginalName],u=s===l?void 0:o.alias;t.push(C`${C.raw(o.joinType)} join ${a?C`${C.identifier(a)}.`:void 0}${C.identifier(l)}${u&&C` ${C.identifier(u)}`}${i}`)}else t.push(C`${C.raw(o.joinType)} join ${n}${i}`);if(r<e.length-1)t.push(C` `)}return C.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?C` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,o]of e.entries())if(t.push(o),r<e.length-1)t.push(C`, `)}return t.length>0?C` order by ${C.join(t)}`:void 0}buildFromTable(e){if(oe(e,ge)&&e[ge.Symbol.IsAlias])return C`${C`${C.identifier(e[ge.Symbol.Schema]??"")}.`.if(e[ge.Symbol.Schema])}${C.identifier(e[ge.Symbol.OriginalName])} ${C.identifier(e[ge.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:o,having:n,table:i,joins:s,orderBy:a,groupBy:l,limit:u,offset:d,distinct:p,setOperators:m}){let h=r??an(t);for(let T of h)if(oe(T.field,He)&&rs(T.field.table)!==(oe(i,dt)?i._.alias:oe(i,Wo)?i[pt].name:oe(i,Ee)?void 0:rs(i))&&!((Z)=>s?.some(({alias:A})=>A===(Z[ge.Symbol.IsAlias]?rs(Z):Z[ge.Symbol.BaseName])))(T.field.table)){let Z=rs(T.field.table);throw Error(`Your "${T.path.join("->")}" field references a column "${Z}"."${T.field.name}", but the table "${Z}" is not part of the query! Did you forget to join it?`)}let S=!s||s.length===0,y=this.buildWithCTE(e),v=p?C` distinct`:void 0,x=this.buildSelection(h,{isSingleTable:S}),_=this.buildFromTable(i),k=this.buildJoins(s),O=o?C` where ${o}`:void 0,L=n?C` having ${n}`:void 0,P=[];if(l){for(let[T,Z]of l.entries())if(P.push(Z),T<l.length-1)P.push(C`, `)}let K=P.length>0?C` group by ${C.join(P)}`:void 0,z=this.buildOrderBy(a),W=this.buildLimit(u),ee=d?C` offset ${d}`:void 0,j=C`${y}select${v} ${x} from ${_}${k}${O}${K}${L}${z}${W}${ee}`;if(m.length>0)return this.buildSetOperations(j,m);return j}buildSetOperations(e,t){let[r,...o]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(o.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),o)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:o,limit:n,orderBy:i,offset:s}}){let a=C`${e.getSQL()} `,l=C`${o.getSQL()}`,u;if(i&&i.length>0){let h=[];for(let S of i)if(oe(S,yt))h.push(C.identifier(S.name));else if(oe(S,Ee)){for(let y=0;y<S.queryChunks.length;y++){let v=S.queryChunks[y];if(oe(v,yt))S.queryChunks[y]=C.identifier(this.casing.getColumnCasing(v))}h.push(C`${S}`)}else h.push(C`${S}`);u=C` order by ${C.join(h,C`, `)}`}let d=typeof n==="object"||typeof n==="number"&&n>=0?C` limit ${n}`:void 0,p=C.raw(`${t} ${r?"all ":""}`),m=s?C` offset ${s}`:void 0;return C`${a}${p}${l}${u}${d}${m}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:o,withList:n,select:i}){let s=[],a=e[ge.Symbol.Columns],l=Object.entries(a).filter(([S,y])=>!y.shouldDisableInsert()),u=l.map(([,S])=>C.identifier(this.casing.getColumnCasing(S)));if(i){let S=t;if(oe(S,Ee))s.push(S);else s.push(S.getSQL())}else{let S=t;s.push(C.raw("values "));for(let[y,v]of S.entries()){let x=[];for(let[_,k]of l){let O=v[_];if(O===void 0||oe(O,Mr)&&O.value===void 0){let L;if(k.default!==null&&k.default!==void 0)L=oe(k.default,Ee)?k.default:C.param(k.default,k);else if(k.defaultFn!==void 0){let P=k.defaultFn();L=oe(P,Ee)?P:C.param(P,k)}else if(!k.default&&k.onUpdateFn!==void 0){let P=k.onUpdateFn();L=oe(P,Ee)?P:C.param(P,k)}else L=C`null`;x.push(L)}else x.push(O)}if(s.push(x),y<S.length-1)s.push(C`, `)}}let d=this.buildWithCTE(n),p=C.join(s),m=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,h=r?.length?C.join(r):void 0;return C`${d}insert into ${e} ${u} ${p}${h}${m}`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:t})}buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:o,tableConfig:n,queryConfig:i,tableAlias:s,nestedQueryRelation:a,joinOn:l}){let u=[],d,p,m=[],h,S=[];if(i===!0)u=Object.entries(n.columns).map(([x,_])=>({dbKey:_.name,tsKey:x,field:ao(_,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let v=Object.fromEntries(Object.entries(n.columns).map(([P,K])=>[P,ao(K,s)]));if(i.where){let P=typeof i.where==="function"?i.where(v,f5()):i.where;h=P&&Wp(P,s)}let x=[],_=[];if(i.columns){let P=!1;for(let[K,z]of Object.entries(i.columns)){if(z===void 0)continue;if(K in n.columns){if(!P&&z===!0)P=!0;_.push(K)}}if(_.length>0)_=P?_.filter((K)=>i.columns?.[K]===!0):Object.keys(n.columns).filter((K)=>!_.includes(K))}else _=Object.keys(n.columns);for(let P of _){let K=n.columns[P];x.push({tsKey:P,value:K})}let k=[];if(i.with)k=Object.entries(i.with).filter((P)=>!!P[1]).map(([P,K])=>({tsKey:P,queryConfig:K,relation:n.relations[P]}));let O;if(i.extras){O=typeof i.extras==="function"?i.extras(v,{sql:C}):i.extras;for(let[P,K]of Object.entries(O))x.push({tsKey:P,value:WT(K,s)})}for(let{tsKey:P,value:K}of x)u.push({dbKey:oe(K,Ee.Aliased)?K.fieldAlias:n.columns[P].name,tsKey:P,field:oe(K,He)?ao(K,s):K,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof i.orderBy==="function"?i.orderBy(v,m5()):i.orderBy??[];if(!Array.isArray(L))L=[L];m=L.map((P)=>{if(oe(P,He))return ao(P,s);return Wp(P,s)}),d=i.limit,p=i.offset;for(let{tsKey:P,queryConfig:K,relation:z}of k){let W=g5(t,r,z),ee=ba(z.referencedTable),j=r[ee],T=`${s}_${P}`,Z=tt(...W.fields.map((I,q)=>je(ao(W.references[q],T),ao(I,s)))),A=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[j],tableConfig:t[j],queryConfig:oe(z,as)?K===!0?{limit:1}:{...K,limit:1}:K,tableAlias:T,joinOn:Z,nestedQueryRelation:z}),R=C`(${A.sql})`.as(P);u.push({dbKey:P,tsKey:P,field:R,relationTableTsKey:j,isJson:!0,selection:A.selection})}}if(u.length===0)throw new Zl({message:`No fields selected for table "${n.tsName}" ("${s}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let y;if(h=tt(l,h),a){let v=C`json_array(${C.join(u.map(({field:k})=>oe(k,yt)?C.identifier(this.casing.getColumnCasing(k)):oe(k,Ee.Aliased)?k.sql:k),C`, `)})`;if(oe(a,Kp))v=C`coalesce(json_group_array(${v}), json_array())`;let x=[{dbKey:"data",tsKey:"data",field:v.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:u}];if(d!==void 0||p!==void 0||m.length>0)y=this.buildSelectQuery({table:Vp(o,s),fields:{},fieldsFlat:[{path:[],field:C.raw("*")}],where:h,limit:d,offset:p,orderBy:m,setOperators:[]}),h=void 0,d=void 0,p=void 0,m=void 0;else y=Vp(o,s);y=this.buildSelectQuery({table:oe(y,Rt)?y:new dt(y,{},s),fields:{},fieldsFlat:x.map(({field:k})=>({path:[],field:oe(k,He)?ao(k,s):k})),joins:S,where:h,limit:d,offset:p,orderBy:m,setOperators:[]})}else y=this.buildSelectQuery({table:Vp(o,s),fields:{},fieldsFlat:u.map(({field:v})=>({path:[],field:oe(v,He)?ao(v,s):v})),joins:S,where:h,limit:d,offset:p,orderBy:m,setOperators:[]});return{tableTsKey:n.tsName,sql:y,selection:u}}};d$=class d$ extends jl{static[F]="SQLiteSyncDialect";migrate(e,t,r){let o=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=C`
|
|
447
448
|
CREATE TABLE IF NOT EXISTS ${C.identifier(o)} (
|
|
448
449
|
id SERIAL PRIMARY KEY,
|
|
@@ -455,21 +456,21 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrac
|
|
|
455
456
|
hash text NOT NULL,
|
|
456
457
|
created_at numeric
|
|
457
458
|
)
|
|
458
|
-
`;await t.run(n);let s=(await t.values(C`SELECT id, hash, created_at FROM ${C.identifier(o)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let l of e)if(!s||Number(s[2])<l.folderMillis){for(let u of l.sql)await a.run(C.raw(u));await a.run(C`INSERT INTO ${C.identifier(o)} ("hash", "created_at") VALUES(${l.hash}, ${l.folderMillis})`)}})}}});var f$;var p8=b(()=>{$e();f$=class f${static[F]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function gb(e,t){return(r,o,...n)=>{let i=[o,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of i)if(!Fp(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(i)}}var Rn,f8,m$,bge=()=>({union:Sge,unionAll:vge,intersect:wge,except:xge}),Sge,vge,wge,xge;var h$=b(()=>{$e();p8();Jo();wa();Qt();An();sr();Sr();qo();Ll();Yp();Rn=class Rn{static[F]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(oe(e,dt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((o)=>[o,e[o]]));else if(oe(e,Wo))r=e[pt].selectedFields;else if(oe(e,Ee))r={};else r=sb(e);return new m$({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};f8=class f8 extends f${static[F]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:o,dialect:n,withList:i,distinct:s}){super();this.config={withList:i,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=o,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=Jp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of kn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let o=this.tableName,n=Jp(t);for(let i of kn(t))this.usedTables.add(i);if(typeof n==="string"&&this.config.joins?.some((i)=>i.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof o==="string")this.config.fields={[o]:this.config.fields};if(typeof n==="string"&&!oe(t,Ee)){let i=oe(t,dt)?t._.selectedFields:oe(t,sn)?t[pt].selectedFields:t[ge.Symbol.Columns];this.config.fields[n]=i}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let o=typeof r==="function"?r(bge()):r;if(!Fp(this.getSelectedFields(),o.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:o}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...kn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...kn(r.table));return new Proxy(new dt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new at({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};m$=class m$ extends f8{static[F]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=an(this.config.fields),r=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.all()}};J3(m$,[vr]);Sge=gb("union",!1),vge=gb("union",!0),wge=gb("intersect",!1),xge=gb("except",!1)});var xa;var yb=b(()=>{$e();wa();hb();An();h$();xa=class xa{static[F]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=oe(e,jl)?e:void 0,this.dialectConfig=oe(e,jl)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new Up(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function o(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:o}}select(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new d$(this.dialectConfig);return this.dialect}}});var bb,g$;var m8=b(()=>{$e();Jo();Qt();Ko();sr();Sr();Ll();yb();bb=class bb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let o={},n=this.table[ge.Symbol.Columns];for(let i of Object.keys(r)){let s=r[i];o[i]=oe(s,Ee)?s:new Mr(s,n[i])}return o});return new g$(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new xa):e;if(!oe(t,Ee)&&!Fp(this.table[nb],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new g$(this.table,t,this.session,this.dialect,this.withList,!0)}};g$=class g$ extends vr{constructor(e,t,r,o,n,i){super();this.session=r,this.dialect=o,this.config={table:e,values:t,withList:n,select:i}}static[F]="SQLiteInsert";config;returning(e=this.config.table[Rt.Symbol.Columns]){return this.config.returning=an(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(C` on conflict do nothing`);else{let t=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,r=e.where?C` where ${e.where}`:C``;this.config.onConflict.push(C` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?C` where ${e.where}`:void 0,r=e.targetWhere?C` where ${e.targetWhere}`:void 0,o=e.setWhere?C` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,i=this.dialect.buildUpdateSet(this.config.table,ib(this.config.table,e.set));return this.config.onConflict.push(C` on conflict ${n}${r} do update set ${i}${t}${o}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:kn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var Sb,h8;var g8=b(()=>{$e();Jo();wa();Ko();An();sr();Sr();qo();Ll();Yp();Sb=class Sb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteUpdateBuilder";set(e){return new h8(this.table,ib(this.table,e),this.session,this.dialect,this.withList)}};h8=class h8 extends vr{constructor(e,t,r,o,n){super();this.session=r,this.dialect=o,this.config={set:t,table:e,withList:n,joins:[]}}static[F]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let o=Jp(t);if(typeof o==="string"&&this.config.joins.some((n)=>n.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?oe(t,Rt)?t[ge.Symbol.Columns]:oe(t,dt)?t._.selectedFields:oe(t,Wo)?t[pt].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[ge.Symbol.Columns],new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:o}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[ge.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[Rt.Symbol.Columns]){return this.config.returning=an(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:kn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var y$=b(()=>{a8();m8();yb();h$();g8()});var Xp;var y8=b(()=>{$e();Qt();Xp=class Xp extends Ee{constructor(e){super(Xp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Xp.buildCount(e.source,e.filters)}sql;static[F]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return C`(select count(*) from ${e}${C.raw(" where ").if(t)}${t})`}static buildCount(e,t){return C`select count(*) from ${e}${C.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var S$,vb,b$;var b8=b(()=>{$e();Jo();Hp();S$=class S${constructor(e,t,r,o,n,i,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=o,this.table=n,this.tableConfig=i,this.dialect=s,this.session=a}static[F]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new b$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new vb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new b$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new vb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};vb=class vb extends vr{constructor(e,t,r,o,n,i,s,a,l){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=o,this.tableConfig=n,this.dialect=i,this.session=s,this.config=a,this.mode=l}static[F]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(o,n)=>{let i=o.map((s)=>ub(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return i[0];return i})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};b$=class b$ extends vb{static[F]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var Bl;var S8=b(()=>{$e();Jo();Bl=class Bl extends vr{constructor(e,t,r,o,n){super();this.execute=e,this.getSQL=t,this.dialect=o,this.mapBatchResult=n,this.config={action:r}}static[F]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var ef;var wb=b(()=>{$e();wa();Qt();y$();An();y8();b8();S8();ef=class ef{constructor(e,t,r,o){this.resultKind=e,this.dialect=t,this.session=r,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[i,s]of Object.entries(this._.schema))n[i]=new S$(e,o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[i],s,t,r);this.$cache={invalidate:async(i)=>{}}}static[F]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new xa(r.dialect));return new Proxy(new Up(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Xp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function o(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Sb(a,t.session,t.dialect,e)}function i(a){return new bb(a,t.session,t.dialect,e)}function s(a){return new fb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:o,update:n,insert:i,delete:s}}select(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Sb(e,this.session,this.dialect)}$cache;insert(e){return new bb(e,this.session,this.dialect)}delete(e){return new fb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Bl(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Bl(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Bl(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Bl(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}});async function v$(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(i)].map((l)=>l.toString(16).padStart(2,"0")).join("")}var v8,tf;var w$=b(()=>{$e();v8=class v8{static[F]="Cache"};tf=class tf extends v8{strategy(){return"all"}static[F]="NoopCache";async get(e){return}async put(e,t,r,o){}async onMutate(e){}}});var w8=b(()=>{w$()});function xb(e,t){return new Proxy(e,new va(t,!1))}var x8=b(()=>{Gp()});var _8,x$,_$,E$;var A$=b(()=>{w$();$e();mb();Jo();wb();_8=class _8 extends vr{constructor(e){super();this.resultCb=e}static[F]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};x$=class x${constructor(e,t,r,o,n,i){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=o,this.queryMetadata=n,this.cacheConfig=i,o&&o.strategy()==="all"&&i===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[F]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||oe(this.cache,tf)||this.queryMetadata===void 0)try{return await r()}catch(o){throw new Vo(e,t,o)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(o){throw new Vo(e,t,o)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[o]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return o}catch(o){throw new Vo(e,t,o)}if(!this.cacheConfig)try{return await r()}catch(o){throw new Vo(e,t,o)}if(this.queryMetadata.type==="select"){let o=await this.cache.get(this.cacheConfig.tag??await v$(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(o===void 0){let n;try{n=await r()}catch(i){throw new Vo(e,t,i)}return await this.cache.put(this.cacheConfig.tag??await v$(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return o}try{return await r()}catch(o){throw new Vo(e,t,o)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new _8(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}};_$=class _${constructor(e){this.dialect=e}static[F]="SQLiteSession";prepareOneTimeQuery(e,t,r,o,n,i,s){return this.prepareQuery(e,t,r,o,n,i,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new Zl({cause:r,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}};E$=class E$ extends ef{constructor(e,t,r,o,n=0){super(e,t,r,o);this.schema=o,this.nestedIndex=n}static[F]="SQLiteTransaction";rollback(){throw new c$}}});var I$,_ge,Ege,_b;var E8=b(()=>{$e();wa();Sr();yb();Ko();Yp();I$=class I${constructor(e){this.name=e}static[F]="SQLiteViewBuilderCore";config={}};_ge=class _ge extends I${static[F]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new xa);let t=new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new _b({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};Ege=class Ege extends I${static[F]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=sb(Qp(e,t))}existing(){return new Proxy(new _b({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new _b({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};_b=class _b extends Wo{static[F]="SQLiteView";constructor({config:e}){super(e)}}});var Eb=b(()=>{x8();e8();u$();wb();hb();QT();o8();s8();y$();A$();Ko();XT();Ll();E8()});function A8(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Ab(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var Ib,k$,I8;var R$=b(()=>{w8();$e();ab();Qt();Eb();A$();Sr();Ib=class Ib extends _${constructor(e,t,r,o,n){super(t);this.client=e,this.schema=r,this.options=o,this.tx=n,this.logger=o.logger??new FT,this.cache=o.cache??new tf}static[F]="LibSQLSession";logger;cache;prepareQuery(e,t,r,o,n,i,s){return new I8(this.client,e,this.logger,this.cache,i,s,t,this.tx,r,o,n)}async batch(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,i)=>t[i].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,i)=>t[i].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),o=new Ib(this.client,this.dialect,this.schema,this.options,r),n=new k$("async",this.dialect,o,this.schema);try{let i=await e(n);return await r.commit(),i}catch(i){throw await r.rollback(),i}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};k$=class k$ extends E${static[F]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new k$("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(C.raw(`savepoint ${t}`));try{let o=await e(r);return await this.session.run(C.raw(`release savepoint ${t}`)),o}catch(o){throw await this.session.run(C.raw(`rollback to savepoint ${t}`)),o}}};I8=class I8 extends x${constructor(e,t,r,o,n,i,s,a,l,u,d){super("async",l,t,o,n,i);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=u,this.customResultMapper=d,this.customResultMapper=d,this.fields=s}static[F]="LibSQLPreparedQuery";async run(e){let t=qp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=qp(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapAllResult(d))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>A8(r));if(this.customResultMapper)return this.customResultMapper(e,Ab);return e.map((r)=>UT(this.fields,Array.prototype.slice.call(r).map((o)=>Ab(o)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=qp(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapGetResult(d))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return A8(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Ab);return UT(this.fields,Array.prototype.slice.call(r).map((o)=>Ab(o)),this.joinsNotNullableMap)}async values(e){let t=qp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:o})=>o)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function Ul(e,t={}){let r=new p$({casing:t.casing}),o;if(t.logger===!0)o=new qT;else if(t.logger!==!1)o=t.logger;let n;if(t.schema){let a=h5(t.schema,y5);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let i=new Ib(e,r,n,{logger:o,cache:t.cache},void 0),s=new k8("async",r,i,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var k8;var R8=b(()=>{$e();ab();Hp();wb();hb();R$();k8=class k8 extends ef{static[F]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function kb(...e){if(typeof e[0]==="string"){let t=zl({url:e[0]});return Ul(t,e[1])}if(K3(e[0])){let{connection:t,client:r,...o}=e[0];if(r)return Ul(r,o);let n=typeof t==="string"?zl({url:t}):zl(t);return Ul(n,o)}return Ul(e[0],e[1])}var T8=b(()=>{$T();Sr();R8();((e)=>{function t(r){return Ul({},r)}e.mock=t})(kb||(kb={}))});var $8=b(()=>{T8();R$()});function Age(){return new Promise((e)=>setTimeout(e,0))}function kge(){if(T$)return;T$=!0,setTimeout(()=>{T$=!1,$$=performance.now()},0)}async function rf(e=Ige){if(kge(),performance.now()-$$<e)return;await Age(),$$=performance.now()}var Ige=50,$$,T$=!1;var O8=b(()=>{$$=performance.now()});function C8(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function Oge(e){return e instanceof Ce&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Rb(e,t){let r=Date.now()+(t.budgetMs??Rge),o=async(n)=>{if(t.isClosed())throw new Ce("The client is closed","CLIENT_CLOSED");try{return await e()}catch(i){if(t.isClosed()||!Oge(i))throw i;await t.afterRefusal?.();let s=Math.min(Tge*2**(n-1),$ge),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw i;if(await new Promise((l)=>setTimeout(l,a)),t.isClosed()||Date.now()>=r)throw i;return o(n+1)}};return o(1)}function O$(e,t={}){let r=zl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let o=r.transaction.bind(r),n=()=>r.closed,i=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),l=r.migrate.bind(r),u={isClosed:n,budgetMs:i,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function d(p,m){return await rf(),Rb(()=>typeof p==="string"?s(p,m):s(p),u)}r.execute=d,r.batch=async(p,m)=>(await rf(),Rb(()=>a(p,m),u)),r.migrate=async(p)=>(await rf(),Rb(()=>l(p),u)),r.transaction=async(p)=>(await rf(),Rb(()=>o(p),u))}return r}function Tb(e){let{url:t,schema:r}=e,o=C8(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},i=o?O$({url:t,authToken:o},n):O$({url:t},n);return{db:kb(i,{schema:r}),client:i,url:t}}async function $b(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var Rge=5000,Tge=5,$ge=40;var C$=b(()=>{$T();$8();O8()});var z8=b(()=>{JR();C$()});var z$=b(()=>{C$();z8()});var P$=b(()=>{Gp();eb();En();$e();mb();ab();Jo();Hp();l$();An();sr();Sr();qo()});var Y,Me;var N$=b(()=>{Eb();P$();hp();Y=Qp("job_queue",{id:ft("id").primaryKey().$defaultFn(()=>Lo()),type:ft("type").notNull(),data:ft("data").notNull(),result:ft("result",{mode:"json"}),progress:ft("progress",{mode:"json"}).$type(),source:ft("source"),metadata:ft("metadata",{mode:"json"}).$type().notNull(),status:ft("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:ar("priority").notNull().default(0),retryCount:ar("retryCount").notNull().default(0),maxRetries:ar("maxRetries").notNull().default(3),lastError:ft("lastError"),lastErrorPublic:ft("lastErrorPublic",{mode:"json"}),createdAt:ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:ar("startedAt"),completedAt:ar("completedAt"),attemptId:ft("attemptId"),workerSlotId:ft("workerSlotId"),workerSessionId:ft("workerSessionId"),leaseExpiresAt:ar("leaseExpiresAt"),attemptHeartbeatAt:ar("attemptHeartbeatAt"),runtimeUpdatedAt:ar("runtimeUpdatedAt"),brainVersion:ft("brainVersion"),brainVersionSortKey:ft("brainVersionSortKey")},(e)=>({queueReadyIdx:Ho("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Ho("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Ho("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Ho("idx_job_queue_source").on(e.source),rootJobIdx:Ho("idx_job_queue_root_job").on(C`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:Ho("idx_job_queue_deduplication").on(e.type,C`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),Me=Qp("job_worker_sessions",{slotId:ft("slotId").primaryKey(),sessionId:ft("sessionId").notNull().unique(),startedAt:ar("startedAt").notNull(),heartbeatAt:ar("heartbeatAt").notNull(),expiresAt:ar("expiresAt").notNull().default(0),brainVersion:ft("brainVersion"),brainVersionSortKey:ft("brainVersionSortKey"),stableSlotId:ft("stableSlotId")},(e)=>({heartbeatIdx:Ho("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Ho("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function P8(e){return Tb({url:e.url,schema:{jobQueue:Y,jobWorkerSessions:Me},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var N8=b(()=>{z$();N$()});class D${declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}class L${tails=new Map;async run(e,t){let r=this.tails.get(e),o=()=>{},n=new Promise((i)=>{o=i});this.tails.set(e,n),await r;try{return await t()}finally{if(o(),this.tails.get(e)===n)this.tails.delete(e)}}}class Z${findDuplicate(e,t,r){if(!t||t==="none")return null;let o=this.filterByDeduplicationKey(e,r).sort((i,s)=>s.createdAt-i.createdAt||s.id.localeCompare(i.id)),n=o.find((i)=>i.status===Oe.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??o[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let o=Cge.safeParse(r.metadata);return o.success&&o.data.deduplicationKey===t})}}var Cge;var D8=b(()=>{ue();Zo();Cge=c.looseObject({deduplicationKey:c.string().optional()})});function j8(e){return`${String(e.length).padStart(2,"0")}${e}`}function Pge(e){return zge.test(e)?`0${j8(e)}`:`1${e}`}function nf(e){let t=L8.exec(e);if(!t)throw Error(`Invalid brain version "${e}"`);let[,r="",o="",n="",i]=t,s=[r,o,n].map(j8).join("");return i===void 0?`${s}~`:`${s}-${i.split(".").map(Pge).join("!")}`}var L8,zge,Z8;var j$=b(()=>{ue();L8=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u,zge=/^\d+$/u,Z8=c.string().regex(L8,"Brain version must be a semver version")});function B8(e){return JSON.stringify(new Ci(e).toJSON())}class B${db;transactionClient;databaseUrl;logger;deduplicator=new Z$;writeRetryBudgetMs;constructor(e,t,r,o,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=o.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??Nge}async insert(e){await this.write("insert",async()=>this.db.insert(Y).values(e))}async enqueueAtomic(e){return jge.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let o=await this.runEnqueueTransaction(e,t,r);if(o.retry)return this.attemptEnqueue(e,t,r+1);return o.decision}async runEnqueueTransaction(e,t,r){let o=await this.acquireWriteTransaction(e,t),n={prepared:!1},i=!1;try{let s=await this.decideEnqueue(o,e,()=>{n.prepared=!0});return i=!0,await o.commit(),{retry:!1,decision:s}}catch(s){let a=i&&this.isSerializationConflict(s)&&!o.closed,l=!0;if(!o.closed)try{await o.rollback()}catch(u){l=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(n.prepared)e.onInsertRollback?.();if(!a||!l)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{o.close()}}async decideEnqueue(e,t,r){let{jobData:o,strategy:n,deduplicationKey:i,beforeInsert:s}=t,a=n??"none",l=async()=>{await s?.(),r()},u=async()=>{await l(),await this.insertJob(e,o)};if(a==="none")return await u(),{kind:"inserted",jobId:o.id};let d=await this.getActiveDeduplicationCandidates(e,o.type,i),p=this.deduplicator.findDuplicate(d,a,i);if(!p)return await u(),{kind:"inserted",jobId:o.id};if(a==="skip")return await this.raiseBrainVersion(e,p.id,o),{kind:"skipped",jobId:p.id};if(a==="coalesce"){if(await this.raiseBrainVersion(e,p.id,o),(await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),p.id,p.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${p.id}`);return{kind:"coalesced",jobId:p.id}}await l();let m=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `lastErrorPublic` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Oe.FAILED,"Replaced by newer job",B8("cancelled"),m,m,p.id,Oe.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${p.id}`);return await this.insertJob(e,o),{kind:"replaced",jobId:o.id,replacedJobId:p.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Oe.PENDING,Oe.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Oe.PENDING,Oe.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:o,metadata:n}=e;if(typeof t!=="string"||r!==Oe.PENDING&&r!==Oe.PROCESSING||typeof o!=="number"&&typeof o!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let i=JSON.parse(n);return{id:t,status:r,createdAt:Number(o),metadata:i}}async raiseBrainVersion(e,t,r){if(!r.brainVersion)return;let o=nf(r.brainVersion);await e.execute({sql:"UPDATE `job_queue`\n SET `brainVersion` = ?, `brainVersionSortKey` = ?\n WHERE `id` = ?\n AND (`brainVersionSortKey` IS NULL OR `brainVersionSortKey` < ?)",args:[r.brainVersion,o,t,o]})}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`, `brainVersion`, `brainVersionSortKey`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt,t.brainVersion??null,t.brainVersion?nf(t.brainVersion):null]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,o,n){let i=Math.min(Dge*2**(o-1),Lge),s=i/2+Math.random()*(i/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,o,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,o,n=Date.now()+this.writeRetryBudgetMs,i=1){try{return await r()}catch(s){if(!o(s))throw s;return await this.waitForConflictRetry(e,t,n,i,s),this.retryOnConflict(e,t,r,o,n,i+1)}}transactionConflictError(e,t,r,o){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:o});let n=t.strategy??"none",i=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${i})`,{cause:o})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let o=new Set;for(let n=r;n!==void 0&&!o.has(n);){if(o.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",o=Ve(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(o))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),o=Ki,n,i){let s=r+o,a={brainVersion:n??null,brainVersionSortKey:n?nf(n):null,stableSlotId:i??null};await this.write("start worker session",async()=>{await this.db.insert(Me).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}).onConflictDoUpdate({target:Me.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}}),await this.pruneDeadWorkerSessions(r,o)})}async heartbeatWorkerSession(e,t,r=Date.now(),o=Ki){return(await this.write("heartbeat worker session",async()=>{let i=await this.db.update(Me).set({heartbeatAt:r,expiresAt:r+o}).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId});return await this.pruneDeadWorkerSessions(r,o),i})).length===1}async pruneDeadWorkerSessions(e,t){let r=this.db.select({id:Y.id}).from(Y).where(tt(je(Y.workerSlotId,Me.slotId),je(Y.workerSessionId,Me.sessionId),je(Y.status,Oe.PROCESSING),In(Y.leaseExpiresAt,e)));await this.db.delete(Me).where(tt(os(Me.expiresAt,e-t),ss(r)))}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(Me).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId}))).length===1}async complete(e,t,r){let o=Date.now(),i=(await this.write("complete",async()=>this.db.update(Y).set({status:Oe.COMPLETED,result:t,lastError:null,lastErrorPublic:null,completedAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(i)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return i}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(Y).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,o=Date.now()){return(await this.write("record progress",async()=>this.db.update(Y).set({attemptHeartbeatAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async renewAttemptLease(e,t,r,o){return(await this.write("renew attempt lease",async()=>this.db.update(Y).set({attemptHeartbeatAt:r,leaseExpiresAt:r+o}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async release(e,t,r=Date.now()){return(await this.write("release",async()=>this.db.update(Y).set({status:Oe.PENDING,scheduledFor:r,startedAt:null,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async fail(e,t,r,o=Date.now()){let i=(await this.db.select({retryCount:Y.retryCount,maxRetries:Y.maxRetries,type:Y.type,scheduledFor:Y.scheduledFor,startedAt:Y.startedAt,runtimeUpdatedAt:Y.runtimeUpdatedAt}).from(Y).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!i)return!1;let s=i.retryCount<i.maxRetries,a=s?i.retryCount+1:i.retryCount,l=Math.min(1000*2**i.retryCount,60000),u=s?o+l:i.scheduledFor;if((await this.write("fail",async()=>this.db.update(Y).set({status:s?Oe.PENDING:Oe.FAILED,retryCount:a,lastError:t.message,lastErrorPublic:og(t).toJSON(),scheduledFor:u,completedAt:s?null:o,runtimeUpdatedAt:s?i.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),startedAt:s?null:i.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(tt(this.attemptWriteGuard(e,r),je(Y.retryCount,i.retryCount))).returning({id:Y.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:l,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:i.type,retryCount:i.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let o=(await this.write("retire unowned job",async()=>this.db.update(Y).set({status:Oe.FAILED,lastError:t,lastErrorPublic:new Ci("no_handler").toJSON(),completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(tt(je(Y.id,e.jobId),je(Y.type,e.expectedType),cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),qr(Y.attemptId),qr(Y.workerSlotId),qr(Y.workerSessionId),qr(Y.leaseExpiresAt),qr(Y.attemptHeartbeatAt),qr(Y.progress),qr(Y.result))).returning()))[0]??null;if(o)this.logger.warn("Retired unowned legacy job",{jobId:o.id,type:o.type,reason:t});return o}async getStatus(e){return(await this.db.select().from(Y).where(je(Y.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(Y).where(C`json_extract(${Y.metadata}, '$.rootJobId') = ${e}`).orderBy(Fo(Y.createdAt),Fo(Y.id))}async getStatusByEntityId(e){return(await this.db.select().from(Y).where(C`json_extract(${Y.data}, '$.id') = ${e}`).orderBy(Sa(Y.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let o=Number(r.count);t[r.status]=o,t.total+=o}return t}async getDiagnostics(e=Date.now()){let[t,r,o]=await Promise.all([this.db.select({type:Y.type,status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.type,Y.status),this.db.select({oldestPendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} then ${Y.createdAt} end)`,duePending:C`coalesce(sum(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then ${Y.scheduledFor} end)`,latestClaimAt:C`max(${Y.startedAt})`,oldestProcessingAt:C`min(case when ${Y.status} = ${Oe.PROCESSING} then ${Y.startedAt} end)`,staleLeaseCount:C`coalesce(sum(case when ${Y.status} = ${Oe.PROCESSING} and ${Y.leaseExpiresAt} is not null and ${Y.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(Y),this.db.select({total:C`count(*)`,active:C`coalesce(sum(case when ${Me.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:C`coalesce(sum(case when ${Me.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:C`max(${Me.heartbeatAt})`}).from(Me)]),n={pending:0,processing:0,completed:0,failed:0},i=t.map((u)=>{let d=Number(u.count);return n[u.status]+=d,{type:u.type,status:u.status,count:d}}),s=r[0],a=o[0],l=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:n,byType:i,oldestPendingAgeMs:l(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:l(s?.oldestDuePendingAt),latestClaimAgeMs:l(s?.latestClaimAt),oldestProcessingAgeMs:l(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:l(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=Zge.parse(t);if(r===0)return[];return(await this.db.select().from(Y).where(C`(${Y.runtimeUpdatedAt}, ${Y.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(Fo(Y.runtimeUpdatedAt),Fo(Y.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(Y).where(tt(cn(je(Y.status,Oe.COMPLETED),je(Y.status,Oe.FAILED)),os(Y.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),r=e&&e.length>0?tt(t,is(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(Sa(Y.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?is(Y.type,e):void 0;return this.db.select().from(Y).where(r).orderBy(Sa(Y.createdAt)).limit(t)}async getFailedJobs(e){let t=je(Y.status,Oe.FAILED),r=e&&e.length>0?tt(t,is(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(Sa(Y.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:o,workerSessionId:n,leaseDurationMs:i,executableTypes:s,exclusiveTypes:a=[],brainVersion:l}=e,u=l?this.brainVersionGate(l,t):{admissible:void 0,noNewerWorker:void 0},d=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,o),je(Me.sessionId,n),In(Me.expiresAt,t))),p=this.noNewerLiveInstance(o,n,t),m=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,Y.workerSlotId),je(Me.sessionId,Y.workerSessionId))),h=tt(je(Y.status,Oe.PROCESSING),cn(qr(Y.attemptId),ss(m),os(Y.leaseExpiresAt,t))),S=xb(Y,"running"),y=this.db.select({id:S.id}).from(S).where(tt(je(S.type,Y.type),je(S.status,Oe.PROCESSING),In(S.leaseExpiresAt,t),C`${S.id} <> ${Y.id}`)),v=a.length===0?void 0:cn(cb(Y.type,[...a]),ss(y)),x=C`${Y.status} = ${Oe.PROCESSING} AND ${Y.retryCount} + 1 > ${Y.maxRetries}`,_=this.db.select({id:Y.id}).from(Y).where(tt(is(Y.type,s),v,u.admissible,cn(tt(je(Y.status,Oe.PENDING),os(Y.scheduledFor,t)),h))).orderBy(Fo(Y.priority),Fo(Y.createdAt)).limit(1),O=(await this.write("claim",async()=>this.db.update(Y).set({status:C`CASE WHEN ${x} THEN ${Oe.FAILED} ELSE ${Oe.PROCESSING} END`,retryCount:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${Y.retryCount} + 1 ELSE ${Y.retryCount} END`,lastError:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN 'Attempt lease expired' ELSE ${Y.lastError} END`,lastErrorPublic:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${B8("deadline_exceeded")} ELSE ${Y.lastErrorPublic} END`,startedAt:C`CASE WHEN ${x} THEN ${Y.startedAt} ELSE ${t} END`,completedAt:C`CASE WHEN ${x} THEN ${t} ELSE NULL END`,attemptId:C`CASE WHEN ${x} THEN ${Y.attemptId} ELSE ${r} END`,workerSlotId:C`CASE WHEN ${x} THEN ${Y.workerSlotId} ELSE ${o} END`,workerSessionId:C`CASE WHEN ${x} THEN ${Y.workerSessionId} ELSE ${n} END`,leaseExpiresAt:C`CASE WHEN ${x} THEN ${Y.leaseExpiresAt} ELSE ${t+i} END`,attemptHeartbeatAt:C`CASE WHEN ${x} THEN ${Y.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:C`CASE WHEN ${x} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${Y.runtimeUpdatedAt} END`}).where(tt(is(Y.id,_),lb(d),p,u.noNewerWorker)).returning()))[0];if(!O)return null;if(O.status===Oe.FAILED)return O;return this.logger.debug("Job claimed",{jobId:O.id,attemptId:O.attemptId,workerSlotId:o,workerSessionId:n}),O}noNewerLiveInstance(e,t,r){let o=xb(Me,"claimer"),n=xb(Me,"peer"),i=this.db.select({slotId:n.slotId}).from(n).innerJoin(o,tt(je(o.slotId,e),je(o.sessionId,t))).where(tt(je(n.stableSlotId,o.stableSlotId),In(n.expiresAt,r),cn(In(n.startedAt,o.startedAt),tt(je(n.startedAt,o.startedAt),In(n.slotId,o.slotId)))));return ss(i)}brainVersionGate(e,t){let r=nf(e),o=this.db.select({slotId:Me.slotId}).from(Me).where(tt(In(Me.expiresAt,t),In(Me.brainVersionSortKey,r)));return{admissible:cn(qr(Y.brainVersionSortKey),os(Y.brainVersionSortKey,r)),noNewerWorker:ss(o)}}nextRuntimeUpdatedAt(e){return C`max(${e}, coalesce((select max(${Y.runtimeUpdatedAt}) from ${Y}), 0) + 1)`}attemptWriteGuard(e,t){return t?tt(je(Y.id,e),je(Y.status,Oe.PROCESSING),je(Y.attemptId,t)):tt(je(Y.id,e),qr(Y.attemptId),cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)))}}var Nge=2000,Dge=5,Lge=40,Zge,jge;var U8=b(()=>{P$();Eb();N$();wt();ue();Zo();yp();D8();j$();Zge=c.number().int().min(0).max(1000),jge=new L$});import{AsyncLocalStorage as Bge}from"async_hooks";class Ml{storage=new Bge;static createFresh(){return new Ml}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let o=To.parse(e),n=Uge(o);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function Uge(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var Ob=b(()=>{wt()});class of{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Lo()}`;directWorkerSessionId=Lo();directLeaseDurationMs;directSessionStart=null;brainVersion;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new of(e,t??Rr.getInstance(),r)}constructor(e,t,r){this.brainVersion=e.brainVersion===void 0?void 0:Z8.parse(e.brainVersion);let{db:o,client:n,url:i}=P8(e);this.client=n,this.databaseUrl=i,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Ml.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new D$(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new B$(o,n,i,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await $b(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:o}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let i=n.validateAndParse(r);if(i===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Lo(),l=o?.rootJobId??(o?.detached?a:this.operationContext.current()?.provenance.rootJobId)??a,u=this.createJobProvenance(a,l,o),d=o?.metadata??{operationType:"data_processing"},{provenance:p,...m}=d,h={id:a,type:t,data:JSON.stringify(i),status:Oe.PENDING,priority:o?.priority??0,maxRetries:o?.maxRetries??3,retryCount:0,source:o?.source??null,metadata:{...m,...o?.deduplicationKey&&{deduplicationKey:o.deduplicationKey},rootJobId:l,provenance:u},createdAt:s,scheduledFor:o?.delayMs?s+o.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null,brainVersion:this.brainVersion},S,y=()=>{S?.rollback(),S=void 0};try{let v=await this.repository.enqueueAtomic({jobData:h,strategy:o?.deduplication,deduplicationKey:o?.deduplicationKey,beforeInsert:async()=>{S=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:y});if(S?.commit(),S=void 0,v.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:v.jobId});else if(v.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:v.jobId});else{if(v.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:v.replacedJobId});this.logger.debug("Job enqueued",{id:v.jobId,type:t,priority:h.priority,rootJobId:h.metadata.rootJobId})}return v.jobId}catch(v){throw y(),this.logger.error("Failed to enqueue job",{type:t,error:Ve(v)}),v}}createJobProvenance(e,t,r){let o=this.operationContext.current(),n=r?.metadata.provenance??o?.provenance,i=n?.rootJobId===t?n:void 0,s=o?.provenance.rootJobId===t?o.operationId:void 0,a=r?.projection,l=a?[...i?.projectionLineage??[],a.id]:[...i?.projectionLineage??[]],u=a?.id??i?.projectionId;return To.parse({rootJobId:t,causationId:s??i?.causationId??e,...u?{projectionId:u}:{},projectionLineage:l,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:i?.sourceEntity?{sourceEntity:i.sourceEntity}:{},derivationDepth:l.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...o}=e??await this.getDirectClaimOptions(),n=Date.now(),i=await this.repository.claimNextReady({...o,workerSlotId:this.sessionSlotId(o.workerSlotId,o.workerSessionId),brainVersion:this.brainVersion,now:n,attemptId:Lo(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!i)return null;if(i.status===Oe.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:i.id,type:i.type,retryCount:i.retryCount}),await r?.(i),null;return this.logger.debug("Job dequeued",{id:i.id,type:i.type,priority:i.priority,retryCount:i.retryCount,attemptId:i.attemptId,workerSlotId:i.workerSlotId,workerSessionId:i.workerSessionId}),i}async startWorkerSession(e,t,r=Ki){await this.repository.startWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r,this.brainVersion,this.versionedSlotId(e))}heartbeatWorkerSession(e,t,r=Ki){return this.repository.heartbeatWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(this.sessionSlotId(e,t),t)}versionedSlotId(e){return this.brainVersion?`${e}@${this.brainVersion}`:e}sessionSlotId(e,t){return`${this.versionedSlotId(e)}#${t}`}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}release(e,t){return this.repository.release(e,t)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.sessionSlotId(this.directWorkerSlotId,this.directWorkerSessionId),this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs,this.brainVersion),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,o=Date.now()+(e.timeoutMs??30000),n=async(i)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),l=s.pending===0&&s.processing===0?i??Date.now():null;if(l!==null&&Date.now()-l>=t)return;if(Date.now()>=o)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(l)};return n(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}var M8=b(()=>{hp();JR();yp();Zo();z$();N8();U8();wt();Ob();j$()});var U$=()=>{};var q8=b(()=>{hp();Zo();yp();Zo();U$();Ob()});var F8=b(()=>{Zo();U$()});var Cb,J8;var M$=b(()=>{ue();Cb=c.object({success:c.boolean(),data:c.unknown().optional(),error:c.string().optional(),code:c.string().optional()}),J8=c.object({id:c.string().min(1),timestamp:c.string(),type:c.string().min(1),source:c.string().min(1),target:c.string().optional(),metadata:c.record(c.string(),c.unknown()).optional()})});var q8e;var K8=b(()=>{ue();M$();q8e=c.union([c.object({noop:c.literal(!0)}),Cb])});var zb=b(()=>{K8()});var H8=b(()=>{zb()});var V8=b(()=>{zb()});var W8=b(()=>{V8()});var aJe;var q$=b(()=>{ue();aJe=c.looseObject({issues:c.array(c.looseObject({message:c.string()})).optional()})});var G8=b(()=>{H8();zb();W8();q$();wt();Ob()});var Qge;var Q8=b(()=>{ue();M$();Qge=c.object({id:c.string().min(1),requestId:c.string().min(1),success:c.boolean(),data:c.unknown().optional(),error:c.object({message:c.string(),code:c.string().optional()}).optional(),timestamp:c.string().datetime()})});var AJe;var Y8=b(()=>{wt();AJe=new Ci("invalid_response").toJSON()});var X8=b(()=>{G8();Q8();q$();Y8()});var FJe;var eJ=b(()=>{ue();X8();gp();Zo();FJe=c.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},c.record(c.string(),c.unknown()))});var HJe;var tJ=b(()=>{ue();HJe=c.record(c.string(),c.unknown())});var rJ=b(()=>{wt();hp()});var nJ=b(()=>{M8();q8();F8();eJ();tJ();yp();Zo();gp();rJ()});var F$={};Lt(F$,{LEGACY_PROJECTION_JOB_TYPES:()=>iJ,LEGACY_PROJECTION_RETIREMENT_REASON:()=>aJ,legacyProjectionJobTypeSchema:()=>sJ,retireLegacyProjectionJob:()=>rye});import{existsSync as Xge}from"fs";import{resolve as eye}from"path";function oJ(e){return{id:e.id,type:e.type,status:e.status,retryCount:e.retryCount,maxRetries:e.maxRetries,createdAt:e.createdAt,startedAt:e.startedAt,completedAt:e.completedAt}}function tye(e,t){if(e.type!==t)throw Error(`Job ${e.id} has type ${e.type}; expected ${t}`);if(e.status!=="pending"&&e.status!=="processing")throw Error(`Job ${e.id} is already terminal (${e.status})`);if(e.attemptId!==null||e.workerSlotId!==null||e.workerSessionId!==null||e.leaseExpiresAt!==null||e.attemptHeartbeatAt!==null)throw Error(`Job ${e.id} still has attempt ownership`);if(e.progress!==null||e.result!=null)throw Error(`Job ${e.id} contains partial progress or a result`)}async function rye(e){let t=eye(e.databasePath);if(!Xge(t))throw Error(`Job database does not exist: ${t}`);let r=sJ.parse(e.jobType),o=of.createFresh({url:`file:${t}`});try{let n=await o.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(tye(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:oJ(n),retired:!1}}let i=`retire:${n.id}`;if(e.confirmation!==i)throw Error(`Refusing to retire ${n.id}; expected --confirm ${i}`);let s=await o.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:aJ,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:oJ(s),retired:!0}}finally{o.close()}}var iJ,sJ,aJ="Retired legacy projection job superseded by scheduler-owned projections";var J$=b(()=>{nJ();ue();iJ=["conversation-memory:project","skill:project","swot:derive","topic:project"],sJ=c.enum(iJ)});function Ut(e,t,r,o,n){return lJ.parse({id:e,operation:t,count:r,targetProbeCount:o,settleMs:n})}function fJ(e){return Db.parse(structuredClone(aye[e]))}function Lb(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function H$(e,t={}){let r=t.fetchImpl??fetch,o=t.now??(()=>new Date),n=t.timeoutMs??20000,i=o(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let l=await r(e,{method:"GET",signal:s.signal});return await l.arrayBuffer(),K$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:l.status,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:l.ok})}catch(l){return K$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:!1,error:lye(l)})}finally{clearTimeout(a)}}async function mJ(e,t){let r=Db.parse(e),o=[],n,i=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(l){n=`monitor: ${Pb(l)}`}if(!n)for(let l of r.phases)try{let u=uJ.parse(await t.executePhase(l,i));if(o.push(u),!u.success){n=`${l.id}: ${u.error??"phase failed"}`;break}}catch(u){let d=Pb(u);o.push({id:l.id,operation:l.operation,count:l.count,success:!1,error:d}),n=`${l.id}: ${d}`;break}}finally{try{if(s=dJ.parse(await t.cleanup(i)),!s.success&&!n)n=s.error??"cleanup failed"}catch(l){let u=Pb(l);s={success:!1,probesRemaining:0,error:u},n??=`cleanup: ${u}`}try{a=pJ.parse(await t.stopMonitoring())}catch(l){let u=Pb(l);a={health:[],runtime:[]},n??=`monitor: ${u}`}}return n??=cye(a,r.maximumExternalAiCalls??0),sye.parse({profile:r.profile,success:n===void 0&&o.length===r.phases.length&&s.success,baseline:i,phases:o,cleanup:s,metrics:a,...n?{failure:n}:{}})}function cye(e,t=0){let r=e.health.find((i)=>!i.ok);if(r)return`health: ${r.endpoint} unavailable`;let o=e.externalAiCalls??0;if(o>t)return t===0?`external AI: observed ${o} call(s)`:`external AI: observed ${o} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function lye(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function Pb(e){return Ve(e)}var Nb,cJ,lJ,Db,nye,K$,oye,uJ,dJ,iye,pJ,sye,aye;var V$=b(()=>{ue();Nb=c.enum(["regression","load","stress"]),cJ=c.enum(["add","update","rename","delete"]),lJ=c.object({id:c.string().min(1),operation:cJ,count:c.number().int().positive().max(700),targetProbeCount:c.number().int().min(0).max(700),settleMs:c.number().int().nonnegative().max(300000)}),Db=c.object({profile:Nb,maximumProbeCount:c.number().int().positive().max(700),maximumExternalAiCalls:c.number().int().nonnegative().max(1e4).optional(),phases:c.array(lJ).min(1)}),nye=c.object({entities:c.number().int().nonnegative(),notes:c.number().int().nonnegative(),version:c.string().min(1)}),K$=c.object({timestamp:c.iso.datetime(),endpoint:c.string().startsWith("/"),status:c.number().int().nonnegative(),durationMs:c.number().nonnegative(),ok:c.boolean(),error:c.string().optional()}),oye=c.object({timestamp:c.iso.datetime(),cpuPercent:c.number().nonnegative(),memoryPercent:c.number().nonnegative(),pids:c.number().int().nonnegative()}),uJ=c.object({id:c.string().min(1),operation:cJ,count:c.number().int().positive(),success:c.boolean(),commitLatencyMs:c.number().nonnegative().optional(),persistenceLatencyMs:c.number().nonnegative().optional(),error:c.string().optional()}),dJ=c.object({success:c.boolean(),probesRemaining:c.number().int().nonnegative(),finalEntities:c.number().int().nonnegative().optional(),finalNotes:c.number().int().nonnegative().optional(),contentTreeRestored:c.boolean().optional(),error:c.string().optional()}),iye=c.object({status:c.string(),restartCount:c.number().int().nonnegative(),oomKilled:c.boolean()}),pJ=c.object({health:c.array(K$),runtime:c.array(oye),externalAiCalls:c.number().int().nonnegative().optional(),container:iye.optional()}),sye=c.object({profile:Nb,success:c.boolean(),baseline:nye,phases:c.array(uJ),cleanup:dJ,metrics:pJ,failure:c.string().optional()}),aye={regression:{profile:"regression",maximumProbeCount:20,phases:[Ut("add20","add",20,20,0),Ut("update20","update",20,20,30000),Ut("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Ut("add50","add",50,50,0),Ut("add150","add",100,150,0),Ut("add350","add",200,350,0),Ut("update350a","update",350,350,45000),Ut("rename100","rename",100,350,45000),Ut("update350b","update",350,350,45000),Ut("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Ut("add50","add",50,50,0),Ut("add150","add",100,150,0),Ut("add350","add",200,350,0),Ut("add700","add",350,700,0),Ut("update700a","update",700,700,45000),Ut("rename200","rename",200,700,45000),Ut("update700b","update",700,700,45000),Ut("delete700","delete",700,0,150000)]}}});import{spawn as uye}from"child_process";async function hJ(e,t,r,o){let n=await e(t,r,o);if(n.exitCode!==0)throw co(t,r,n);return n}function co(e,t,r){let o=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${o?`: ${o}`:""}`)}var Go=async(e,t,r={})=>new Promise((o,n)=>{let i=uye(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",(l)=>{s+=l}),i.stderr.on("data",(l)=>{a+=l}),i.on("error",n),i.on("close",(l)=>{o({exitCode:l??1,stdout:s,stderr:a})}),i.stdin.end(r.stdin)});var sf=()=>{};class ql{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,o){let n=new ql(e,r,o);return await hJ(e,"git",["-c","credential.helper=","-c",`credential.helper=${gJ}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",gJ]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw co("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var gJ='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var yJ=b(()=>{sf()});function af(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class W${#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#o=!0;#i;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await H$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#o=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#i=Promise.all([this.#m(),this.#f()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#o=!0})}async stop(){this.#o=!0,await this.#i}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let o=this.#e.now().getTime();while(this.#e.now().getTime()-o<r){let n=await this.fetchHealthPayload();if(this.#p(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let o=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-o<r){let i=await this.fetchHealthPayload();if(this.#p(i,e,t)){if(n+=1,n===2)return i}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=await this.#d();if(e===void 0)return;let t=await this.#e.readEntityCounts();if(!t)return;return{version:e,entities:t.reduce((r,o)=>r+o.count,0),entityCounts:t}}async#d(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let o=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await o.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:o.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:o.ok}),!o.ok)return;return dye.parse(JSON.parse(n)).app.version}catch(o){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:o instanceof Error?`${o.name}: ${o.message}`:String(o)});return}finally{clearTimeout(r)}}#p(e,t,r){return e!==void 0&&(t===void 0||af(e)===t)&&(r===void 0||e.entities===r)}async#m(){while(!this.#o){for(let e of this.#n)this.#t.push(await H$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#f(){while(!this.#o){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var bJ,dye;var SJ=b(()=>{ue();V$();bJ=c.array(c.object({entityType:c.string(),count:c.number().int().nonnegative()})),dye=c.object({status:c.literal("ready"),operationalStatus:c.literal("operational"),app:c.object({version:c.string()})})});var Zb={};Lt(Zb,{applyDirectorySyncStressPhase:()=>_J,cleanupDirectorySyncStress:()=>xye,listProbeFiles:()=>_a,parseStressRuntimeSample:()=>EJ,removeProbeFiles:()=>rO,runDeployedDirectorySyncStress:()=>vye,runStressCommand:()=>Go,verifyDirectorySyncStressAccess:()=>wye});import{chmod as pye,mkdir as Q$,mkdtemp as Y$,readFile as fye,readdir as mye,rename as hye,rm as lf,writeFile as Tn}from"fs/promises";import{tmpdir as X$}from"os";import{join as ct,resolve as eO}from"path";async function vye(e){let t=e.now??(()=>new Date),r=t().toISOString(),o=nO(r),n=eO(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",o));await Q$(n,{recursive:!0});let{pilot:i,user:s}=await tO(e.rootDir,e.handle);Lb({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Nb.parse(e.profile),l=e.plan?Db.parse(e.plan):fJ(a);if(l.profile!==a)throw Error(`Directory-sync stress plan profile ${l.profile} does not match requested profile ${a}`);if((l.maximumExternalAiCalls??0)===0)xJ(s);let u=gye.parse(e.env??process.env),d=new wJ({runId:o,artifactsDir:n,user:s,githubOrg:i.githubOrg,serverLabel:`${i.contentRepoPrefix}${s.handle}`,environment:u,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??Go,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),p;try{p=await mJ(l,d)}finally{await d.dispose()}let m={runId:o,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:p};return await Aye(m),m}async function wye(e){let r=(e.now??(()=>new Date))().toISOString(),o=nO(r),n=eO(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`access-check-${o}`));await Q$(n,{recursive:!0});let{pilot:i,user:s}=await tO(e.rootDir,e.handle);Lb({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),xJ(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let l=await Y$(ct(X$(),"brains-ops-directory-sync-access-check-"));try{let u=await ql.clone(e.commandRunner??Go,`${i.githubOrg}/${s.contentRepo}`,ct(l,"content"),a),d=await u.output(["rev-parse","HEAD"]);await u.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${o}`]);let p={success:!0,artifactsDir:n,checkedAt:r,remoteHead:d,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`}};return await Tn(ct(n,"access-check.json"),`${JSON.stringify(p,null,2)}
|
|
459
|
-
`),p}finally{await lf(l,{recursive:!0,force:!0})}}async function
|
|
460
|
-
`),y}finally{await lf(l,{recursive:!0,force:!0})}}class wJ{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new W$({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#b(),readEntityCounts:()=>this.#y()})}async prepare(e){this.#r=await Y$(ct(X$(),"brains-ops-directory-sync-stress-"));let t=ct(this.#r,"content");this.#o=ct(this.#r,"id_ed25519"),this.#i=ct(this.#r,"known_hosts"),this.#a=await this.#m(),await Tn(this.#o,
|
|
459
|
+
`;await t.run(n);let s=(await t.values(C`SELECT id, hash, created_at FROM ${C.identifier(o)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let l of e)if(!s||Number(s[2])<l.folderMillis){for(let u of l.sql)await a.run(C.raw(u));await a.run(C`INSERT INTO ${C.identifier(o)} ("hash", "created_at") VALUES(${l.hash}, ${l.folderMillis})`)}})}}});var f$;var p8=b(()=>{$e();f$=class f${static[F]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function gb(e,t){return(r,o,...n)=>{let i=[o,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of i)if(!Fp(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(i)}}var Rn,f8,m$,Sge=()=>({union:vge,unionAll:wge,intersect:xge,except:_ge}),vge,wge,xge,_ge;var h$=b(()=>{$e();p8();Jo();wa();Qt();An();sr();Sr();qo();Ll();Yp();Rn=class Rn{static[F]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(oe(e,dt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((o)=>[o,e[o]]));else if(oe(e,Wo))r=e[pt].selectedFields;else if(oe(e,Ee))r={};else r=sb(e);return new m$({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};f8=class f8 extends f${static[F]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:o,dialect:n,withList:i,distinct:s}){super();this.config={withList:i,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=o,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=Jp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of kn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let o=this.tableName,n=Jp(t);for(let i of kn(t))this.usedTables.add(i);if(typeof n==="string"&&this.config.joins?.some((i)=>i.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof o==="string")this.config.fields={[o]:this.config.fields};if(typeof n==="string"&&!oe(t,Ee)){let i=oe(t,dt)?t._.selectedFields:oe(t,sn)?t[pt].selectedFields:t[ge.Symbol.Columns];this.config.fields[n]=i}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let o=typeof r==="function"?r(Sge()):r;if(!Fp(this.getSelectedFields(),o.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:o}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...kn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...kn(r.table));return new Proxy(new dt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new at({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};m$=class m$ extends f8{static[F]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=an(this.config.fields),r=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.all()}};J3(m$,[vr]);vge=gb("union",!1),wge=gb("union",!0),xge=gb("intersect",!1),_ge=gb("except",!1)});var xa;var yb=b(()=>{$e();wa();hb();An();h$();xa=class xa{static[F]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=oe(e,jl)?e:void 0,this.dialectConfig=oe(e,jl)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new Up(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function o(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:o}}select(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new d$(this.dialectConfig);return this.dialect}}});var bb,g$;var m8=b(()=>{$e();Jo();Qt();Ko();sr();Sr();Ll();yb();bb=class bb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let o={},n=this.table[ge.Symbol.Columns];for(let i of Object.keys(r)){let s=r[i];o[i]=oe(s,Ee)?s:new Mr(s,n[i])}return o});return new g$(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new xa):e;if(!oe(t,Ee)&&!Fp(this.table[nb],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new g$(this.table,t,this.session,this.dialect,this.withList,!0)}};g$=class g$ extends vr{constructor(e,t,r,o,n,i){super();this.session=r,this.dialect=o,this.config={table:e,values:t,withList:n,select:i}}static[F]="SQLiteInsert";config;returning(e=this.config.table[Rt.Symbol.Columns]){return this.config.returning=an(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(C` on conflict do nothing`);else{let t=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,r=e.where?C` where ${e.where}`:C``;this.config.onConflict.push(C` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?C` where ${e.where}`:void 0,r=e.targetWhere?C` where ${e.targetWhere}`:void 0,o=e.setWhere?C` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,i=this.dialect.buildUpdateSet(this.config.table,ib(this.config.table,e.set));return this.config.onConflict.push(C` on conflict ${n}${r} do update set ${i}${t}${o}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:kn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var Sb,h8;var g8=b(()=>{$e();Jo();wa();Ko();An();sr();Sr();qo();Ll();Yp();Sb=class Sb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteUpdateBuilder";set(e){return new h8(this.table,ib(this.table,e),this.session,this.dialect,this.withList)}};h8=class h8 extends vr{constructor(e,t,r,o,n){super();this.session=r,this.dialect=o,this.config={set:t,table:e,withList:n,joins:[]}}static[F]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let o=Jp(t);if(typeof o==="string"&&this.config.joins.some((n)=>n.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?oe(t,Rt)?t[ge.Symbol.Columns]:oe(t,dt)?t._.selectedFields:oe(t,Wo)?t[pt].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[ge.Symbol.Columns],new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:o}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[ge.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[Rt.Symbol.Columns]){return this.config.returning=an(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:kn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var y$=b(()=>{a8();m8();yb();h$();g8()});var Xp;var y8=b(()=>{$e();Qt();Xp=class Xp extends Ee{constructor(e){super(Xp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Xp.buildCount(e.source,e.filters)}sql;static[F]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return C`(select count(*) from ${e}${C.raw(" where ").if(t)}${t})`}static buildCount(e,t){return C`select count(*) from ${e}${C.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var S$,vb,b$;var b8=b(()=>{$e();Jo();Hp();S$=class S${constructor(e,t,r,o,n,i,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=o,this.table=n,this.tableConfig=i,this.dialect=s,this.session=a}static[F]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new b$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new vb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new b$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new vb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};vb=class vb extends vr{constructor(e,t,r,o,n,i,s,a,l){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=o,this.tableConfig=n,this.dialect=i,this.session=s,this.config=a,this.mode=l}static[F]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(o,n)=>{let i=o.map((s)=>ub(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return i[0];return i})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};b$=class b$ extends vb{static[F]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var Bl;var S8=b(()=>{$e();Jo();Bl=class Bl extends vr{constructor(e,t,r,o,n){super();this.execute=e,this.getSQL=t,this.dialect=o,this.mapBatchResult=n,this.config={action:r}}static[F]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var ef;var wb=b(()=>{$e();wa();Qt();y$();An();y8();b8();S8();ef=class ef{constructor(e,t,r,o){this.resultKind=e,this.dialect=t,this.session=r,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[i,s]of Object.entries(this._.schema))n[i]=new S$(e,o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[i],s,t,r);this.$cache={invalidate:async(i)=>{}}}static[F]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new xa(r.dialect));return new Proxy(new Up(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Xp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function o(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Sb(a,t.session,t.dialect,e)}function i(a){return new bb(a,t.session,t.dialect,e)}function s(a){return new fb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:o,update:n,insert:i,delete:s}}select(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Sb(e,this.session,this.dialect)}$cache;insert(e){return new bb(e,this.session,this.dialect)}delete(e){return new fb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Bl(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Bl(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Bl(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Bl(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}});async function v$(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(i)].map((l)=>l.toString(16).padStart(2,"0")).join("")}var v8,tf;var w$=b(()=>{$e();v8=class v8{static[F]="Cache"};tf=class tf extends v8{strategy(){return"all"}static[F]="NoopCache";async get(e){return}async put(e,t,r,o){}async onMutate(e){}}});var w8=b(()=>{w$()});function xb(e,t){return new Proxy(e,new va(t,!1))}var x8=b(()=>{Gp()});var _8,x$,_$,E$;var A$=b(()=>{w$();$e();mb();Jo();wb();_8=class _8 extends vr{constructor(e){super();this.resultCb=e}static[F]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};x$=class x${constructor(e,t,r,o,n,i){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=o,this.queryMetadata=n,this.cacheConfig=i,o&&o.strategy()==="all"&&i===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[F]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||oe(this.cache,tf)||this.queryMetadata===void 0)try{return await r()}catch(o){throw new Vo(e,t,o)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(o){throw new Vo(e,t,o)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[o]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return o}catch(o){throw new Vo(e,t,o)}if(!this.cacheConfig)try{return await r()}catch(o){throw new Vo(e,t,o)}if(this.queryMetadata.type==="select"){let o=await this.cache.get(this.cacheConfig.tag??await v$(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(o===void 0){let n;try{n=await r()}catch(i){throw new Vo(e,t,i)}return await this.cache.put(this.cacheConfig.tag??await v$(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return o}try{return await r()}catch(o){throw new Vo(e,t,o)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new _8(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}};_$=class _${constructor(e){this.dialect=e}static[F]="SQLiteSession";prepareOneTimeQuery(e,t,r,o,n,i,s){return this.prepareQuery(e,t,r,o,n,i,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new Zl({cause:r,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}};E$=class E$ extends ef{constructor(e,t,r,o,n=0){super(e,t,r,o);this.schema=o,this.nestedIndex=n}static[F]="SQLiteTransaction";rollback(){throw new c$}}});var I$,Ege,Age,_b;var E8=b(()=>{$e();wa();Sr();yb();Ko();Yp();I$=class I${constructor(e){this.name=e}static[F]="SQLiteViewBuilderCore";config={}};Ege=class Ege extends I${static[F]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new xa);let t=new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new _b({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};Age=class Age extends I${static[F]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=sb(Qp(e,t))}existing(){return new Proxy(new _b({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new _b({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};_b=class _b extends Wo{static[F]="SQLiteView";constructor({config:e}){super(e)}}});var Eb=b(()=>{x8();e8();u$();wb();hb();QT();o8();s8();y$();A$();Ko();XT();Ll();E8()});function A8(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Ab(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var Ib,k$,I8;var R$=b(()=>{w8();$e();ab();Qt();Eb();A$();Sr();Ib=class Ib extends _${constructor(e,t,r,o,n){super(t);this.client=e,this.schema=r,this.options=o,this.tx=n,this.logger=o.logger??new FT,this.cache=o.cache??new tf}static[F]="LibSQLSession";logger;cache;prepareQuery(e,t,r,o,n,i,s){return new I8(this.client,e,this.logger,this.cache,i,s,t,this.tx,r,o,n)}async batch(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,i)=>t[i].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,i)=>t[i].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),o=new Ib(this.client,this.dialect,this.schema,this.options,r),n=new k$("async",this.dialect,o,this.schema);try{let i=await e(n);return await r.commit(),i}catch(i){throw await r.rollback(),i}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};k$=class k$ extends E${static[F]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new k$("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(C.raw(`savepoint ${t}`));try{let o=await e(r);return await this.session.run(C.raw(`release savepoint ${t}`)),o}catch(o){throw await this.session.run(C.raw(`rollback to savepoint ${t}`)),o}}};I8=class I8 extends x${constructor(e,t,r,o,n,i,s,a,l,u,d){super("async",l,t,o,n,i);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=u,this.customResultMapper=d,this.customResultMapper=d,this.fields=s}static[F]="LibSQLPreparedQuery";async run(e){let t=qp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=qp(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapAllResult(d))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>A8(r));if(this.customResultMapper)return this.customResultMapper(e,Ab);return e.map((r)=>UT(this.fields,Array.prototype.slice.call(r).map((o)=>Ab(o)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=qp(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapGetResult(d))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return A8(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Ab);return UT(this.fields,Array.prototype.slice.call(r).map((o)=>Ab(o)),this.joinsNotNullableMap)}async values(e){let t=qp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:o})=>o)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function Ul(e,t={}){let r=new p$({casing:t.casing}),o;if(t.logger===!0)o=new qT;else if(t.logger!==!1)o=t.logger;let n;if(t.schema){let a=h5(t.schema,y5);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let i=new Ib(e,r,n,{logger:o,cache:t.cache},void 0),s=new k8("async",r,i,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var k8;var R8=b(()=>{$e();ab();Hp();wb();hb();R$();k8=class k8 extends ef{static[F]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function kb(...e){if(typeof e[0]==="string"){let t=zl({url:e[0]});return Ul(t,e[1])}if(K3(e[0])){let{connection:t,client:r,...o}=e[0];if(r)return Ul(r,o);let n=typeof t==="string"?zl({url:t}):zl(t);return Ul(n,o)}return Ul(e[0],e[1])}var T8=b(()=>{$T();Sr();R8();((e)=>{function t(r){return Ul({},r)}e.mock=t})(kb||(kb={}))});var $8=b(()=>{T8();R$()});function Ige(){return new Promise((e)=>setTimeout(e,0))}function Rge(){if(T$)return;T$=!0,setTimeout(()=>{T$=!1,$$=performance.now()},0)}async function rf(e=kge){if(Rge(),performance.now()-$$<e)return;await Ige(),$$=performance.now()}var kge=50,$$,T$=!1;var O8=b(()=>{$$=performance.now()});function C8(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function Cge(e){return e instanceof Ce&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Rb(e,t){let r=Date.now()+(t.budgetMs??Tge),o=async(n)=>{if(t.isClosed())throw new Ce("The client is closed","CLIENT_CLOSED");try{return await e()}catch(i){if(t.isClosed()||!Cge(i))throw i;await t.afterRefusal?.();let s=Math.min($ge*2**(n-1),Oge),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw i;if(await new Promise((l)=>setTimeout(l,a)),t.isClosed()||Date.now()>=r)throw i;return o(n+1)}};return o(1)}function O$(e,t={}){let r=zl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let o=r.transaction.bind(r),n=()=>r.closed,i=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),l=r.migrate.bind(r),u={isClosed:n,budgetMs:i,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function d(p,m){return await rf(),Rb(()=>typeof p==="string"?s(p,m):s(p),u)}r.execute=d,r.batch=async(p,m)=>(await rf(),Rb(()=>a(p,m),u)),r.migrate=async(p)=>(await rf(),Rb(()=>l(p),u)),r.transaction=async(p)=>(await rf(),Rb(()=>o(p),u))}return r}function Tb(e){let{url:t,schema:r}=e,o=C8(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},i=o?O$({url:t,authToken:o},n):O$({url:t},n);return{db:kb(i,{schema:r}),client:i,url:t}}async function $b(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var Tge=5000,$ge=5,Oge=40;var C$=b(()=>{$T();$8();O8()});var z8=b(()=>{JR();C$()});var z$=b(()=>{C$();z8()});var P$=b(()=>{Gp();eb();En();$e();mb();ab();Jo();Hp();l$();An();sr();Sr();qo()});var Y,Me;var N$=b(()=>{Eb();P$();hp();Y=Qp("job_queue",{id:ft("id").primaryKey().$defaultFn(()=>Lo()),type:ft("type").notNull(),data:ft("data").notNull(),result:ft("result",{mode:"json"}),progress:ft("progress",{mode:"json"}).$type(),source:ft("source"),metadata:ft("metadata",{mode:"json"}).$type().notNull(),status:ft("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:ar("priority").notNull().default(0),retryCount:ar("retryCount").notNull().default(0),maxRetries:ar("maxRetries").notNull().default(3),lastError:ft("lastError"),lastErrorPublic:ft("lastErrorPublic",{mode:"json"}),createdAt:ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:ar("startedAt"),completedAt:ar("completedAt"),attemptId:ft("attemptId"),workerSlotId:ft("workerSlotId"),workerSessionId:ft("workerSessionId"),leaseExpiresAt:ar("leaseExpiresAt"),attemptHeartbeatAt:ar("attemptHeartbeatAt"),runtimeUpdatedAt:ar("runtimeUpdatedAt"),brainVersion:ft("brainVersion"),brainVersionSortKey:ft("brainVersionSortKey")},(e)=>({queueReadyIdx:Ho("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Ho("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Ho("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Ho("idx_job_queue_source").on(e.source),rootJobIdx:Ho("idx_job_queue_root_job").on(C`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:Ho("idx_job_queue_deduplication").on(e.type,C`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),Me=Qp("job_worker_sessions",{slotId:ft("slotId").primaryKey(),sessionId:ft("sessionId").notNull().unique(),startedAt:ar("startedAt").notNull(),heartbeatAt:ar("heartbeatAt").notNull(),expiresAt:ar("expiresAt").notNull().default(0),brainVersion:ft("brainVersion"),brainVersionSortKey:ft("brainVersionSortKey"),stableSlotId:ft("stableSlotId")},(e)=>({heartbeatIdx:Ho("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Ho("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function P8(e){return Tb({url:e.url,schema:{jobQueue:Y,jobWorkerSessions:Me},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var N8=b(()=>{z$();N$()});class D${declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}class L${tails=new Map;async run(e,t){let r=this.tails.get(e),o=()=>{},n=new Promise((i)=>{o=i});this.tails.set(e,n),await r;try{return await t()}finally{if(o(),this.tails.get(e)===n)this.tails.delete(e)}}}class Z${findDuplicate(e,t,r){if(!t||t==="none")return null;let o=this.filterByDeduplicationKey(e,r).sort((i,s)=>s.createdAt-i.createdAt||s.id.localeCompare(i.id)),n=o.find((i)=>i.status===Oe.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??o[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let o=zge.safeParse(r.metadata);return o.success&&o.data.deduplicationKey===t})}}var zge;var D8=b(()=>{ue();Zo();zge=c.looseObject({deduplicationKey:c.string().optional()})});function j8(e){return`${String(e.length).padStart(2,"0")}${e}`}function Nge(e){return Pge.test(e)?`0${j8(e)}`:`1${e}`}function nf(e){let t=L8.exec(e);if(!t)throw Error(`Invalid brain version "${e}"`);let[,r="",o="",n="",i]=t,s=[r,o,n].map(j8).join("");return i===void 0?`${s}~`:`${s}-${i.split(".").map(Nge).join("!")}`}var L8,Pge,Z8;var j$=b(()=>{ue();L8=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u,Pge=/^\d+$/u,Z8=c.string().regex(L8,"Brain version must be a semver version")});function B8(e){return JSON.stringify(new Ci(e).toJSON())}class B${db;transactionClient;databaseUrl;logger;deduplicator=new Z$;writeRetryBudgetMs;constructor(e,t,r,o,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=o.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??Dge}async insert(e){await this.write("insert",async()=>this.db.insert(Y).values(e))}async enqueueAtomic(e){return Bge.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let o=await this.runEnqueueTransaction(e,t,r);if(o.retry)return this.attemptEnqueue(e,t,r+1);return o.decision}async runEnqueueTransaction(e,t,r){let o=await this.acquireWriteTransaction(e,t),n={prepared:!1},i=!1;try{let s=await this.decideEnqueue(o,e,()=>{n.prepared=!0});return i=!0,await o.commit(),{retry:!1,decision:s}}catch(s){let a=i&&this.isSerializationConflict(s)&&!o.closed,l=!0;if(!o.closed)try{await o.rollback()}catch(u){l=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(n.prepared)e.onInsertRollback?.();if(!a||!l)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{o.close()}}async decideEnqueue(e,t,r){let{jobData:o,strategy:n,deduplicationKey:i,beforeInsert:s}=t,a=n??"none",l=async()=>{await s?.(),r()},u=async()=>{await l(),await this.insertJob(e,o)};if(a==="none")return await u(),{kind:"inserted",jobId:o.id};let d=await this.getActiveDeduplicationCandidates(e,o.type,i),p=this.deduplicator.findDuplicate(d,a,i);if(!p)return await u(),{kind:"inserted",jobId:o.id};if(a==="skip")return await this.raiseBrainVersion(e,p.id,o),{kind:"skipped",jobId:p.id};if(a==="coalesce"){if(await this.raiseBrainVersion(e,p.id,o),(await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),p.id,p.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${p.id}`);return{kind:"coalesced",jobId:p.id}}await l();let m=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `lastErrorPublic` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Oe.FAILED,"Replaced by newer job",B8("cancelled"),m,m,p.id,Oe.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${p.id}`);return await this.insertJob(e,o),{kind:"replaced",jobId:o.id,replacedJobId:p.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Oe.PENDING,Oe.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Oe.PENDING,Oe.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:o,metadata:n}=e;if(typeof t!=="string"||r!==Oe.PENDING&&r!==Oe.PROCESSING||typeof o!=="number"&&typeof o!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let i=JSON.parse(n);return{id:t,status:r,createdAt:Number(o),metadata:i}}async raiseBrainVersion(e,t,r){if(!r.brainVersion)return;let o=nf(r.brainVersion);await e.execute({sql:"UPDATE `job_queue`\n SET `brainVersion` = ?, `brainVersionSortKey` = ?\n WHERE `id` = ?\n AND (`brainVersionSortKey` IS NULL OR `brainVersionSortKey` < ?)",args:[r.brainVersion,o,t,o]})}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`, `brainVersion`, `brainVersionSortKey`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt,t.brainVersion??null,t.brainVersion?nf(t.brainVersion):null]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,o,n){let i=Math.min(Lge*2**(o-1),Zge),s=i/2+Math.random()*(i/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,o,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,o,n=Date.now()+this.writeRetryBudgetMs,i=1){try{return await r()}catch(s){if(!o(s))throw s;return await this.waitForConflictRetry(e,t,n,i,s),this.retryOnConflict(e,t,r,o,n,i+1)}}transactionConflictError(e,t,r,o){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:o});let n=t.strategy??"none",i=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${i})`,{cause:o})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let o=new Set;for(let n=r;n!==void 0&&!o.has(n);){if(o.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",o=Ve(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(o))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),o=Ki,n,i){let s=r+o,a={brainVersion:n??null,brainVersionSortKey:n?nf(n):null,stableSlotId:i??null};await this.write("start worker session",async()=>{await this.db.insert(Me).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}).onConflictDoUpdate({target:Me.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}}),await this.pruneDeadWorkerSessions(r,o)})}async heartbeatWorkerSession(e,t,r=Date.now(),o=Ki){return(await this.write("heartbeat worker session",async()=>{let i=await this.db.update(Me).set({heartbeatAt:r,expiresAt:r+o}).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId});return await this.pruneDeadWorkerSessions(r,o),i})).length===1}async pruneDeadWorkerSessions(e,t){let r=this.db.select({id:Y.id}).from(Y).where(tt(je(Y.workerSlotId,Me.slotId),je(Y.workerSessionId,Me.sessionId),je(Y.status,Oe.PROCESSING),In(Y.leaseExpiresAt,e)));await this.db.delete(Me).where(tt(os(Me.expiresAt,e-t),ss(r)))}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(Me).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId}))).length===1}async complete(e,t,r){let o=Date.now(),i=(await this.write("complete",async()=>this.db.update(Y).set({status:Oe.COMPLETED,result:t,lastError:null,lastErrorPublic:null,completedAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(i)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return i}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(Y).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,o=Date.now()){return(await this.write("record progress",async()=>this.db.update(Y).set({attemptHeartbeatAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async renewAttemptLease(e,t,r,o){return(await this.write("renew attempt lease",async()=>this.db.update(Y).set({attemptHeartbeatAt:r,leaseExpiresAt:r+o}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async release(e,t,r=Date.now()){return(await this.write("release",async()=>this.db.update(Y).set({status:Oe.PENDING,scheduledFor:r,startedAt:null,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async fail(e,t,r,o=Date.now()){let i=(await this.db.select({retryCount:Y.retryCount,maxRetries:Y.maxRetries,type:Y.type,scheduledFor:Y.scheduledFor,startedAt:Y.startedAt,runtimeUpdatedAt:Y.runtimeUpdatedAt}).from(Y).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!i)return!1;let s=i.retryCount<i.maxRetries,a=s?i.retryCount+1:i.retryCount,l=Math.min(1000*2**i.retryCount,60000),u=s?o+l:i.scheduledFor;if((await this.write("fail",async()=>this.db.update(Y).set({status:s?Oe.PENDING:Oe.FAILED,retryCount:a,lastError:t.message,lastErrorPublic:og(t).toJSON(),scheduledFor:u,completedAt:s?null:o,runtimeUpdatedAt:s?i.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),startedAt:s?null:i.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(tt(this.attemptWriteGuard(e,r),je(Y.retryCount,i.retryCount))).returning({id:Y.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:l,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:i.type,retryCount:i.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let o=(await this.write("retire unowned job",async()=>this.db.update(Y).set({status:Oe.FAILED,lastError:t,lastErrorPublic:new Ci("no_handler").toJSON(),completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(tt(je(Y.id,e.jobId),je(Y.type,e.expectedType),cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),qr(Y.attemptId),qr(Y.workerSlotId),qr(Y.workerSessionId),qr(Y.leaseExpiresAt),qr(Y.attemptHeartbeatAt),qr(Y.progress),qr(Y.result))).returning()))[0]??null;if(o)this.logger.warn("Retired unowned legacy job",{jobId:o.id,type:o.type,reason:t});return o}async getStatus(e){return(await this.db.select().from(Y).where(je(Y.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(Y).where(C`json_extract(${Y.metadata}, '$.rootJobId') = ${e}`).orderBy(Fo(Y.createdAt),Fo(Y.id))}async getStatusByEntityId(e){return(await this.db.select().from(Y).where(C`json_extract(${Y.data}, '$.id') = ${e}`).orderBy(Sa(Y.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let o=Number(r.count);t[r.status]=o,t.total+=o}return t}async getDiagnostics(e=Date.now()){let[t,r,o]=await Promise.all([this.db.select({type:Y.type,status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.type,Y.status),this.db.select({oldestPendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} then ${Y.createdAt} end)`,duePending:C`coalesce(sum(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then ${Y.scheduledFor} end)`,latestClaimAt:C`max(${Y.startedAt})`,oldestProcessingAt:C`min(case when ${Y.status} = ${Oe.PROCESSING} then ${Y.startedAt} end)`,staleLeaseCount:C`coalesce(sum(case when ${Y.status} = ${Oe.PROCESSING} and ${Y.leaseExpiresAt} is not null and ${Y.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(Y),this.db.select({total:C`count(*)`,active:C`coalesce(sum(case when ${Me.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:C`coalesce(sum(case when ${Me.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:C`max(${Me.heartbeatAt})`}).from(Me)]),n={pending:0,processing:0,completed:0,failed:0},i=t.map((u)=>{let d=Number(u.count);return n[u.status]+=d,{type:u.type,status:u.status,count:d}}),s=r[0],a=o[0],l=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:n,byType:i,oldestPendingAgeMs:l(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:l(s?.oldestDuePendingAt),latestClaimAgeMs:l(s?.latestClaimAt),oldestProcessingAgeMs:l(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:l(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=jge.parse(t);if(r===0)return[];return(await this.db.select().from(Y).where(C`(${Y.runtimeUpdatedAt}, ${Y.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(Fo(Y.runtimeUpdatedAt),Fo(Y.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(Y).where(tt(cn(je(Y.status,Oe.COMPLETED),je(Y.status,Oe.FAILED)),os(Y.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),r=e&&e.length>0?tt(t,is(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(Sa(Y.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?is(Y.type,e):void 0;return this.db.select().from(Y).where(r).orderBy(Sa(Y.createdAt)).limit(t)}async getFailedJobs(e){let t=je(Y.status,Oe.FAILED),r=e&&e.length>0?tt(t,is(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(Sa(Y.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:o,workerSessionId:n,leaseDurationMs:i,executableTypes:s,exclusiveTypes:a=[],brainVersion:l}=e,u=l?this.brainVersionGate(l,t):{admissible:void 0,noNewerWorker:void 0},d=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,o),je(Me.sessionId,n),In(Me.expiresAt,t))),p=this.noNewerLiveInstance(o,n,t),m=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,Y.workerSlotId),je(Me.sessionId,Y.workerSessionId))),h=tt(je(Y.status,Oe.PROCESSING),cn(qr(Y.attemptId),ss(m),os(Y.leaseExpiresAt,t))),S=xb(Y,"running"),y=this.db.select({id:S.id}).from(S).where(tt(je(S.type,Y.type),je(S.status,Oe.PROCESSING),In(S.leaseExpiresAt,t),C`${S.id} <> ${Y.id}`)),v=a.length===0?void 0:cn(cb(Y.type,[...a]),ss(y)),x=C`${Y.status} = ${Oe.PROCESSING} AND ${Y.retryCount} + 1 > ${Y.maxRetries}`,_=this.db.select({id:Y.id}).from(Y).where(tt(is(Y.type,s),v,u.admissible,cn(tt(je(Y.status,Oe.PENDING),os(Y.scheduledFor,t)),h))).orderBy(Fo(Y.priority),Fo(Y.createdAt)).limit(1),O=(await this.write("claim",async()=>this.db.update(Y).set({status:C`CASE WHEN ${x} THEN ${Oe.FAILED} ELSE ${Oe.PROCESSING} END`,retryCount:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${Y.retryCount} + 1 ELSE ${Y.retryCount} END`,lastError:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN 'Attempt lease expired' ELSE ${Y.lastError} END`,lastErrorPublic:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${B8("deadline_exceeded")} ELSE ${Y.lastErrorPublic} END`,startedAt:C`CASE WHEN ${x} THEN ${Y.startedAt} ELSE ${t} END`,completedAt:C`CASE WHEN ${x} THEN ${t} ELSE NULL END`,attemptId:C`CASE WHEN ${x} THEN ${Y.attemptId} ELSE ${r} END`,workerSlotId:C`CASE WHEN ${x} THEN ${Y.workerSlotId} ELSE ${o} END`,workerSessionId:C`CASE WHEN ${x} THEN ${Y.workerSessionId} ELSE ${n} END`,leaseExpiresAt:C`CASE WHEN ${x} THEN ${Y.leaseExpiresAt} ELSE ${t+i} END`,attemptHeartbeatAt:C`CASE WHEN ${x} THEN ${Y.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:C`CASE WHEN ${x} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${Y.runtimeUpdatedAt} END`}).where(tt(is(Y.id,_),lb(d),p,u.noNewerWorker)).returning()))[0];if(!O)return null;if(O.status===Oe.FAILED)return O;return this.logger.debug("Job claimed",{jobId:O.id,attemptId:O.attemptId,workerSlotId:o,workerSessionId:n}),O}noNewerLiveInstance(e,t,r){let o=xb(Me,"claimer"),n=xb(Me,"peer"),i=this.db.select({slotId:n.slotId}).from(n).innerJoin(o,tt(je(o.slotId,e),je(o.sessionId,t))).where(tt(je(n.stableSlotId,o.stableSlotId),In(n.expiresAt,r),cn(In(n.startedAt,o.startedAt),tt(je(n.startedAt,o.startedAt),In(n.slotId,o.slotId)))));return ss(i)}brainVersionGate(e,t){let r=nf(e),o=this.db.select({slotId:Me.slotId}).from(Me).where(tt(In(Me.expiresAt,t),In(Me.brainVersionSortKey,r)));return{admissible:cn(qr(Y.brainVersionSortKey),os(Y.brainVersionSortKey,r)),noNewerWorker:ss(o)}}nextRuntimeUpdatedAt(e){return C`max(${e}, coalesce((select max(${Y.runtimeUpdatedAt}) from ${Y}), 0) + 1)`}attemptWriteGuard(e,t){return t?tt(je(Y.id,e),je(Y.status,Oe.PROCESSING),je(Y.attemptId,t)):tt(je(Y.id,e),qr(Y.attemptId),cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)))}}var Dge=2000,Lge=5,Zge=40,jge,Bge;var U8=b(()=>{P$();Eb();N$();wt();ue();Zo();yp();D8();j$();jge=c.number().int().min(0).max(1000),Bge=new L$});import{AsyncLocalStorage as Uge}from"async_hooks";class Ml{storage=new Uge;static createFresh(){return new Ml}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let o=To.parse(e),n=Mge(o);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function Mge(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var Ob=b(()=>{wt()});class of{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Lo()}`;directWorkerSessionId=Lo();directLeaseDurationMs;directSessionStart=null;brainVersion;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new of(e,t??Rr.getInstance(),r)}constructor(e,t,r){this.brainVersion=e.brainVersion===void 0?void 0:Z8.parse(e.brainVersion);let{db:o,client:n,url:i}=P8(e);this.client=n,this.databaseUrl=i,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Ml.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new D$(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new B$(o,n,i,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await $b(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:o}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let i=n.validateAndParse(r);if(i===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Lo(),l=o?.rootJobId??(o?.detached?a:this.operationContext.current()?.provenance.rootJobId)??a,u=this.createJobProvenance(a,l,o),d=o?.metadata??{operationType:"data_processing"},{provenance:p,...m}=d,h={id:a,type:t,data:JSON.stringify(i),status:Oe.PENDING,priority:o?.priority??0,maxRetries:o?.maxRetries??3,retryCount:0,source:o?.source??null,metadata:{...m,...o?.deduplicationKey&&{deduplicationKey:o.deduplicationKey},rootJobId:l,provenance:u},createdAt:s,scheduledFor:o?.delayMs?s+o.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null,brainVersion:this.brainVersion},S,y=()=>{S?.rollback(),S=void 0};try{let v=await this.repository.enqueueAtomic({jobData:h,strategy:o?.deduplication,deduplicationKey:o?.deduplicationKey,beforeInsert:async()=>{S=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:y});if(S?.commit(),S=void 0,v.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:v.jobId});else if(v.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:v.jobId});else{if(v.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:v.replacedJobId});this.logger.debug("Job enqueued",{id:v.jobId,type:t,priority:h.priority,rootJobId:h.metadata.rootJobId})}return v.jobId}catch(v){throw y(),this.logger.error("Failed to enqueue job",{type:t,error:Ve(v)}),v}}createJobProvenance(e,t,r){let o=this.operationContext.current(),n=r?.metadata.provenance??o?.provenance,i=n?.rootJobId===t?n:void 0,s=o?.provenance.rootJobId===t?o.operationId:void 0,a=r?.projection,l=a?[...i?.projectionLineage??[],a.id]:[...i?.projectionLineage??[]],u=a?.id??i?.projectionId;return To.parse({rootJobId:t,causationId:s??i?.causationId??e,...u?{projectionId:u}:{},projectionLineage:l,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:i?.sourceEntity?{sourceEntity:i.sourceEntity}:{},derivationDepth:l.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...o}=e??await this.getDirectClaimOptions(),n=Date.now(),i=await this.repository.claimNextReady({...o,workerSlotId:this.sessionSlotId(o.workerSlotId,o.workerSessionId),brainVersion:this.brainVersion,now:n,attemptId:Lo(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!i)return null;if(i.status===Oe.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:i.id,type:i.type,retryCount:i.retryCount}),await r?.(i),null;return this.logger.debug("Job dequeued",{id:i.id,type:i.type,priority:i.priority,retryCount:i.retryCount,attemptId:i.attemptId,workerSlotId:i.workerSlotId,workerSessionId:i.workerSessionId}),i}async startWorkerSession(e,t,r=Ki){await this.repository.startWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r,this.brainVersion,this.versionedSlotId(e))}heartbeatWorkerSession(e,t,r=Ki){return this.repository.heartbeatWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(this.sessionSlotId(e,t),t)}versionedSlotId(e){return this.brainVersion?`${e}@${this.brainVersion}`:e}sessionSlotId(e,t){return`${this.versionedSlotId(e)}#${t}`}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}release(e,t){return this.repository.release(e,t)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.sessionSlotId(this.directWorkerSlotId,this.directWorkerSessionId),this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs,this.brainVersion),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,o=Date.now()+(e.timeoutMs??30000),n=async(i)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),l=s.pending===0&&s.processing===0?i??Date.now():null;if(l!==null&&Date.now()-l>=t)return;if(Date.now()>=o)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(l)};return n(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}var M8=b(()=>{hp();JR();yp();Zo();z$();N8();U8();wt();Ob();j$()});var U$=()=>{};var q8=b(()=>{hp();Zo();yp();Zo();U$();Ob()});var F8=b(()=>{Zo();U$()});var Cb,J8;var M$=b(()=>{ue();Cb=c.object({success:c.boolean(),data:c.unknown().optional(),error:c.string().optional(),code:c.string().optional()}),J8=c.object({id:c.string().min(1),timestamp:c.string(),type:c.string().min(1),source:c.string().min(1),target:c.string().optional(),metadata:c.record(c.string(),c.unknown()).optional()})});var F8e;var K8=b(()=>{ue();M$();F8e=c.union([c.object({noop:c.literal(!0)}),Cb])});var zb=b(()=>{K8()});var H8=b(()=>{zb()});var V8=b(()=>{zb()});var W8=b(()=>{V8()});var cJe;var q$=b(()=>{ue();cJe=c.looseObject({issues:c.array(c.looseObject({message:c.string()})).optional()})});var G8=b(()=>{H8();zb();W8();q$();wt();Ob()});var Yge;var Q8=b(()=>{ue();M$();Yge=c.object({id:c.string().min(1),requestId:c.string().min(1),success:c.boolean(),data:c.unknown().optional(),error:c.object({message:c.string(),code:c.string().optional()}).optional(),timestamp:c.string().datetime()})});var IJe;var Y8=b(()=>{wt();IJe=new Ci("invalid_response").toJSON()});var X8=b(()=>{G8();Q8();q$();Y8()});var JJe;var eJ=b(()=>{ue();X8();gp();Zo();JJe=c.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},c.record(c.string(),c.unknown()))});var VJe;var tJ=b(()=>{ue();VJe=c.record(c.string(),c.unknown())});var rJ=b(()=>{wt();hp()});var nJ=b(()=>{M8();q8();F8();eJ();tJ();yp();Zo();gp();rJ()});var F$={};Lt(F$,{LEGACY_PROJECTION_JOB_TYPES:()=>iJ,LEGACY_PROJECTION_RETIREMENT_REASON:()=>aJ,legacyProjectionJobTypeSchema:()=>sJ,retireLegacyProjectionJob:()=>nye});import{existsSync as eye}from"fs";import{resolve as tye}from"path";function oJ(e){return{id:e.id,type:e.type,status:e.status,retryCount:e.retryCount,maxRetries:e.maxRetries,createdAt:e.createdAt,startedAt:e.startedAt,completedAt:e.completedAt}}function rye(e,t){if(e.type!==t)throw Error(`Job ${e.id} has type ${e.type}; expected ${t}`);if(e.status!=="pending"&&e.status!=="processing")throw Error(`Job ${e.id} is already terminal (${e.status})`);if(e.attemptId!==null||e.workerSlotId!==null||e.workerSessionId!==null||e.leaseExpiresAt!==null||e.attemptHeartbeatAt!==null)throw Error(`Job ${e.id} still has attempt ownership`);if(e.progress!==null||e.result!=null)throw Error(`Job ${e.id} contains partial progress or a result`)}async function nye(e){let t=tye(e.databasePath);if(!eye(t))throw Error(`Job database does not exist: ${t}`);let r=sJ.parse(e.jobType),o=of.createFresh({url:`file:${t}`});try{let n=await o.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(rye(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:oJ(n),retired:!1}}let i=`retire:${n.id}`;if(e.confirmation!==i)throw Error(`Refusing to retire ${n.id}; expected --confirm ${i}`);let s=await o.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:aJ,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:oJ(s),retired:!0}}finally{o.close()}}var iJ,sJ,aJ="Retired legacy projection job superseded by scheduler-owned projections";var J$=b(()=>{nJ();ue();iJ=["conversation-memory:project","skill:project","swot:derive","topic:project"],sJ=c.enum(iJ)});function Ut(e,t,r,o,n){return lJ.parse({id:e,operation:t,count:r,targetProbeCount:o,settleMs:n})}function fJ(e){return Db.parse(structuredClone(cye[e]))}function Lb(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function H$(e,t={}){let r=t.fetchImpl??fetch,o=t.now??(()=>new Date),n=t.timeoutMs??20000,i=o(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let l=await r(e,{method:"GET",signal:s.signal});return await l.arrayBuffer(),K$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:l.status,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:l.ok})}catch(l){return K$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:!1,error:uye(l)})}finally{clearTimeout(a)}}async function mJ(e,t){let r=Db.parse(e),o=[],n,i=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(l){n=`monitor: ${Pb(l)}`}if(!n)for(let l of r.phases)try{let u=uJ.parse(await t.executePhase(l,i));if(o.push(u),!u.success){n=`${l.id}: ${u.error??"phase failed"}`;break}}catch(u){let d=Pb(u);o.push({id:l.id,operation:l.operation,count:l.count,success:!1,error:d}),n=`${l.id}: ${d}`;break}}finally{try{if(s=dJ.parse(await t.cleanup(i)),!s.success&&!n)n=s.error??"cleanup failed"}catch(l){let u=Pb(l);s={success:!1,probesRemaining:0,error:u},n??=`cleanup: ${u}`}try{a=pJ.parse(await t.stopMonitoring())}catch(l){let u=Pb(l);a={health:[],runtime:[]},n??=`monitor: ${u}`}}return n??=lye(a,r.maximumExternalAiCalls??0),aye.parse({profile:r.profile,success:n===void 0&&o.length===r.phases.length&&s.success,baseline:i,phases:o,cleanup:s,metrics:a,...n?{failure:n}:{}})}function lye(e,t=0){let r=e.health.find((i)=>!i.ok);if(r)return`health: ${r.endpoint} unavailable`;let o=e.externalAiCalls??0;if(o>t)return t===0?`external AI: observed ${o} call(s)`:`external AI: observed ${o} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function uye(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function Pb(e){return Ve(e)}var Nb,cJ,lJ,Db,oye,K$,iye,uJ,dJ,sye,pJ,aye,cye;var V$=b(()=>{ue();Nb=c.enum(["regression","load","stress"]),cJ=c.enum(["add","update","rename","delete"]),lJ=c.object({id:c.string().min(1),operation:cJ,count:c.number().int().positive().max(700),targetProbeCount:c.number().int().min(0).max(700),settleMs:c.number().int().nonnegative().max(300000)}),Db=c.object({profile:Nb,maximumProbeCount:c.number().int().positive().max(700),maximumExternalAiCalls:c.number().int().nonnegative().max(1e4).optional(),phases:c.array(lJ).min(1)}),oye=c.object({entities:c.number().int().nonnegative(),notes:c.number().int().nonnegative(),version:c.string().min(1)}),K$=c.object({timestamp:c.iso.datetime(),endpoint:c.string().startsWith("/"),status:c.number().int().nonnegative(),durationMs:c.number().nonnegative(),ok:c.boolean(),error:c.string().optional()}),iye=c.object({timestamp:c.iso.datetime(),cpuPercent:c.number().nonnegative(),memoryPercent:c.number().nonnegative(),pids:c.number().int().nonnegative()}),uJ=c.object({id:c.string().min(1),operation:cJ,count:c.number().int().positive(),success:c.boolean(),commitLatencyMs:c.number().nonnegative().optional(),persistenceLatencyMs:c.number().nonnegative().optional(),error:c.string().optional()}),dJ=c.object({success:c.boolean(),probesRemaining:c.number().int().nonnegative(),finalEntities:c.number().int().nonnegative().optional(),finalNotes:c.number().int().nonnegative().optional(),contentTreeRestored:c.boolean().optional(),error:c.string().optional()}),sye=c.object({status:c.string(),restartCount:c.number().int().nonnegative(),oomKilled:c.boolean()}),pJ=c.object({health:c.array(K$),runtime:c.array(iye),externalAiCalls:c.number().int().nonnegative().optional(),container:sye.optional()}),aye=c.object({profile:Nb,success:c.boolean(),baseline:oye,phases:c.array(uJ),cleanup:dJ,metrics:pJ,failure:c.string().optional()}),cye={regression:{profile:"regression",maximumProbeCount:20,phases:[Ut("add20","add",20,20,0),Ut("update20","update",20,20,30000),Ut("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Ut("add50","add",50,50,0),Ut("add150","add",100,150,0),Ut("add350","add",200,350,0),Ut("update350a","update",350,350,45000),Ut("rename100","rename",100,350,45000),Ut("update350b","update",350,350,45000),Ut("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Ut("add50","add",50,50,0),Ut("add150","add",100,150,0),Ut("add350","add",200,350,0),Ut("add700","add",350,700,0),Ut("update700a","update",700,700,45000),Ut("rename200","rename",200,700,45000),Ut("update700b","update",700,700,45000),Ut("delete700","delete",700,0,150000)]}}});import{spawn as dye}from"child_process";async function hJ(e,t,r,o){let n=await e(t,r,o);if(n.exitCode!==0)throw co(t,r,n);return n}function co(e,t,r){let o=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${o?`: ${o}`:""}`)}var Go=async(e,t,r={})=>new Promise((o,n)=>{let i=dye(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",(l)=>{s+=l}),i.stderr.on("data",(l)=>{a+=l}),i.on("error",n),i.on("close",(l)=>{o({exitCode:l??1,stdout:s,stderr:a})}),i.stdin.end(r.stdin)});var sf=()=>{};class ql{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,o){let n=new ql(e,r,o);return await hJ(e,"git",["-c","credential.helper=","-c",`credential.helper=${gJ}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",gJ]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw co("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var gJ='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var yJ=b(()=>{sf()});function af(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class W${#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#o=!0;#i;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await H$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#o=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#i=Promise.all([this.#m(),this.#f()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#o=!0})}async stop(){this.#o=!0,await this.#i}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let o=this.#e.now().getTime();while(this.#e.now().getTime()-o<r){let n=await this.fetchHealthPayload();if(this.#p(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let o=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-o<r){let i=await this.fetchHealthPayload();if(this.#p(i,e,t)){if(n+=1,n===2)return i}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=await this.#d();if(e===void 0)return;let t=await this.#e.readEntityCounts();if(!t)return;return{version:e,entities:t.reduce((r,o)=>r+o.count,0),entityCounts:t}}async#d(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let o=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await o.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:o.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:o.ok}),!o.ok)return;return pye.parse(JSON.parse(n)).app.version}catch(o){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:o instanceof Error?`${o.name}: ${o.message}`:String(o)});return}finally{clearTimeout(r)}}#p(e,t,r){return e!==void 0&&(t===void 0||af(e)===t)&&(r===void 0||e.entities===r)}async#m(){while(!this.#o){for(let e of this.#n)this.#t.push(await H$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#f(){while(!this.#o){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var bJ,pye;var SJ=b(()=>{ue();V$();bJ=c.array(c.object({entityType:c.string(),count:c.number().int().nonnegative()})),pye=c.object({status:c.literal("ready"),operationalStatus:c.literal("operational"),app:c.object({version:c.string()})})});var Zb={};Lt(Zb,{applyDirectorySyncStressPhase:()=>_J,cleanupDirectorySyncStress:()=>_ye,listProbeFiles:()=>_a,parseStressRuntimeSample:()=>EJ,removeProbeFiles:()=>rO,runDeployedDirectorySyncStress:()=>wye,runStressCommand:()=>Go,verifyDirectorySyncStressAccess:()=>xye});import{chmod as fye,mkdir as Q$,mkdtemp as Y$,readFile as mye,readdir as hye,rename as gye,rm as lf,writeFile as Tn}from"fs/promises";import{tmpdir as X$}from"os";import{join as ct,resolve as eO}from"path";async function wye(e){let t=e.now??(()=>new Date),r=t().toISOString(),o=nO(r),n=eO(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",o));await Q$(n,{recursive:!0});let{pilot:i,user:s}=await tO(e.rootDir,e.handle);Lb({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Nb.parse(e.profile),l=e.plan?Db.parse(e.plan):fJ(a);if(l.profile!==a)throw Error(`Directory-sync stress plan profile ${l.profile} does not match requested profile ${a}`);if((l.maximumExternalAiCalls??0)===0)xJ(s);let u=yye.parse(e.env??process.env),d=new wJ({runId:o,artifactsDir:n,user:s,githubOrg:i.githubOrg,serverLabel:`${i.contentRepoPrefix}${s.handle}`,environment:u,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??Go,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),p;try{p=await mJ(l,d)}finally{await d.dispose()}let m={runId:o,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:p};return await Iye(m),m}async function xye(e){let r=(e.now??(()=>new Date))().toISOString(),o=nO(r),n=eO(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`access-check-${o}`));await Q$(n,{recursive:!0});let{pilot:i,user:s}=await tO(e.rootDir,e.handle);Lb({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),xJ(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let l=await Y$(ct(X$(),"brains-ops-directory-sync-access-check-"));try{let u=await ql.clone(e.commandRunner??Go,`${i.githubOrg}/${s.contentRepo}`,ct(l,"content"),a),d=await u.output(["rev-parse","HEAD"]);await u.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${o}`]);let p={success:!0,artifactsDir:n,checkedAt:r,remoteHead:d,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`}};return await Tn(ct(n,"access-check.json"),`${JSON.stringify(p,null,2)}
|
|
460
|
+
`),p}finally{await lf(l,{recursive:!0,force:!0})}}async function _ye(e){let t=e.now??(()=>new Date),r=eO(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`cleanup-${nO(t().toISOString())}`));await Q$(r,{recursive:!0});let{pilot:o,user:n}=await tO(e.rootDir,e.handle);Lb({handle:n.handle,domain:n.domain,contentRepo:n.contentRepo,confirmation:e.confirmation});let i=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!i)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let s=e.commandRunner??Go,a=e.logger??console.info,l=await Y$(ct(X$(),"brains-ops-directory-sync-cleanup-")),u=ct(l,"content");try{let d=await ql.clone(s,`${o.githubOrg}/${n.contentRepo}`,u,i),p=await rO(d.dir),m;if(p>0)await d.commitAll("test(directory-sync): clean residual stress probes"),await d.pushMainWithRebase(),m=await d.output(["rev-parse","HEAD"]),a(`Removed ${p} directory-sync stress probes`);let h=(await _a(d.dir)).length,S=h===0?await d.pruneStressBackupBranches():[],y={success:h===0,artifactsDir:r,probesRemoved:p,probesRemaining:h,backupBranchesDeleted:S,...m?{cleanupCommit:m}:{}};return await Tn(ct(r,"cleanup.json"),`${JSON.stringify(y,null,2)}
|
|
461
|
+
`),y}finally{await lf(l,{recursive:!0,force:!0})}}class wJ{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new W$({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#b(),readEntityCounts:()=>this.#y()})}async prepare(e){this.#r=await Y$(ct(X$(),"brains-ops-directory-sync-stress-"));let t=ct(this.#r,"content");this.#o=ct(this.#r,"id_ed25519"),this.#i=ct(this.#r,"known_hosts"),this.#a=await this.#m(),await Tn(this.#o,Aye(this.#e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await fye(this.#o,384);let r=await this.#S("ssh-keyscan",["-T","10","-t","ed25519",this.#a]);if(r.exitCode!==0||!r.stdout.trim())throw Error("Unable to resolve smoke SSH host key");await Tn(this.#i,r.stdout,{mode:384});let o=await this.#h(["docker","ps","--filter","label=service=rover","--filter","label=role=web","--format","{{.Names}}"]);if(this.#s=o.stdout.trim().split(/\r?\n/)[0],!this.#s||!/^[A-Za-z0-9_.-]+$/.test(this.#s))throw Error("Unable to resolve a running smoke container");let n=await ql.clone(this.#e.commandRunner,`${this.#e.githubOrg}/${this.#e.user.contentRepo}`,t,this.#e.environment.CONTENT_REPO_ADMIN_TOKEN);if(this.#n=n,(await _a(n.dir)).length>0)throw Error("Directory-sync stress probes already exist");let i=await n.output(["rev-parse","HEAD"]);this.#l=await n.output(["rev-parse","HEAD^{tree}"]),this.#d=await this.#p();let s=await this.#t.waitForHealthSnapshot(60000);if(!s)throw Error("Smoke health was unavailable before stress testing");return this.#c=`ops/directory-sync-stress-backup-${this.#e.runId}`,await n.run(["push","origin",`HEAD:refs/heads/${this.#c}`]),await this.#t.discoverEndpoints(),await Tn(ct(this.#e.artifactsDir,"state.json"),`${JSON.stringify({runId:this.#e.runId,profile:e.profile,originalHead:i,originalTree:this.#l,backupBranch:this.#c,baseline:{entities:s.entities,notes:af(s),version:s.version}},null,2)}
|
|
461
462
|
`),this.#e.logger(`Prepared ${e.profile} directory-sync stress run for ${this.#e.user.handle}`),{entities:s.entities,notes:af(s),version:s.version}}async startMonitoring(){this.#v(),this.#t.start()}async executePhase(e,t){this.#v();let r=this.#n;if(!r)throw Error("Directory-sync stress checkout is not prepared");await r.sync();let o=this.#t.healthSamples.length,n=this.#e.now().getTime(),i=await this.#g();if(i?.pending!==0||i.processing!==0)return Fl(e,"health did not provide a drained queue before the phase");await _J(r.dir,e),await r.commitAll(`test(directory-sync): stress ${e.id}`),await r.pushMainWithRebase();let s=this.#e.now().getTime(),a=await r.output(["rev-parse","HEAD"]),l=await this.#f(a,900000);if(l===void 0)return Fl(e,"runtime did not pull the phase commit");let u;if(e.operation==="rename"){let h=t.notes+e.targetProbeCount;if(e.settleMs>0)await this.#e.sleep(e.settleMs);let S=await this.#t.waitForStableEntityBaseline(h,void 0,1200000);if(u=this.#e.now().getTime()-s,!S)return Fl(e,`health did not stabilize at ${h} notes`,l,u)}else if(e.operation==="add"||e.operation==="delete"){let h=t.notes+e.targetProbeCount,S=this.#e.now().getTime(),y=await this.#t.waitForEntityBaseline(h,void 0,1200000);if(u=this.#e.now().getTime()-S,!y)return Fl(e,`health did not reach ${h} notes`,l,u)}if(e.operation!=="rename"&&e.settleMs>0)await this.#e.sleep(e.settleMs);let d=e.operation==="delete"?0:Math.ceil(e.count/50);if(!await this.#u(i.completedImports+d,1200000))return Fl(e,`health did not observe ${d} completed import job(s) with a drained queue`,l,u);let m=this.#t.healthSamples.slice(o).find((h)=>!h.ok);if(m)return Fl(e,`${m.endpoint} unavailable (${m.status===0?m.error??"unknown":m.status})`,l,u);return this.#e.logger(`Completed ${e.id} in ${this.#e.now().getTime()-n}ms`),{id:e.id,operation:e.operation,count:e.count,success:!0,commitLatencyMs:l,...u===void 0?{}:{persistenceLatencyMs:u}}}async cleanup(e){let t=this.#n;if(!t)return{success:!1,probesRemaining:0,error:"stress checkout was not prepared"};try{if(await t.sync(!0),await rO(t.dir)>0)await t.commitAll("test(directory-sync): remove stress probes"),await t.pushMainWithRebase();let o=(await _a(t.dir)).length;this.#t.markGateEnd();let n=await this.#t.waitForEntityBaseline(e.notes,e.entities,1200000);await t.sync(!0);let s=await t.output(["rev-parse","HEAD^{tree}"])===this.#l,a=o===0&&n!==void 0&&s;if(a&&this.#c){if((await t.run(["push","origin","--delete",this.#c],!1)).exitCode!==0)this.#e.logger(`Warning: unable to delete backup branch ${this.#c}`)}return{success:a,probesRemaining:o,...n?{finalEntities:n.entities,finalNotes:af(n)}:{},contentTreeRestored:s,...!a?{error:!n?"entity baseline was not restored before cleanup timeout":!s?"content tree differs from the pre-stress baseline":"stress probes remain after cleanup"}:{}}}catch(r){return{success:!1,probesRemaining:(await _a(t.dir)).length,error:Ve(r)}}}async stopMonitoring(){await this.#t.stop(),await Tn(ct(this.#e.artifactsDir,"health-samples.json"),`${JSON.stringify(this.#t.healthSamples,null,2)}
|
|
462
|
-
`);let e=0;if(this.#s&&this.#t.startedAt){let o=await this.#h(["docker","logs","--since",this.#t.startedAt,this.#s],!1),n=`${o.stdout}${o.stderr}`;e=n.match(/\] ai:usage \{/g)?.length??0,await Tn(ct(this.#e.artifactsDir,"runtime.log"),n)}let t=await this.#p(),r={health:this.#t.gateHealthSamples(),runtime:[...this.#t.runtimeSamples],externalAiCalls:e,...t?{container:t}:{}};if(this.#t.error)throw this.#t.error;return r}async dispose(){if(await this.#t.stop(),this.#r)await lf(this.#r,{recursive:!0,force:!0})}async#p(){if(!this.#s)return;let e=await this.#h(["docker","inspect",this.#s],!1);if(e.exitCode!==0)throw Error(`docker inspect ${this.#s} exited with code ${e.exitCode}`);let t;try{t=c.array(c.object({RestartCount:c.number().int().nonnegative(),State:c.object({Status:c.string(),OOMKilled:c.boolean(),StartedAt:c.string().min(1)})})).parse(JSON.parse(e.stdout))}catch(i){throw Error(`Could not read docker inspect output for ${this.#s}`,{cause:i})}let r=t[0];if(!r)throw Error("docker inspect reported no such container");let o=Math.max(0,r.RestartCount-(this.#d?.restartCount??0)),n=this.#d!==void 0&&r.State.StartedAt!==this.#d.startedAt;return{status:r.State.Status,restartCount:Math.max(o,n?1:0),oomKilled:r.State.OOMKilled&&!(this.#d?.oomKilled??!1),startedAt:r.State.StartedAt}}async#m(){let e=encodeURIComponent(`brain=${this.#e.serverLabel}`),t=await this.#e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${e}`,{headers:{Authorization:`Bearer ${this.#e.environment.HCLOUD_TOKEN}`}});if(!t.ok)throw Error(`Hetzner server lookup failed with ${t.status}`);let o=
|
|
463
|
-
`))}break}case"update":{if(r.length!==t.count)throw Error(`${t.id} expected ${t.count} probes, found ${r.length}`);for(let o of r){let n=ct(e,o),i=await
|
|
463
|
+
`);let e=0;if(this.#s&&this.#t.startedAt){let o=await this.#h(["docker","logs","--since",this.#t.startedAt,this.#s],!1),n=`${o.stdout}${o.stderr}`;e=n.match(/\] ai:usage \{/g)?.length??0,await Tn(ct(this.#e.artifactsDir,"runtime.log"),n)}let t=await this.#p(),r={health:this.#t.gateHealthSamples(),runtime:[...this.#t.runtimeSamples],externalAiCalls:e,...t?{container:t}:{}};if(this.#t.error)throw this.#t.error;return r}async dispose(){if(await this.#t.stop(),this.#r)await lf(this.#r,{recursive:!0,force:!0})}async#p(){if(!this.#s)return;let e=await this.#h(["docker","inspect",this.#s],!1);if(e.exitCode!==0)throw Error(`docker inspect ${this.#s} exited with code ${e.exitCode}`);let t;try{t=c.array(c.object({RestartCount:c.number().int().nonnegative(),State:c.object({Status:c.string(),OOMKilled:c.boolean(),StartedAt:c.string().min(1)})})).parse(JSON.parse(e.stdout))}catch(i){throw Error(`Could not read docker inspect output for ${this.#s}`,{cause:i})}let r=t[0];if(!r)throw Error("docker inspect reported no such container");let o=Math.max(0,r.RestartCount-(this.#d?.restartCount??0)),n=this.#d!==void 0&&r.State.StartedAt!==this.#d.startedAt;return{status:r.State.Status,restartCount:Math.max(o,n?1:0),oomKilled:r.State.OOMKilled&&!(this.#d?.oomKilled??!1),startedAt:r.State.StartedAt}}async#m(){let e=encodeURIComponent(`brain=${this.#e.serverLabel}`),t=await this.#e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${e}`,{headers:{Authorization:`Bearer ${this.#e.environment.HCLOUD_TOKEN}`}});if(!t.ok)throw Error(`Hetzner server lookup failed with ${t.status}`);let o=bye.parse(await t.json()).servers[0];if(o?.status!=="running")throw Error("Smoke server is not running");return o.public_net.ipv4.ip}async#f(e,t){let r=this.#s;if(!r)throw Error("Directory-sync stress container is not prepared");let o=this.#e.now().getTime();while(this.#e.now().getTime()-o<t){if((await this.#h(["docker","exec",r,"git","-C","/app/brain-data","merge-base","--is-ancestor",e,"HEAD"],!1)).exitCode===0)return this.#e.now().getTime()-o;await this.#e.sleep(5000)}return}async#g(){let e=new AbortController,t=setTimeout(()=>e.abort(),20000),r;try{let i=await this.#e.fetchImpl(`https://${this.#e.user.domain}/health/operate`,{method:"GET",signal:e.signal});if(!i.ok)return;r=await i.json()}catch{return}finally{clearTimeout(t)}let o=Sye.safeParse(r);if(!o.success)throw Error(`Unexpected /health/operate payload from ${this.#e.user.domain}`,{cause:o.error});let n=o.data.resources.queue.byType.filter((i)=>i.type==="directory-sync:directory-import"&&i.status==="completed").reduce((i,s)=>i+s.count,0);return{pending:o.data.resources.queue.totals.pending,processing:o.data.resources.queue.totals.processing,completedImports:n}}async#u(e,t){let r=this.#e.now().getTime(),o=0;while(this.#e.now().getTime()-r<t){let n=await this.#g();if(n?.pending===0&&n.processing===0&&n.completedImports>=e){if(o+=1,o===2)return!0}else o=0;await this.#e.sleep(5000)}return!1}async#y(){let e=this.#s;if(!e)throw Error("Directory-sync stress container is not prepared");let t=await this.#h(["docker","exec",e,"bun","-e",`'${vye}'`],!1);if(t.exitCode!==0)return;try{return bJ.parse(JSON.parse(t.stdout))}catch(r){throw Error(`Could not read entity counts from ${e}`,{cause:r})}}async#b(){let e=this.#s;if(!e)throw Error("Directory-sync stress container is not prepared");let t=await this.#h(["timeout","15","docker","stats","--no-stream","--format","{{.CPUPerc}},{{.MemPerc}},{{.PIDs}}",e],!1);return EJ(t.stdout.trim(),this.#e.now().toISOString())}async#h(e,t=!0){let r=this.#o,o=this.#i,n=this.#a;if(!r||!o||!n)throw Error("Directory-sync stress SSH access is not prepared");let i=await this.#S("ssh",["-i",r,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${o}`,`root@${n}`,...e]);if(t&&i.exitCode!==0)throw co("ssh",e,i);return i}async#S(e,t,r){return this.#e.commandRunner(e,t,r)}#v(){if(!this.#n||!this.#o||!this.#i||!this.#a||!this.#s)throw Error("Directory-sync stress driver is not prepared")}}function xJ(e){if(e.embeddingEnabled!==!1)throw Error("Directory-sync stress requires embeddingEnabled: false for a hermetic smoke workload");if(e.topicExtractionEnabled!==!1)throw Error("Directory-sync stress requires topicExtractionEnabled: false for a hermetic smoke workload");if(e.skillDerivationEnabled!==!1)throw Error("Directory-sync stress requires skillDerivationEnabled: false for a hermetic smoke workload");if(e.swotDerivationEnabled!==!1)throw Error("Directory-sync stress requires swotDerivationEnabled: false for a hermetic smoke workload")}async function tO(e,t){let r=await xt(e),o=r.users.find((n)=>n.handle===t);if(!o)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:o}}async function _J(e,t){let r=await _a(e);switch(t.operation){case"add":{let o=t.targetProbeCount-r.length;if(o!==t.count)throw Error(`${t.id} expected to add ${t.count} probes from ${r.length}`);let n=r.map(Eye).filter((s)=>s!==void 0),i=n.length===0?1:Math.max(...n)+1;for(let s=i;s<i+o;s+=1){let a=String(s).padStart(3,"0");await Tn(ct(e,`directory-sync-stress-${a}.md`),["---",`title: "Directory Sync Stress ${a}"`,"---","",`Deterministic directory-sync stress probe ${a}.`,"Payload: abcdefghijklmnopqrstuvwxyz-0123456789-abcdefghijklmnopqrstuvwxyz.",""].join(`
|
|
464
|
+
`))}break}case"update":{if(r.length!==t.count)throw Error(`${t.id} expected ${t.count} probes, found ${r.length}`);for(let o of r){let n=ct(e,o),i=await mye(n,"utf8");await Tn(n,`${i.trimEnd()}
|
|
464
465
|
|
|
465
466
|
Update marker: ${t.id}.
|
|
466
|
-
`)}break}case"rename":{let o=r.filter((n)=>/^directory-sync-stress-\d+\.md$/.test(n)).slice(0,t.count);if(o.length!==t.count)throw Error(`${t.id} expected ${t.count} unrenamed probes, found ${o.length}`);for(let n of o)await
|
|
467
|
+
`)}break}case"rename":{let o=r.filter((n)=>/^directory-sync-stress-\d+\.md$/.test(n)).slice(0,t.count);if(o.length!==t.count)throw Error(`${t.id} expected ${t.count} unrenamed probes, found ${o.length}`);for(let n of o)await gye(ct(e,n),ct(e,n.replace("directory-sync-stress-","directory-sync-stress-renamed-")));break}case"delete":{if(r.length!==t.count)throw Error(`${t.id} expected ${t.count} probes, found ${r.length}`);await Promise.all(r.map((o)=>lf(ct(e,o),{force:!0})));break}}}async function _a(e){return(await hye(e)).filter((r)=>/^directory-sync-stress-(?:renamed-)?\d+\.md$/.test(r)&&!r.includes("/")).sort()}async function rO(e){let t=await _a(e);return await Promise.all(t.map((r)=>lf(ct(e,r),{force:!0}))),t.length}function Eye(e){let t=e.match(/(\d+)\.md$/)?.[1];return t?Number.parseInt(t,10):void 0}function Fl(e,t,r,o){return{id:e.id,operation:e.operation,count:e.count,success:!1,...r===void 0?{}:{commitLatencyMs:r},...o===void 0?{}:{persistenceLatencyMs:o},error:t}}function EJ(e,t){let[r,o,n]=e.split(",");if(!r||!o||!n)return;let i=Number.parseFloat(r.replace("%","")),s=Number.parseFloat(o.replace("%","")),a=Number.parseInt(n,10);if(!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(a))return;return{timestamp:t,cpuPercent:i,memoryPercent:s,pids:a}}function Aye(e){return`${e.replace(/\r\n/g,`
|
|
467
468
|
`).replace(/\\n/g,`
|
|
468
469
|
`).trimEnd()}
|
|
469
|
-
`}function nO(e){return e.replace(/[-:.TZ]/g,"").slice(0,14)}async function
|
|
470
|
-
`),await Tn(ct(e.artifactsDir,"report.md"),
|
|
470
|
+
`}function nO(e){return e.replace(/[-:.TZ]/g,"").slice(0,14)}async function Iye(e){await Tn(ct(e.artifactsDir,"report.json"),`${JSON.stringify(e,null,2)}
|
|
471
|
+
`),await Tn(ct(e.artifactsDir,"report.md"),kye(e))}function kye(e){let t=e.report.metrics.runtime,r=e.report.metrics.health,o=t.map((a)=>a.cpuPercent).sort((a,l)=>a-l),n=t.map((a)=>a.memoryPercent),i=r.filter((a)=>!a.ok),s=["# Directory-sync stress report","",`- Run: \`${e.runId}\``,`- Target: \`${e.target.handle}\` (${e.target.domain})`,`- Profile: \`${e.report.profile}\``,`- Version: \`${e.report.baseline.version}\``,`- Result: **${e.report.success?"PASS":"FAIL"}**`,`- Started: ${e.startedAt}`,`- Completed: ${e.completedAt}`,"","## Phases","","| Phase | Operation | Count | Result | Pull latency | Persistence latency |","| --- | --- | ---: | --- | ---: | ---: |",...e.report.phases.map((a)=>`| ${a.id} | ${a.operation} | ${a.count} | ${a.success?"pass":`fail: ${a.error??"unknown"}`} | ${vJ(a.commitLatencyMs)} | ${vJ(a.persistenceLatencyMs)} |`),"","## Runtime","",`- Samples: ${t.length}`,`- CPU p50/p95/p99/max: ${cf(G$(o,0.5))} / ${cf(G$(o,0.95))} / ${cf(G$(o,0.99))} / ${cf(o.at(-1))}`,`- Memory max: ${cf(n.length?Math.max(...n):void 0)}`,`- PIDs max: ${t.length?Math.max(...t.map((a)=>a.pids)):"n/a"}`,`- Container status/restarts/OOM: ${e.report.metrics.container?`${e.report.metrics.container.status} / ${e.report.metrics.container.restartCount} / ${e.report.metrics.container.oomKilled}`:"unknown"}`,`- External AI calls: ${e.report.metrics.externalAiCalls??0}`,`- Health samples: ${r.length}`,`- Health failures: ${i.length}`,"","## Cleanup","",`- Result: ${e.report.cleanup.success?"pass":"fail"}`,`- Remaining probes: ${e.report.cleanup.probesRemaining}`,`- Final entities: ${e.report.cleanup.finalEntities??"unknown"}`,`- Final notes: ${e.report.cleanup.finalNotes??"unknown"}`,`- Content tree restored: ${e.report.cleanup.contentTreeRestored??"unknown"}`,""];if(e.report.failure)s.push("## Failure","",e.report.failure,"");return`${s.join(`
|
|
471
472
|
`)}
|
|
472
|
-
`}function G$(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function cf(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function vJ(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var
|
|
473
|
+
`}function G$(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function cf(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function vJ(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var yye,bye,Sye,vye;var jb=b(()=>{ue();V$();gn();sf();yJ();SJ();sf();yye=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1),CONTENT_REPO_ADMIN_TOKEN:c.string().min(1)}),bye=c.object({servers:c.array(c.object({id:c.number().int(),status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))}),Sye=c.object({status:c.literal("ready"),operationalStatus:c.literal("operational"),resources:c.object({queue:c.object({totals:c.object({pending:c.number().int().nonnegative(),processing:c.number().int().nonnegative()}),byType:c.array(c.object({type:c.string(),status:c.string(),count:c.number().int().nonnegative()}))})})}),vye=['import { Database } from "bun:sqlite";','const path = (process.env.XDG_DATA_HOME || "./data") + "/brain.db";',"const db = new Database(path, { readonly: true });",'const rows = db.query(`SELECT "entityType" AS "entityType", COUNT(*) AS "count" FROM entities GROUP BY "entityType"`).all();',"process.stdout.write(JSON.stringify(rows));"].join(" ")});var AJ=b(()=>{wi()});var Rye="/usr/local/sbin/brains-health-watchdog",Tye="ai.rizom.brain.watchdog",$ye="true",oO,IJ,JKe;var kJ=b(async()=>{AJ();oO=`${Tye}=${$ye}`,IJ=`#!/usr/bin/env bash
|
|
473
474
|
set -euo pipefail
|
|
474
475
|
umask 077
|
|
475
476
|
|
|
@@ -528,14 +529,14 @@ while read -r container_id; do
|
|
|
528
529
|
logger -t brains-health-watchdog "restarting unhealthy container=$container_name service=$service_name incident=$incident_path"
|
|
529
530
|
docker restart "$container_id"
|
|
530
531
|
done < <(docker ps --filter health=unhealthy --filter label=${oO} --format '{{.ID}}')
|
|
531
|
-
`,
|
|
532
|
+
`,JKe=`[Unit]
|
|
532
533
|
Description=Restart persistently unhealthy Brain containers
|
|
533
534
|
After=docker.service
|
|
534
535
|
Requires=docker.service
|
|
535
536
|
|
|
536
537
|
[Service]
|
|
537
538
|
Type=oneshot
|
|
538
|
-
ExecStart=${
|
|
539
|
+
ExecStart=${Rye}
|
|
539
540
|
`});var TJ=`#!/usr/bin/env bash
|
|
540
541
|
set -euo pipefail
|
|
541
542
|
umask 077
|
|
@@ -763,13 +764,13 @@ deployed_container_restarted=false
|
|
|
763
764
|
EOF
|
|
764
765
|
pass "fleet watchdog isolation smoke completed"
|
|
765
766
|
printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
766
|
-
`;var RJ=()=>{};var cO={};Lt(cO,{assertHealthWatchdogSmokeTarget:()=>aO,cleanupHealthWatchdogSmoke:()=>
|
|
767
|
-
`),p}async function
|
|
768
|
-
`),i}async function PJ(e,t){let r=await xt(e),o=r.users.find((n)=>n.handle===t);if(!o)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:o}}async function NJ(e){let t=await
|
|
767
|
+
`;var RJ=()=>{};var cO={};Lt(cO,{assertHealthWatchdogSmokeTarget:()=>aO,cleanupHealthWatchdogSmoke:()=>Lye,renderHealthWatchdogSmokeRemoteScript:()=>zJ,runHealthWatchdogSmoke:()=>Dye});import{chmod as Cye,mkdir as $J,mkdtemp as zye,rm as sO,writeFile as Jl}from"fs/promises";import{tmpdir as Pye}from"os";import{join as lo,resolve as OJ}from"path";function aO(e){let t=`watchdog-smoke:${e.handle}`;if(e.confirmation!==t)throw Error(`Health watchdog smoke requires --confirm ${t}`);if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,100}$/.test(e.runId))throw Error("Health watchdog smoke run ID is invalid");let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain))throw Error("Health watchdog smoke is smoke-only; handle and domain must both identify smoke")}function zJ(){return TJ.replace("__WATCHDOG_PAYLOAD_BASE64__",Buffer.from(IJ,"utf8").toString("base64")).replace("__WATCHDOG_LABEL_FILTER__",oO)}async function Dye(e){let t=OJ(e.artifactsDir??lo(e.rootDir,".brains-ops","watchdog-smoke",e.runId)),r=await PJ(e.rootDir,e.handle);aO({handle:r.user.handle,domain:r.user.domain,confirmation:e.confirmation,runId:e.runId}),await $J(t,{recursive:!0});let o=CJ.parse(e.env??process.env),n=e.commandRunner??Go,i=e.logger??console.info,s=await NJ({target:r,environment:o,commandRunner:n,fetchImpl:e.fetchImpl??fetch}),a=`/tmp/brains-health-watchdog-smoke-${e.runId}`,l,u=!1;try{let m=await iO(s,"run",e.runId);if(await Bb(t,"remote",m),m.stdout.trim())i(m.stdout.trim());if(m.exitCode!==0)l=co("ssh",["watchdog-smoke","run"],m);let h=await Zye(s,a,t);if(await Bb(t,"scp",h),h.exitCode===0){if(u=await Ir(lo(t,"summary.txt")),!u)l??=Error("Health watchdog smoke evidence is missing summary.txt")}else l??=co("scp",[a,t],h)}catch(m){l=Error(Ve(m,"Health watchdog smoke execution failed"))}let d;try{let m=await iO(s,"cleanup",e.runId);if(await Bb(t,"cleanup",m),m.exitCode!==0)d=co("ssh",["watchdog-smoke","cleanup"],m)}catch(m){d=Error(Ve(m,"Health watchdog smoke cleanup failed"))}finally{await sO(s.temporaryRoot,{recursive:!0,force:!0})}if(l)throw l;if(d)throw d;if(!u)throw Error("Health watchdog smoke completed without copied evidence");let p={success:!0,runId:e.runId,artifactsDir:t,target:{handle:r.user.handle,domain:r.user.domain,serverIp:s.serverIp}};return await Jl(lo(t,"result.json"),`${JSON.stringify(p,null,2)}
|
|
768
|
+
`),p}async function Lye(e){let t=OJ(e.artifactsDir??lo(e.rootDir,".brains-ops","watchdog-smoke",`cleanup-${e.runId}`)),r=await PJ(e.rootDir,e.handle);aO({handle:r.user.handle,domain:r.user.domain,confirmation:e.confirmation,runId:e.runId}),await $J(t,{recursive:!0});let o=CJ.parse(e.env??process.env),n=await NJ({target:r,environment:o,commandRunner:e.commandRunner??Go,fetchImpl:e.fetchImpl??fetch});try{let s=await iO(n,"cleanup",e.runId);if(await Bb(t,"cleanup",s),s.stdout.trim())(e.logger??console.info)(s.stdout.trim());if(s.exitCode!==0)throw co("ssh",["watchdog-smoke","cleanup"],s)}finally{await sO(n.temporaryRoot,{recursive:!0,force:!0})}let i={success:!0,runId:e.runId,artifactsDir:t,target:{handle:r.user.handle,domain:r.user.domain,serverIp:n.serverIp}};return await Jl(lo(t,"result.json"),`${JSON.stringify(i,null,2)}
|
|
769
|
+
`),i}async function PJ(e,t){let r=await xt(e),o=r.users.find((n)=>n.handle===t);if(!o)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:o}}async function NJ(e){let t=await zye(lo(Pye(),"brains-ops-watchdog-smoke-")),r=lo(t,"id_ed25519"),o=lo(t,"known_hosts");try{let n=encodeURIComponent(`brain=${e.target.pilot.contentRepoPrefix}${e.target.user.handle}`),i=await e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${n}`,{headers:{Authorization:`Bearer ${e.environment.HCLOUD_TOKEN}`}});if(!i.ok)throw Error(`Hetzner server lookup failed with ${i.status}`);let s=Nye.parse(await i.json());if(s.servers.length!==1)throw Error(`Expected one smoke server, found ${s.servers.length}`);let a=s.servers[0];if(a?.status!=="running")throw Error("Smoke server is not running");await Jl(r,jye(e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await Cye(r,384);let l=await e.commandRunner("ssh-keyscan",["-T","10","-t","ed25519",a.public_net.ipv4.ip]);if(l.exitCode!==0||!l.stdout.trim())throw Error("Unable to resolve watchdog smoke SSH host key");return await Jl(o,l.stdout,{mode:384}),{temporaryRoot:t,sshKeyPath:r,knownHostsPath:o,serverIp:a.public_net.ipv4.ip,commandRunner:e.commandRunner}}catch(n){throw await sO(t,{recursive:!0,force:!0}),n}}async function iO(e,t,r){return e.commandRunner("ssh",[...DJ(e),`root@${e.serverIp}`,"bash","-s","--",t,r],{stdin:zJ()})}async function Zye(e,t,r){return e.commandRunner("scp",[...DJ(e),"-r",`root@${e.serverIp}:${t}/.`,r])}function DJ(e){return["-i",e.sshKeyPath,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${e.knownHostsPath}`]}async function Bb(e,t,r){await Promise.all([Jl(lo(e,`${t}.stdout.log`),r.stdout),Jl(lo(e,`${t}.stderr.log`),r.stderr)])}function jye(e){return`${e.replace(/\r\n/g,`
|
|
769
770
|
`).replace(/\\n/g,`
|
|
770
771
|
`).trimEnd()}
|
|
771
|
-
`}var CJ,
|
|
772
|
-
`)}function yO(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function ot(e,t){let r=e[t];return typeof r==="string"?r:void 0}function fs(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var pf={name:"@rizom/ops",version:"0.2.0-alpha.
|
|
772
|
+
`}var CJ,Nye;var lO=b(async()=>{ue();RJ();gn();sf();Xs();await kJ();CJ=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),Nye=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{parseArgs as vK}from"util";function nt(e){return e}class df extends Error{constructor(e){super(e);this.name="CliUsageError"}}function wK(e,t){let r={...t};for(let o of e)for(let[n,i]of Object.entries(o.flags??{})){let s=r[n];if(s===void 0){r[n]=i;continue}if(s.type!==i.type||s.short!==i.short||s.default!==i.default)throw Error(`Conflicting definitions for flag --${n}: commands must agree on type, short, and default`)}return r}function xK(e){let t={};for(let[r,o]of Object.entries(e))t[r]={type:o.type,...o.short!==void 0?{short:o.short}:{},...o.default!==void 0?{default:o.default}:{}};return t}function _K(e){if(!(e instanceof Error)||!("code"in e))return!1;return e.code==="ERR_PARSE_ARGS_UNKNOWN_OPTION"||e.code==="ERR_PARSE_ARGS_INVALID_OPTION_VALUE"}function pO(e,t){let r=wK(t.commands,t.globalFlags??{}),o,n;try{({values:o,positionals:n}=vK({args:e,options:xK(r),allowPositionals:!0,strict:t.strict??!0}))}catch(s){if(_K(s))throw new df(s.message.split(". ")[0]??s.message);throw s}if("help"in r&&o.help===!0)return{command:"help",args:[],flags:{help:!0}};if("version"in r&&o.version===!0)return{command:"version",args:[],flags:{version:!0}};let i={};for(let[s,a]of Object.entries(r)){let l=o[s];if(typeof l==="string"&&a.type==="string")i[s]=l;else if(typeof l==="boolean"&&a.type==="boolean")i[s]=l}return{command:n[0]??"help",args:n.slice(1),flags:i}}function fO(e){let t=e.reduce((r,o)=>Math.max(r,o.label.length),0);return e.map((r)=>` ${r.label.padEnd(t)} ${r.description}`)}function EK(e){return fO(e.map((t)=>({label:t.usage?`${t.name} ${t.usage}`:t.name,description:t.description})))}function AK(e,t){let r=t.type==="string"?` ${t.placeholder??"<value>"}`:"",o=t.short!==void 0?`, -${t.short}`:"";return`--${e}${r}${o}`}function mO(e){return fO(Object.entries(e).map(([t,r])=>({label:AK(t,r),description:r.description})))}function hO(e,t){return`Usage: ${e} ${t.name}${t.usage?` ${t.usage}`:""}`}function IK(e){return JSON.stringify(Object.entries(e).map(([t,r])=>[t,r.type,r.short??"",r.description,r.placeholder??"",r.default??""]).sort((t,r)=>String(t[0]).localeCompare(String(r[0]))))}function kK(e){let t=[],r=new Map;for(let n of e){let i=n.flags??{};if(Object.keys(i).length===0)continue;let s=IK(i),a=r.get(s);if(a){a.names.push(n.name);continue}let l={names:[n.name],flags:i};r.set(s,l),t.push(l)}let o=[];for(let n of t)o.push("",`${n.names.join(" / ")} options:`),o.push(...mO(n.flags));return o}function gO(e){let t=[e.intro,"",`Usage: ${e.cliName} ${e.usage??"<command> [args]"}`,"","Commands:",...EK(e.commands)];if(e.globalFlags&&Object.keys(e.globalFlags).length>0)t.push("","Options:",...mO(e.globalFlags));return t.push(...kK(e.commands)),t.join(`
|
|
773
|
+
`)}function yO(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function ot(e,t){let r=e[t];return typeof r==="string"?r:void 0}function fs(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var pf={name:"@rizom/ops",version:"0.2.0-alpha.850",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Lv();wi();import{writeFile as See}from"fs/promises";import{join as iB}from"path";import{createSign as hG,generateKeyPairSync as gG}from"crypto";import{mkdir as yG,writeFile as yD}from"fs/promises";import{join as bD}from"path";async function A9(e){let t=await e.text();if(!t.trim())return;try{return JSON.parse(t)}catch{return t}}async function Ya(e,t,r){let o=await A9(e),n=t.safeParse(o);if(!e.ok||!n.success){let i=r.formatError??I9;throw Error(`${r.label}${i(e,o)}`)}return n.data}function I9(e,t){let r=t===void 0?"":`: ${typeof t==="string"?t:JSON.stringify(t)}`;return` (${e.status} ${e.statusText}${r})`}ue();var bG="2.5.4.3",SG="1.2.840.113549.1.1.11",wD="https://api.cloudflare.com/client/v4",vG="origin-rsa",wG=5475,xD=15000;function _D(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}var SD=c.looseObject({message:c.string().optional()}),xG=c.looseObject({errors:c.array(SD).optional(),messages:c.array(SD).optional()}),_G=c.looseObject({certificate:c.string().min(1),expires_on:c.string().optional()}),EG=c.looseObject({success:c.literal(!0),result:_G}),AG=c.looseObject({success:c.literal(!0)});function IG(){let{privateKey:e,publicKey:t}=gG("rsa",{modulusLength:2048,privateKeyEncoding:{type:"pkcs8",format:"pem"},publicKeyEncoding:{type:"spki",format:"der"}});return{privateKeyPem:e,publicKeyDer:Buffer.from(t)}}function kG(e,t){let r=Ed(PG(Ed(vD(bG),OG(e)))),o=Ed($G(0),r,Buffer.from(t.publicKeyDer),NG(0,Buffer.alloc(0))),n=hG("sha256").update(o).sign(t.privateKeyPem),i=Ed(o,Ed(vD(SG),zG()),CG(n));return{csrPem:TG("CERTIFICATE REQUEST",i),certificationRequestInfoDer:o,signature:n}}async function RG(e,t,r,o){let n=await e(`${wD}/certificates`,{method:"POST",headers:_D(t),body:JSON.stringify({hostnames:[o,`*.${o}`],requested_validity:wG,request_type:vG,csr:r}),signal:AbortSignal.timeout(xD)}),i=await Ya(n,EG,{label:"Cloudflare Origin CA request failed",formatError:AD}),a={certificatePem:`${i.result.certificate.trim()}
|
|
773
774
|
`};if(i.result.expires_on)a.expiresOn=i.result.expires_on;return a}async function ED(e,t,r){let o=await e(`${wD}/zones/${r}/settings/ssl`,{method:"PATCH",headers:_D(t),body:JSON.stringify({value:"strict"}),signal:AbortSignal.timeout(xD)});await Ya(o,AG,{label:"Cloudflare zone SSL update failed",formatError:AD})}function TG(e,t){let o=t.toString("base64").match(/.{1,64}/g)??[];return[`-----BEGIN ${e}-----`,...o,`-----END ${e}-----`,""].join(`
|
|
774
775
|
`)}function $G(e){if(e!==0)throw Error("Only zero-valued INTEGER encoding is currently supported");return Buffer.from([2,1,0])}function vD(e){let t=e.split(".").map((s)=>Number(s));if(t.length<2||t.some((s)=>Number.isNaN(s)))throw Error(`Invalid OID: ${e}`);let r=t[0],o=t[1];if(r===void 0||o===void 0)throw Error(`Invalid OID: ${e}`);let i=[r*40+o];for(let s of t.slice(2)){let a=LG(s);i.push(...a)}return $c(6,Buffer.from(i))}function OG(e){return $c(12,Buffer.from(e,"utf8"))}function CG(e){return $c(3,Buffer.concat([Buffer.from([0]),e]))}function zG(){return Buffer.from([5,0])}function Ed(...e){return $c(48,Buffer.concat(e))}function PG(...e){return $c(49,Buffer.concat(e))}function NG(e,t){return $c(160+e,t)}function $c(e,t){return Buffer.concat([Buffer.from([e]),DG(t.length),t])}function DG(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function LG(e){if(!Number.isInteger(e)||e<0)throw Error(`Invalid OID component: ${e}`);if(e===0)return[0];let t=[],r=e;while(r>0)t.unshift(r&127),r>>=7;for(let o=0;o<t.length-1;o+=1)t[o]=(t[o]??0)|128;return t}function AD(e,t){let r=ZG(t),o=r.length>0?`: ${r.join("; ")}`:"";return` (${e.status} ${e.statusText}${o})`}function ZG(e){let t=xG.safeParse(e);if(!t.success)return[];return[...t.data.errors??[],...t.data.messages??[]].map((r)=>r.message).filter((r)=>typeof r==="string"&&r.length>0)}async function ID(e,t,r){let o=IG(),{csrPem:n}=kG(r,o),i=await RG(e,t,n,r);return{certificatePem:i.certificatePem,privateKeyPem:o.privateKeyPem,...i.expiresOn!==void 0&&{expiresOn:i.expiresOn}}}async function kD(e,t){let r=bD(e,"origin.pem"),o=bD(e,"origin.key");return await yG(e,{recursive:!0}),await Promise.all([yD(r,t.certificatePem,"utf-8"),yD(o,t.privateKeyPem,{encoding:"utf-8",mode:384})]),{certificatePath:r,privateKeyPath:o}}gn();Nu();Mn();async function aB(e,t={}){try{return await vee(e,t),{success:!0}}catch(r){return{success:!1,message:Ve(r,"Certificate bootstrap failed")}}}async function vee(e,t={}){let r=await xt(e),o=xee(r,t.handle),n=o.domain,i=t.env??process.env,s=Lr(e),a=t.cfApiToken??jt("CF_API_TOKEN",i,s),l=t.cfZoneId??o.cloudflareZoneId??jt("CF_ZONE_ID",i,s);if(!a)throw Error("Missing CF_API_TOKEN");if(!l)throw Error("Missing CF_ZONE_ID");let u=t.fetchImpl??fetch,d=t.logger??console.log,p=await ID(u,a,n),m=iB(e,".brains-ops","certs",o.id),{certificatePath:h,privateKeyPath:S}=await kD(m,p),y=iB(m,"secrets.yaml");await See(y,wee(p.certificatePem,p.privateKeyPem),"utf-8"),await ED(u,a,l);let v=Ga(t.pushTo);if(v)await Si([["CERTIFICATE_PEM",p.certificatePem],["PRIVATE_KEY_PEM",p.privateKeyPem]],{logger:d,runCommand:t.runCommand??tr});if(d(`Issued ${o.id} Origin CA cert for ${n} and *.${n}`),d(`Wrote ${h}`),d(`Wrote ${S}`),d(`Wrote ${y}`),p.expiresOn)d(`Expires on ${p.expiresOn}`);if(d("Cloudflare zone SSL mode set to Full (strict)"),v)d(`Pushed CERTIFICATE_PEM and PRIVATE_KEY_PEM to ${v}`);return{domain:n,certificatePath:h,privateKeyPath:S,certificatePem:p.certificatePem,secretsSnippetPath:y}}function wee(e,t){return[`certificatePem: ${sB(e)}`,`privateKeyPem: ${sB(t)}`,""].join(`
|
|
775
776
|
`)}function sB(e){return`"${e.replace(/"/g,"\\\"").replace(/\n/g,"\\n")}"`}function xee(e,t){if(!t)return{id:"shared",domain:_ee(e.pilot.domainSuffix)};let r=e.users.find((o)=>o.handle===t);if(!r)throw Error(`Unknown user handle: ${t}`);return{id:t,domain:r.domain,...r.cloudflareZoneId?{cloudflareZoneId:r.cloudflareZoneId}:{}}}function _ee(e){let t=e.trim().replace(/^\./,"").replace(/\.$/,"");if(!t||t.includes("*"))throw Error(`Invalid pilot domainSuffix: ${e}`);return t}import{chmod as GI,mkdir as pg,readFile as uB,writeFile as lB}from"fs/promises";import{dirname as Ree,join as Mc}from"path";import{fileURLToPath as Tee}from"url";wi();Pd();Xs();var $ee=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/pull-local-models.ts","deploy/scripts/reload-homeserver.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],QI=new Set([".kamal/hooks/pre-deploy"]),Oee=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),Cee=Tee(new URL("../templates/rover-pilot/",import.meta.url));function Qn(e){return(t)=>t.includes(e)}function zee(e){return iP.find((t)=>e===`deploy/scripts/${t}`)}function YI(e){return e.replace(/\n {2}secret:\n(?: {4}- .*\n)+\nvolumes:\n/,`
|
|
@@ -777,22 +778,27 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
|
777
778
|
- __DYNAMIC_SECRETS__
|
|
778
779
|
|
|
779
780
|
volumes:
|
|
780
|
-
`)}function Pee(e){return lP(e,"rover",YI)}function Nee(e){if(e.includes("DISCORD_APPLICATION_ID")&&e.includes("ATPROTO_APP_PASSWORD"))return!1;let t=Qa(YI(e)),r=Qa(YI(hm(gm({serviceName:"rover"}))));return t===r}var Dee=[/\n# Stored with the per-user Discord credentials and injected at deploy time\.\n# @sensitive\nDISCORD_PUBLIC_KEY=\n\n# @sensitive\nDISCORD_APPLICATION_ID=\n/,/\n# AT Protocol publishing\/discovery \(optional, per-user\)\n# Comes from the decrypted users\/<handle>\.secrets\.yaml\.age file when configured\.\n# @sensitive\nATPROTO_APP_PASSWORD=\n/],Lee=[/# OpenAI, the provider of the canonical chat and embedding models\n[^]*?\nGOOGLE_GENERATIVE_AI_API_KEY=\n/,/# AI provider\n[^]*?\nAI_API_KEY=\n/];function Zee(e,t){let r=(o)=>Dee.reduce((n,i)=>n.replace(i,`
|
|
781
|
+
`)}function Pee(e){return lP(e,"rover",YI)}function Nee(e){if(e.includes("DISCORD_APPLICATION_ID")&&e.includes("ATPROTO_APP_PASSWORD")&&e.includes("RESEND_API_KEY"))return!1;let t=Qa(YI(e)),r=Qa(YI(hm(gm({serviceName:"rover"}))));return t===r}var Dee=[/\n# Stored with the per-user Discord credentials and injected at deploy time\.\n# @sensitive\nDISCORD_PUBLIC_KEY=\n\n# @sensitive\nDISCORD_APPLICATION_ID=\n/,/\n# AT Protocol publishing\/discovery \(optional, per-user\)\n# Comes from the decrypted users\/<handle>\.secrets\.yaml\.age file when configured\.\n# @sensitive\nATPROTO_APP_PASSWORD=\n/,/\n# Resend newsletter delivery \(optional, per-user\)\n# Comes from the decrypted users\/<handle>\.secrets\.yaml\.age file when configured\.\n# @sensitive\nRESEND_API_KEY=\n/],Lee=[/# OpenAI, the provider of the canonical chat and embedding models\n[^]*?\nGOOGLE_GENERATIVE_AI_API_KEY=\n/,/# AI provider\n[^]*?\nAI_API_KEY=\n/];function Zee(e,t){let r=(o)=>Dee.reduce((n,i)=>n.replace(i,`
|
|
781
782
|
`),Lee.reduce((n,i)=>n.replace(i,`__PROVIDER_KEYS__
|
|
782
|
-
`),o))
|
|
783
|
+
`),o)).replace(/\n{3,}/g,`
|
|
784
|
+
|
|
785
|
+
`);return r(e)===r(t)}var jee=[['writeSecretGitHubEnv("AI_API_KEY", secrets["aiApiKey"]);','writeSecretGitHubEnv("OPENAI_API_KEY", secrets["openaiApiKey"]);'],[`"shared_ai_api_key_secret_name",
|
|
783
786
|
requireFlatValue(pilot, "aiApiKey", "pilot.yaml"),`,`"shared_openai_api_key_secret_name",
|
|
784
787
|
requireFlatValue(pilot, "openaiApiKey", "pilot.yaml"),`]],Bee=[`writeSecretGitHubEnv("DISCORD_PUBLIC_KEY", secrets["discordPublicKey"]);
|
|
785
788
|
writeSecretGitHubEnv("DISCORD_APPLICATION_ID", secrets["discordApplicationId"]);
|
|
786
789
|
`,`writeSecretGitHubEnv("ATPROTO_APP_PASSWORD", secrets["atprotoAppPassword"]);
|
|
790
|
+
`,`// Per-user Resend key for the newsletter (optional; from the user's encrypted
|
|
791
|
+
// secrets file). It grants its whole Resend account, so it is never shared.
|
|
792
|
+
writeSecretGitHubEnv("RESEND_API_KEY", secrets["resendApiKey"]);
|
|
787
793
|
`];function Uee(e,t){let r=(o)=>Bee.reduce((n,i)=>n.replace(i,""),jee.reduce((n,[i,s])=>n.replace(i,s),o));return r(e)===r(t)}function Mee(e){return e.includes('if (eventName !== "push") {')&&e.includes('const currentSha = requireEnv("GITHUB_SHA");')||e.includes("path.match(/^users\\/([^/]+)\\/")&&!e.includes("existsSync(`users/${handle}.yaml`)")}var qee={".env.schema":Zee,"deploy/Dockerfile":(e)=>cP(e),"deploy/kamal/deploy.yml":(e)=>Pee(e)||Nee(e),"deploy/scripts/decrypt-user-secrets.ts":Uee,"deploy/scripts/resolve-deploy-handles.ts":(e)=>Mee(e),"deploy/scripts/helpers.ts":Qn('"@rizom/ops/deploy"'),"deploy/scripts/resolve-user-config.ts":Qn("sitePackagesFor"),"deploy/scripts/resolve-missing-images.ts":Qn("runResolveMissingImages"),"deploy/scripts/sync-content-repo.ts":Qn("GIT_SYNC_TOKEN"),"deploy/scripts/reload-homeserver.ts":Qn("export async function reloadHomeserver"),".github/workflows/build.yml":Qn("resolve-missing-images.ts"),".github/workflows/deploy.yml":Qn("install-health-watchdog.ts"),".github/workflows/offboard.yml":Qn("user:offboard"),".github/workflows/reconcile.yml":Qn("brains-ops reconcile"),".github/workflows/upgrade.yml":Qn("brains-ops upgrade")};function Fee(e,t,r){let o=zee(e);if(o&&sP(o,t,r))return!0;return qee[e]?.(t,r)??!1}async function dB(e){await pg(e,{recursive:!0});let t=Mc(e,"views","users.md"),r=await Ir(t),o=await Ir(Mc(e,"pilot.yaml"));await pg(Mc(e,"users"),{recursive:!0}),await pg(Mc(e,"cohorts"),{recursive:!0});let n=$ee.filter((i)=>!(o&&Oee.has(i))).map(async(i)=>{let s=Mc(e,i);await pg(Ree(s),{recursive:!0}),await Jee(i,s)});if(await Promise.all(n),!r)await Pi(e)}async function Jee(e,t){let r=await Kee(e);try{if(await lB(t,r,{flag:"wx"}),QI.has(e))await GI(t,493);return}catch(n){if(!Vee(n,"EEXIST"))throw n}let o=await uB(t,"utf8");if(o===r){if(QI.has(e))await GI(t,493);return}if(!Fee(e,o,r))return;if(await lB(t,r),QI.has(e))await GI(t,493)}async function Kee(e){if(e===".gitignore")return`node_modules/
|
|
788
794
|
.brains-ops/
|
|
789
795
|
users/*.secrets.yaml
|
|
790
|
-
`;if(e==="deploy/Dockerfile")return aP();if(e==="deploy/kamal/deploy.yml")return gm({serviceName:"rover"});if(e===".kamal/hooks/pre-deploy")return Zv({deployConfigPath:"deploy/kamal/deploy.yml",brainYamlPath:"${BRAIN_YAML_PATH:-brain.yaml}"});let t=Mc(Cee,e),r=await uB(t,"utf8");return Hee(r)}function Hee(e){return e.replaceAll("__BRAINS_OPS_VERSION__",pf.version).replaceAll("__BUN_VERSION__",Bun.version).replaceAll("__PREDEPLOY_BACKUP_SKIP_INPUT__",jv).replaceAll("__PREDEPLOY_BACKUP_SKIP_CONDITION__",Bv)}function Vee(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}gn();ok();rk();$o();import{lookup as nte}from"dns/promises";async function Ld(e,t,r,o){let n=new AbortController,i=setTimeout(()=>n.abort(),o);try{return await e(t,{...r,signal:n.signal})}finally{clearTimeout(i)}}var RB=5000;function TB(e={}){let t=e.fetchImpl??fetch,r=e.lookupHost??nte;return async function(n){let i=await ote(n.domain,r),[s,a,l]=await Promise.all([kB(n.domain,"/health/ready",t),kB(n.domain,"/health/operate",t),ite(n.domain,t)]);return{dnsStatus:i,serverStatus:s,deployStatus:a,mcpStatus:l}}}async function ote(e,t){try{return(await t(e)).address?"ready":"failed"}catch{return"failed"}}async function kB(e,t,r){try{return(await Ld(r,`https://${e}${t}`,{method:"GET"},RB)).ok?"ready":"failed"}catch{return"failed"}}async function ite(e,t){try{let r=await Ld(t,`https://${e}/mcp`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{}})},RB);return r.status===401||r.ok?"ready":"failed"}catch{return"failed"}}Zd();async function UB(e,t,r,o={}){let{registry:n,user:i}=await gg(e,t);await qc(e,n,[i],r,o)}Zd();async function yg(e,t,r={}){let{registry:o,users:n}=await BB(e);await qc(e,o,n,t,r)}import{createHash as kte}from"crypto";import{cp as Rte,lstat as Tte,mkdtemp as $te,readFile as Ote,readdir as Cte,readlink as zte,rm as Pte}from"fs/promises";import{tmpdir as Nte}from"os";import{basename as Dte,join as jd,relative as Lte,resolve as Zte,sep as jte}from"path";var Bte=new Set([".git",".operator",".brains-ops",".turbo","dist","node_modules"]);async function FB(e){let t=Zte(e),r=await $te(jd(Nte(),"brains-ops-reconcile-")),o=jd(r,"repo");try{await Rte(t,o,{recursive:!0,errorOnExist:!0,force:!1,filter:(a)=>Ute(t,a)});let n=await lk(o);await MB(o);let i=await lk(o);await MB(o);let s=await lk(o);return{firstPassChangedFiles:qB(n,i),secondPassChangedFiles:qB(i,s)}}finally{await Pte(r,{recursive:!0,force:!0})}}function Ute(e,t){let r=Lte(e,t);if(r.length===0)return!0;if(r.split(jte).some((n)=>Bte.has(n)))return!1;if(r===".env"||r===".env.local")return!1;return!Dte(r).endsWith(".secrets.yaml")}async function MB(e){await yg(e,void 0,{env:{},contentRepoRemoteResolver:()=>{return},fetchImpl:async()=>{throw Error("Dry-run reconcile attempted external HTTP access")},runCommand:async()=>{throw Error("Dry-run reconcile attempted a subprocess")}})}async function lk(e){let t=new Map;return await JB(e,"",t),t}async function JB(e,t,r){let o=jd(e,t),n=await Cte(o,{withFileTypes:!0});n.sort((i,s)=>i.name.localeCompare(s.name));for(let i of n){let s=jd(t,i.name),a=jd(e,s);if(i.isDirectory()){await JB(e,s,r);continue}let u=(await Tte(a)).isSymbolicLink()?`symlink:${await zte(a)}`:await Ote(a);r.set(s,kte("sha256").update(u).digest("hex"))}}function qB(e,t){return[...new Set([...e.keys(),...t.keys()])].filter((o)=>e.get(o)!==t.get(o)).sort()}Zd();async function KB(e,t,r,o={}){let{registry:n,users:i}=await jB(e,t);await qc(e,n,i,r,o)}Pd();fk();wi();Nu();Mn();import{readFileSync as
|
|
791
|
-
`,"utf-8");if(h.length===0)throw Error(`Unable to derive a public key from ${d}`);let S=await
|
|
792
|
-
`)}function
|
|
793
|
-
`)}function
|
|
794
|
-
`)}async function cU(e,t){try{return await lU(e,t,{flag:"wx"}),!0}catch(r){if(
|
|
796
|
+
`;if(e==="deploy/Dockerfile")return aP();if(e==="deploy/kamal/deploy.yml")return gm({serviceName:"rover"});if(e===".kamal/hooks/pre-deploy")return Zv({deployConfigPath:"deploy/kamal/deploy.yml",brainYamlPath:"${BRAIN_YAML_PATH:-brain.yaml}"});let t=Mc(Cee,e),r=await uB(t,"utf8");return Hee(r)}function Hee(e){return e.replaceAll("__BRAINS_OPS_VERSION__",pf.version).replaceAll("__BUN_VERSION__",Bun.version).replaceAll("__PREDEPLOY_BACKUP_SKIP_INPUT__",jv).replaceAll("__PREDEPLOY_BACKUP_SKIP_CONDITION__",Bv)}function Vee(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}gn();ok();rk();$o();import{lookup as nte}from"dns/promises";async function Ld(e,t,r,o){let n=new AbortController,i=setTimeout(()=>n.abort(),o);try{return await e(t,{...r,signal:n.signal})}finally{clearTimeout(i)}}var RB=5000;function TB(e={}){let t=e.fetchImpl??fetch,r=e.lookupHost??nte;return async function(n){let i=await ote(n.domain,r),[s,a,l]=await Promise.all([kB(n.domain,"/health/ready",t),kB(n.domain,"/health/operate",t),ite(n.domain,t)]);return{dnsStatus:i,serverStatus:s,deployStatus:a,mcpStatus:l}}}async function ote(e,t){try{return(await t(e)).address?"ready":"failed"}catch{return"failed"}}async function kB(e,t,r){try{return(await Ld(r,`https://${e}${t}`,{method:"GET"},RB)).ok?"ready":"failed"}catch{return"failed"}}async function ite(e,t){try{let r=await Ld(t,`https://${e}/mcp`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{}})},RB);return r.status===401||r.ok?"ready":"failed"}catch{return"failed"}}Zd();async function UB(e,t,r,o={}){let{registry:n,user:i}=await gg(e,t);await qc(e,n,[i],r,o)}Zd();async function yg(e,t,r={}){let{registry:o,users:n}=await BB(e);await qc(e,o,n,t,r)}import{createHash as kte}from"crypto";import{cp as Rte,lstat as Tte,mkdtemp as $te,readFile as Ote,readdir as Cte,readlink as zte,rm as Pte}from"fs/promises";import{tmpdir as Nte}from"os";import{basename as Dte,join as jd,relative as Lte,resolve as Zte,sep as jte}from"path";var Bte=new Set([".git",".operator",".brains-ops",".turbo","dist","node_modules"]);async function FB(e){let t=Zte(e),r=await $te(jd(Nte(),"brains-ops-reconcile-")),o=jd(r,"repo");try{await Rte(t,o,{recursive:!0,errorOnExist:!0,force:!1,filter:(a)=>Ute(t,a)});let n=await lk(o);await MB(o);let i=await lk(o);await MB(o);let s=await lk(o);return{firstPassChangedFiles:qB(n,i),secondPassChangedFiles:qB(i,s)}}finally{await Pte(r,{recursive:!0,force:!0})}}function Ute(e,t){let r=Lte(e,t);if(r.length===0)return!0;if(r.split(jte).some((n)=>Bte.has(n)))return!1;if(r===".env"||r===".env.local")return!1;return!Dte(r).endsWith(".secrets.yaml")}async function MB(e){await yg(e,void 0,{env:{},contentRepoRemoteResolver:()=>{return},fetchImpl:async()=>{throw Error("Dry-run reconcile attempted external HTTP access")},runCommand:async()=>{throw Error("Dry-run reconcile attempted a subprocess")}})}async function lk(e){let t=new Map;return await JB(e,"",t),t}async function JB(e,t,r){let o=jd(e,t),n=await Cte(o,{withFileTypes:!0});n.sort((i,s)=>i.name.localeCompare(s.name));for(let i of n){let s=jd(t,i.name),a=jd(e,s);if(i.isDirectory()){await JB(e,s,r);continue}let u=(await Tte(a)).isSymbolicLink()?`symlink:${await zte(a)}`:await Ote(a);r.set(s,kte("sha256").update(u).digest("hex"))}}function qB(e,t){return[...new Set([...e.keys(),...t.keys()])].filter((o)=>e.get(o)!==t.get(o)).sort()}Zd();async function KB(e,t,r,o={}){let{registry:n,users:i}=await jB(e,t);await qc(e,n,i,r,o)}Pd();fk();wi();Nu();Mn();import{readFileSync as Qte}from"fs";async function eU(e,t={}){let r=t.env??process.env,o=t.logger??console.log,n=Lr(e),i=Mv(`${e}/.env.schema`),s=Xte(i),a=[],l=[],u=new Map;for(let p of s){u.set(p.key,p.required);let m=ere(p.key,r,n,e);if(m===void 0||m.trim().length===0){l.push(p.key);continue}a.push([p.key,m])}if(a.length===0)throw Error("No pushable local secrets found for this pilot repo");let d=(p)=>u.get(p)??!1;if(t.dryRun)return o(`Dry run: would push ${a.length} secrets to GitHub Secrets.`),o(`Secrets: ${a.map(([p])=>p).join(", ")}`),Pv(o,l,d),{pushedKeys:a.map(([p])=>p),skippedKeys:l,dryRun:!0};return await Si(a,{logger:o,runCommand:t.runCommand??tr}),Pv(o,l,d),{pushedKeys:a.map(([p])=>p),skippedKeys:l}}var Yte=new Set(["DISCORD_BOT_TOKEN","DISCORD_PUBLIC_KEY","DISCORD_APPLICATION_ID"]);function Xte(e){return e.filter((t)=>!Yte.has(t.key)).map((t)=>({key:t.key,required:t.required}))}function ere(e,t,r,o){let n=jt(`${e}_FILE`,t,r);if(n&&n.trim().length>0)return Qte(vi(n,o),"utf8");let i=jt(e,t,r);if(i===void 0||i.trim().length===0)return;return i}ue();import{execFileSync as tU}from"child_process";import{chmodSync as tre,existsSync as rre,mkdirSync as nre,readFileSync as rU,writeFileSync as ore}from"fs";import{dirname as ire,join as sre}from"path";import{homedir as are}from"os";Fv();Nu();Mn();var nU=c.object({id:c.number(),name:c.string(),public_key:c.string()}),cre=c.object({ssh_keys:c.array(nU)}),lre={createEd25519KeyPair(e,t){tU("ssh-keygen",["-t","ed25519","-f",e,"-C",t,"-N",""],{stdio:"ignore"})},derivePublicKey(e){return tU("ssh-keygen",["-y","-f",e],{encoding:"utf-8",stdio:["ignore","pipe","inherit"]}).trim()}};async function mk(e,t={}){try{let r=await oU(e,t);return{success:!0,message:r.createdLocalKey?`SSH deploy key ready at ${r.privateKeyPath}`:`SSH deploy key already ready at ${r.privateKeyPath}`}}catch(r){return{success:!1,message:Ve(r,"SSH key bootstrap failed")}}}async function oU(e,t={}){let r=t.env??process.env,o=Lr(e),n=t.logger??console.log,i=t.fetchImpl??fetch,s=t.sshKeygen??lre,a=jt("HCLOUD_TOKEN",r,o);if(!a)throw Error("Missing HCLOUD_TOKEN");let l=jt("HCLOUD_SSH_KEY_NAME",r,o);if(!l)throw Error("Missing HCLOUD_SSH_KEY_NAME");let u=jt("KAMAL_SSH_PRIVATE_KEY_FILE",r,o),d=u?vi(u,e):sre(are(),".ssh",`${dre(l)}_ed25519`),p=`${d}.pub`,m=!1;if(!rre(d))nre(ire(d),{recursive:!0,mode:448}),s.createEd25519KeyPair(d,l),m=!0;tre(d,384);let h;if(m)h=rU(p,"utf-8").trim();else h=s.derivePublicKey(d),ore(p,`${h}
|
|
797
|
+
`,"utf-8");if(h.length===0)throw Error(`Unable to derive a public key from ${d}`);let S=await ure({fetchImpl:i,hcloudToken:a,publicKey:h,sshKeyName:l}),y=Ga(t.pushTo);if(y)await Si([["KAMAL_SSH_PRIVATE_KEY",rU(d,"utf-8")]],{logger:n,runCommand:t.runCommand??tr});if(n(m?`Created ${d}`:`Reusing ${d}`),n(S?`Registered Hetzner SSH key ${l}`:`Hetzner SSH key ${l} already exists`),y)n(`Pushed KAMAL_SSH_PRIVATE_KEY to ${y}`);return{createdHetznerKey:S,createdLocalKey:m,privateKeyPath:d,publicKeyPath:p,sshKeyName:l}}async function ure(e){let t=new URL("https://api.hetzner.cloud/v1/ssh_keys");t.searchParams.set("name",e.sshKeyName);let r=await e.fetchImpl(t.toString(),{headers:{Authorization:`Bearer ${e.hcloudToken}`,"Content-Type":"application/json"}}),{ssh_keys:o}=await Ya(r,cre,{label:"Hetzner SSH key lookup failed"}),[n]=o;if(n){if(n.public_key.trim()!==e.publicKey)throw Error(`Existing Hetzner SSH key ${e.sshKeyName} does not match the local public key`);return!1}let i=await e.fetchImpl("https://api.hetzner.cloud/v1/ssh_keys",{method:"POST",headers:{Authorization:`Bearer ${e.hcloudToken}`,"Content-Type":"application/json"},body:JSON.stringify({name:e.sshKeyName,public_key:e.publicKey})});return await Ya(i,c.object({ssh_key:nU}),{label:"Hetzner SSH key create failed"}),!0}function dre(e){return e.replace(/[^A-Za-z0-9._-]+/g,"_")}Dd();vg();Vn();$o();Xs();import{mkdir as aU,readFile as pre,writeFile as lU}from"fs/promises";import{basename as fre,join as Fc}from"path";async function uU(e,t,r){let o=br.parse(t),n=br.parse(r.cohort),i=Fc(e,"users"),s=Fc(e,"cohorts"),a=Fc(i,`${o}.yaml`),l=Fc(i,`${o}.secrets.yaml`),u=Fc(i,`${o}.secrets.yaml.age`),d=Fc(s,`${n}.yaml`);await Promise.all([aU(i,{recursive:!0}),aU(s,{recursive:!0})]);let p=r.discord===!0||Boolean(r.anchorId),m=await cU(a,gre(o,p,r.anchorId)),S=await Ir(u)?!1:await cU(l,yre(o,p)),{addedToCohort:y}=await mre(d,o);return{handle:o,cohort:n,userPath:a,secretsTemplatePath:l,cohortPath:d,createdUser:m,createdSecretsTemplate:S,addedToCohort:y}}async function mre(e,t){let r=await hre(e);if(r.members.includes(t))return{addedToCohort:!1};let o={...r,members:[...r.members,t].sort()};return await lU(e,bre(o)),{addedToCohort:!0}}async function hre(e){try{let t=await pre(e,"utf8"),r=yr(t,hn);if(!r.ok)throw Error(`${fre(e)}: ${r.error}`);return r.data}catch(t){if(fg(t))return{members:[]};throw t}}function gre(e,t,r){return[`handle: ${e}`,"anchorProfile:",` name: ${wre(e)}`,"discord:",` enabled: ${String(t)}`,...t&&r?[` anchorUserId: ${JSON.stringify(r)}`]:[],""].join(`
|
|
798
|
+
`)}function yre(e,t){return["# local per-user secret staging file",`# fill values, run \`bunx brains-ops secrets:encrypt . ${e}\`, then the plaintext file will be removed`,...t?["discordBotToken: "]:[],"atprotoAppPassword: ","# For custom-domain sites, paste PEMs with literal \\n escapes.","certificatePem: ","privateKeyPem: ",""].join(`
|
|
799
|
+
`)}function bre(e){return["members:",...e.members.map((t)=>` - ${t}`),...e.brainVersionOverride?[`brainVersionOverride: ${e.brainVersionOverride}`]:[],...e.bundlesOverride?["bundlesOverride:",...e.bundlesOverride.map((t)=>` - ${t}`)]:[],...e.addOverride?["addOverride:",...e.addOverride.map((t)=>` - ${t}`)]:[],...e.removeOverride?["removeOverride:",...e.removeOverride.map((t)=>` - ${t}`)]:[],...e.openaiApiKeyOverride?[`openaiApiKeyOverride: ${e.openaiApiKeyOverride}`]:[],...e.gitSyncTokenOverride?[`gitSyncTokenOverride: ${e.gitSyncTokenOverride}`]:[],""].join(`
|
|
800
|
+
`)}async function cU(e,t){try{return await lU(e,t,{flag:"wx"}),!0}catch(r){if(Sre(r))return!1;throw r}}function Sre(e){return vre(e,"EEXIST")}function vre(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function wre(e){return e.split("-").filter((t)=>t.length>0).map(sU).join(" ")}ue();gn();var xre=c.looseObject({status:c.string(),operationalStatus:c.string(),checks:c.array(c.looseObject({name:c.string(),status:c.string(),message:c.string().optional()})).default([]),app:c.looseObject({daemons:c.array(c.looseObject({name:c.string().optional(),status:c.string().optional(),health:c.looseObject({status:c.string().optional(),message:c.string().optional()}).optional()})).default([])}).default({daemons:[]})});async function pU(e,t,r={}){let o=r.fetchImpl??fetch,i=(await xt(e)).users.find((m)=>m.handle===t);if(!i)throw Error(`Unknown pilot user: ${t}`);let s=`https://${i.domain}`,a=[],l=[],u=c.number().int().positive().max(30).parse(r.operationalRetryAttempts??6),d=c.number().int().nonnegative().max(60000).parse(r.operationalRetryDelayMs??1e4),p=r.sleep??((m)=>new Promise((h)=>setTimeout(h,m)));if(await wg("health",()=>_re(o,s,u,d,p),a,l),await wg("mcp-auth-gate",()=>Ire(o,s),a,l),i.bundles.includes("site"))await wg("site",()=>dU(o,`${s}/`,"site"),a,l),await wg("studio",()=>dU(o,`${s}/studio`,"studio"),a,l),r.logger?.("WARN Manual check still required: passkey setup/handoff completed from the setup email.");return{handle:i.handle,bundles:i.bundles,domain:i.domain,contentRepo:i.contentRepo,checks:a,failedChecks:l}}async function wg(e,t,r,o){try{await t(),r.push(e)}catch(n){o.push({name:e,message:Ve(n)})}}async function _re(e,t,r,o,n){let i;for(let s=1;s<=r;s++)try{await Ere(e,t);return}catch(a){if(i=a,s<r)await n(o)}throw i}async function Ere(e,t){let o=await hk(e,`${t}/health/operate`,{method:"GET"}),n=await o.json().catch(()=>null),i=xre.safeParse(n);if(!o.ok){let a=i.success?i.data.checks.filter((l)=>l.status!=="healthy").slice(0,10).map((l)=>`${l.name}: ${Are(l.message??l.status)}`):[];throw Error(`/health/operate returned ${o.status}, expected 200${a.length>0?` (${a.join("; ")})`:""}`)}if(!i.success)throw Error(`/health/operate response did not match expected shape: ${i.error.message}`);let s=i.data;if(s.status!=="ready")throw Error(`/health/operate status is ${s.status}, expected ready`);if(s.operationalStatus!=="operational")throw Error(`/health/operate operationalStatus is ${s.operationalStatus}, expected operational`);for(let a of s.app.daemons){let l=a.status??"unknown",u=a.health?.status;if(l==="error"||u==="unhealthy")throw Error(`daemon ${a.name??"unknown"} is unhealthy (${l}/${u??"unknown"})`)}}function Are(e){let t=e.replaceAll(/\s+/g," ").trim();return t.length<=300?t:`${t.slice(0,297)}...`}async function Ire(e,t){let r=await hk(e,`${t}/mcp`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize"})});if(r.status<400||r.status>=500)throw Error(`unauthenticated POST /mcp returned ${r.status}, expected a 4xx auth failure`)}async function dU(e,t,r){let o=await hk(e,t,{method:"GET"});if(o.status>=400)throw Error(`${r} ${t} returned ${o.status}, expected < 400`)}function hk(e,t,r){return Ld(e,t,{...r,redirect:"follow"},20000)}var ZJ="brains-ops",uO={type:"string",placeholder:"<target>",description:"Push target (`gh` or `github`)"},Ub={type:"boolean",description:"Show what would happen without writing anything"};function mt(e){return{success:!1,message:hO(ZJ,e)}}var jJ=nt({name:"init",usage:"<repo>",description:"Create a pilot repo skeleton",run:async({args:e})=>{let t=e[0];if(!t)return mt(jJ);return await dB(t),{success:!0,message:`Initialized ${t}`}}}),BJ=nt({name:"upgrade",usage:"<repo>",description:"Bump @rizom/ops and refresh the generated scaffold",flags:{to:{type:"string",placeholder:"<version>",description:"Explicit @rizom/ops version (`latest` by default)"}},run:async({args:e,flags:t})=>{let r=e[0];if(!r)return mt(BJ);let o=ot(t,"to"),{upgradePilotRepo:n}=await Promise.resolve().then(() => (hU(),mU)),{from:i,to:s}=await n(r,{...o&&o!=="latest"?{version:o}:{}});return{success:!0,message:i===s?`Already at @rizom/ops@${s}; scaffold refreshed`:`Upgraded @rizom/ops ${i} -> ${s}; scaffold refreshed`}}}),UJ=nt({name:"images:lock",usage:"<repo> [--brain-version <version>] [--site-packages <pins>]",description:"Create immutable runtime dependency locks for operator review (no build or deploy)",flags:{"brain-version":{type:"string",placeholder:"<version>",description:"Lock one exact Brain version instead of the declared fleet"},"site-packages":{type:"string",placeholder:"<pins>",description:"Exact site/theme pins for an explicit Brain version"}},run:async({args:e,flags:t},r)=>{let o=e[0],n=ot(t,"brain-version"),i=ot(t,"site-packages");if(!o||i!==void 0&&!n)return mt(UJ);if(n!==void 0)Ct.parse(n);let{users:s}=await xt(o),a=await IB({users:s,brainVersionInput:n,sitePackagesInput:i,imageExists:async()=>!1,verifyImage:async()=>{throw Error("Lock generation must not inspect images")}}),l=[];for(let u of a){let d=await EB(o,u,r.imageLockRunCommand);l.push(`${d}: ${u.tag}`)}return{success:!0,message:["Review and commit runtime dependency locks before building:",...l].join(`
|
|
795
801
|
`)}}}),MJ=nt({name:"crossover:stage",usage:"<source-repo> <output-dir> <bundle-review.yaml> [site-pins.yaml]",description:"Stage a reviewed capability-bundle crossover copy",run:async({args:e})=>{let t=e[0],r=e[1],o=e[2],n=e[3];if(!t||!r||!o)return mt(MJ);let{loadCapabilityBundleReview:i,loadReviewedSitePins:s,stageLegacyCrossover:a}=await Promise.resolve().then(() => (Gq(),Wq)),l=await i(o),u=n?await s(n):void 0,d=await a(t,r,{bundleReview:l,sitePins:u});return{success:!0,message:`Staged ${d.changedFiles.length} reviewed crossover files in ${d.outputDir}`}}}),qJ=nt({name:"migrate:provider-keys",usage:"<repo>",description:"Move a pilot repo from the legacy AI_API_KEY to the OpenAI key its brains read",run:async({args:e})=>{let t=e[0];if(!t)return mt(qJ);let{migratePilotRepoProviderKeys:r}=await Promise.resolve().then(() => (my(),Rq)),o=await r(t,process.env);return{success:!0,message:o.length===0?`${t} already uses the OpenAI key`:`Migrated ${o.length} files: ${o.join(", ")}. Then run brains-ops init ${t} to refresh the deploy scripts.`}}}),FJ=nt({name:"render",usage:"<repo>",description:"Render the observed users table to views/users.md",run:async({args:e},t)=>{let r=e[0];if(!r)return mt(FJ);let o=t.resolveStatus??TB({...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},...t.lookupHost?{lookupHost:t.lookupHost}:{}});return await Pi(r,{resolveStatus:o}),{success:!0,message:`Rendered ${r}/views/users.md`}}}),JJ=nt({name:"user:add",usage:"<repo> <handle> --cohort <cohort> [--discord] [--anchor-id <id>]",description:"Add a user to a cohort",flags:{cohort:{type:"string",placeholder:"<cohort>",description:"Cohort the user joins"},discord:{type:"boolean",description:"Enable Discord for the user (browser chat is the default)"},"anchor-id":{type:"string",placeholder:"<id>",description:"Discord anchor user id stored on the user record (implies --discord)"}},run:async({args:e,flags:t})=>{let r=e[0],o=e[1],n=ot(t,"cohort");if(!r||!o||!n)return mt(JJ);let i=ot(t,"anchor-id");return await uU(r,o,{cohort:n,...fs(t,"discord")?{discord:!0}:{},...i?{anchorId:i}:{}}),{success:!0,message:`Added ${o} to ${n}`}}}),KJ=nt({name:"user:offboard",usage:"<repo> <handle>... [--apply --confirm sunset:<sorted-comma-separated-handles>]",description:"Archive content and remove pilot users, DNS, and servers",flags:{apply:{type:"boolean",description:"Apply the plan (defaults to a read-only dry run)"},confirm:{type:"string",placeholder:"<confirmation>",description:"Exact batch confirmation required with --apply"}},run:async({args:e,flags:t},r)=>{let o=e[0],n=e.slice(1);if(!o||n.length===0)return mt(KJ);let i=fs(t,"apply")??!1,s=ot(t,"confirm"),{offboardPilotUsers:a}=await Promise.resolve().then(() => (X6(),Y6)),l=await a(o,{handles:n,dryRun:!i,...s?{confirmation:s}:{},...r.env?{env:r.env}:{},...r.fetchImpl?{fetchImpl:r.fetchImpl}:{},...r.logger?{logger:r.logger}:{},...r.pilotOffboardDriver?{driver:r.pilotOffboardDriver}:{}});return{success:!0,message:l.dryRun?`Dry run: ${l.handles.length} pilot user(s); apply with --apply --confirm ${l.confirmation}`:`Offboarded ${l.handles.length} pilot user(s)`}}}),HJ=nt({name:"onboard",usage:"<repo> <handle>",description:"Generate a user's brain.yaml and .env",run:async({args:e},t)=>{let r=e[0],o=e[1];if(!r||!o)return mt(HJ);return await UB(r,o,t.runner,{...t.env?{env:t.env}:{}}),{success:!0,message:`Onboarded ${o}`}}}),VJ=nt({name:"age-key:bootstrap",usage:"<repo>",description:"Generate the pilot age key and optional GitHub secret",flags:{"push-to":uO},run:async({args:e,flags:t},r)=>{let o=e[0];if(!o)return mt(VJ);let n=ot(t,"push-to");return Xz(o,{...r.logger?{logger:r.logger}:{},...n?{pushTo:n}:{},...r.bootstrapRunCommand?{runCommand:r.bootstrapRunCommand}:{}})}}),WJ=nt({name:"ssh-key:bootstrap",usage:"<repo>",description:"Bootstrap a deploy SSH key and optional GitHub secret",flags:{"push-to":uO},run:async({args:e,flags:t},r)=>{let o=e[0];if(!o)return mt(WJ);let n=ot(t,"push-to");return mk(o,{...r.env?{env:r.env}:{},...r.fetchImpl?{fetchImpl:r.fetchImpl}:{},...r.logger?{logger:r.logger}:{},...n?{pushTo:n}:{},...r.bootstrapRunCommand?{runCommand:r.bootstrapRunCommand}:{},...r.sshKeygen?{sshKeygen:r.sshKeygen}:{}})}}),GJ=nt({name:"cert:bootstrap",usage:"<repo>",description:"Issue Cloudflare Origin CA certificates for pilot users",flags:{handle:{type:"string",placeholder:"<handle>",description:"Only issue the certificate for this user handle"},"push-to":uO},run:async({args:e,flags:t},r)=>{let o=e[0];if(!o)return mt(GJ);let n=ot(t,"handle"),i=ot(t,"push-to");return aB(o,{...r.env?{env:r.env}:{},...r.fetchImpl?{fetchImpl:r.fetchImpl}:{},...r.logger?{logger:r.logger}:{},...n?{handle:n}:{},...i?{pushTo:i}:{},...r.bootstrapRunCommand?{runCommand:r.bootstrapRunCommand}:{}})}}),QJ=nt({name:"secrets:push",usage:"<repo>",description:"Push env-backed local secrets to GitHub Secrets",flags:{"dry-run":Ub},run:async({args:e,flags:t},r)=>{let o=e[0];if(!o)return mt(QJ);let n=await eU(o,{env:r.env,logger:r.logger,dryRun:fs(t,"dry-run")});return{success:!0,message:n.dryRun?`Dry run: would push ${n.pushedKeys.length} secrets`:`Pushed ${n.pushedKeys.length} secrets`}}}),YJ=nt({name:"secrets:encrypt",usage:"<repo> <handle>",description:"Encrypt pilot secrets for a user with age",flags:{"dry-run":Ub},run:async({args:e,flags:t},r)=>{let o=e[0],n=e[1];if(!o||!n)return mt(YJ);let i=await XB(o,n,{env:r.env,logger:r.logger,dryRun:fs(t,"dry-run")});return{success:!0,message:i.dryRun?`Dry run: would encrypt ${i.encryptedKeys.length} secrets for ${n}`:`Encrypted ${i.encryptedKeys.length} secrets for ${n}`}}}),XJ=nt({name:"recover:retire-legacy-projection-job",usage:"<database> <job-id> --type <legacy-type> (--dry-run | --confirm retire:<job-id>)",description:"Retire one exact unowned pre-scheduler projection job",flags:{type:{type:"string",placeholder:"<legacy-type>",description:"Exact retired projection job type"},confirm:{type:"string",placeholder:"retire:<job-id>",description:"Exact job retirement confirmation"},"dry-run":Ub},run:async({args:e,flags:t},r)=>{let o=e[0],n=e[1],i=ot(t,"type"),s=ot(t,"confirm"),a=fs(t,"dry-run")??!1;if(!o||!n||!i||a===(s!==void 0))return mt(XJ);let{legacyProjectionJobTypeSchema:l}=await Promise.resolve().then(() => (J$(),F$)),u=l.safeParse(i);if(!u.success)return{success:!1,message:`Unsupported legacy projection job type: ${i}`};let d=r.legacyProjectionJobRecoveryRunner??(await Promise.resolve().then(() => (J$(),F$))).retireLegacyProjectionJob;try{let p=await d({databasePath:o,jobId:n,jobType:u.data,...s?{confirmation:s}:{},dryRun:a});return{success:!0,message:p.retired?`Retired unowned legacy projection job ${p.job.id} (${p.job.type})`:`Dry run: legacy projection job ${p.job.id} (${p.job.type}) is unowned and retirable`}}catch(p){return{success:!1,message:`Legacy projection job recovery failed: ${Ve(p)}`}}}}),eK=nt({name:"stress:directory-sync",usage:"<repo> <handle> --profile <regression|load|stress> --confirm stress:<handle> [--artifacts-dir <path>]",description:"Run a smoke-only directory-sync stress profile",flags:{profile:{type:"string",placeholder:"<profile>",description:"Stress profile (`regression`, `load`, or `stress`)"},confirm:{type:"string",placeholder:"stress:<handle>",description:"Explicit smoke target confirmation"},"artifacts-dir":{type:"string",placeholder:"<path>",description:"Directory for JSON, Markdown, samples, and logs"}},run:async({args:e,flags:t},r)=>{let o=e[0],n=e[1],i=ot(t,"profile"),s=ot(t,"confirm");if(!o||!n||!s||i!=="regression"&&i!=="load"&&i!=="stress")return mt(eK);let a=r.directorySyncStressRunner??(await Promise.resolve().then(() => (jb(),Zb))).runDeployedDirectorySyncStress,l=ot(t,"artifacts-dir"),u=await a({rootDir:o,handle:n,profile:i,confirmation:s,...l?{artifactsDir:l}:{},...r.env?{env:r.env}:{},...r.fetchImpl?{fetchImpl:r.fetchImpl}:{},...r.logger?{logger:r.logger}:{}});return{success:u.report.success,message:`${u.report.success?"Passed":"Failed"} ${i} directory-sync stress for ${n}; artifacts: ${u.artifactsDir}`}}}),tK=nt({name:"stress:directory-sync:verify-access",usage:"<repo> <handle> --confirm stress:<handle> [--artifacts-dir <path>]",description:"Verify smoke stress credentials without remote writes",flags:{confirm:{type:"string",placeholder:"stress:<handle>",description:"Explicit smoke target confirmation"},"artifacts-dir":{type:"string",placeholder:"<path>",description:"Directory for the access-check result"}},run:async({args:e,flags:t},r)=>{let o=e[0],n=e[1],i=ot(t,"confirm");if(!o||!n||!i)return mt(tK);let s=r.directorySyncStressAccessRunner??(await Promise.resolve().then(() => (jb(),Zb))).verifyDirectorySyncStressAccess,a=ot(t,"artifacts-dir"),l=await s({rootDir:o,handle:n,confirmation:i,...a?{artifactsDir:a}:{},...r.env?{env:r.env}:{}});return{success:l.success,message:`Verified directory-sync stress access for ${n} at ${l.remoteHead}; artifacts: ${l.artifactsDir}`}}}),rK=nt({name:"stress:directory-sync:cleanup",usage:"<repo> <handle> --confirm stress:<handle> [--artifacts-dir <path>]",description:"Remove residual smoke directory-sync stress probes",flags:{confirm:{type:"string",placeholder:"stress:<handle>",description:"Explicit smoke target confirmation"},"artifacts-dir":{type:"string",placeholder:"<path>",description:"Directory for the cleanup result"}},run:async({args:e,flags:t},r)=>{let o=e[0],n=e[1],i=ot(t,"confirm");if(!o||!n||!i)return mt(rK);let s=r.directorySyncStressCleanupRunner??(await Promise.resolve().then(() => (jb(),Zb))).cleanupDirectorySyncStress,a=ot(t,"artifacts-dir"),l=await s({rootDir:o,handle:n,confirmation:i,...a?{artifactsDir:a}:{},...r.env?{env:r.env}:{},...r.logger?{logger:r.logger}:{}});return{success:l.success,message:`${l.success?"Cleaned":"Failed to clean"} directory-sync stress probes for ${n}; removed ${l.probesRemoved}, remaining ${l.probesRemaining}`}}}),nK={confirm:{type:"string",placeholder:"watchdog-smoke:<handle>",description:"Explicit smoke target confirmation"},"run-id":{type:"string",placeholder:"<id>",description:"Stable workflow run identifier used for cleanup"},"artifacts-dir":{type:"string",placeholder:"<path>",description:"Directory for remote smoke evidence"}},oK=nt({name:"smoke:health-watchdog",usage:"<repo> <handle> --confirm watchdog-smoke:<handle> --run-id <id> [--artifacts-dir <path>]",description:"Run the smoke-fleet host watchdog isolation check",flags:nK,run:async({args:e,flags:t},r)=>{let o=e[0],n=e[1],i=ot(t,"confirm"),s=ot(t,"run-id");if(!o||!n||!i||!s)return mt(oK);let a=r.healthWatchdogSmokeRunner??(await lO().then(() => cO)).runHealthWatchdogSmoke,l=ot(t,"artifacts-dir"),u=await a({rootDir:o,handle:n,confirmation:i,runId:s,...l?{artifactsDir:l}:{},...r.env?{env:r.env}:{},...r.fetchImpl?{fetchImpl:r.fetchImpl}:{},...r.logger?{logger:r.logger}:{}});return{success:u.success,message:`Passed health watchdog smoke for ${n}; artifacts: ${u.artifactsDir}`}}}),iK=nt({name:"smoke:health-watchdog:cleanup",usage:"<repo> <handle> --confirm watchdog-smoke:<handle> --run-id <id> [--artifacts-dir <path>]",description:"Remove residual smoke-fleet watchdog fixtures",flags:nK,run:async({args:e,flags:t},r)=>{let o=e[0],n=e[1],i=ot(t,"confirm"),s=ot(t,"run-id");if(!o||!n||!i||!s)return mt(iK);let a=r.healthWatchdogSmokeCleanupRunner??(await lO().then(() => cO)).cleanupHealthWatchdogSmoke,l=ot(t,"artifacts-dir"),u=await a({rootDir:o,handle:n,confirmation:i,runId:s,...l?{artifactsDir:l}:{},...r.env?{env:r.env}:{},...r.fetchImpl?{fetchImpl:r.fetchImpl}:{},...r.logger?{logger:r.logger}:{}});return{success:u.success,message:`Cleaned health watchdog smoke fixtures for ${n}; artifacts: ${u.artifactsDir}`}}}),sK=nt({name:"verify-user",usage:"<repo> <handle>",description:"Probe a deployed user's endpoints",run:async({args:e},t)=>{let r=e[0],o=e[1];if(!r||!o)return mt(sK);let n=await pU(r,o,{...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},...t.logger?{logger:t.logger}:{},...t.verificationRetryAttempts!==void 0?{operationalRetryAttempts:t.verificationRetryAttempts}:{},...t.verificationRetryDelayMs!==void 0?{operationalRetryDelayMs:t.verificationRetryDelayMs}:{},...t.sleep?{sleep:t.sleep}:{}}),i=n.checks.length>0?n.checks.join(", "):"none";if(n.failedChecks.length>0){let s=n.failedChecks.map((a)=>` ${a.name}: ${a.message}`).join(`
|
|
796
802
|
`);return{success:!1,message:`Verified ${n.handle} (${n.bundles.join(",")}) at https://${n.domain}: passed ${i}; failed:
|
|
797
803
|
${s}`}}return{success:!0,message:`Verified ${n.handle} (${n.bundles.join(",")}) at https://${n.domain}: ${i}`}}}),aK=nt({name:"reconcile-cohort",usage:"<repo> <cohort>",description:"Reconcile all users in a cohort",run:async({args:e},t)=>{let r=e[0],o=e[1];if(!r||!o)return mt(aK);return await KB(r,o,t.runner,{...t.env?{env:t.env}:{}}),{success:!0,message:`Reconciled cohort ${o}`}}});function LJ(e,t){return[e,...t.length===0?["- (none)"]:t.map((r)=>`- ${r}`)]}var cK=nt({name:"reconcile-all",usage:"<repo> [--dry-run]",description:"Reconcile every cohort",flags:{"dry-run":Ub},run:async({args:e,flags:t},r)=>{let o=e[0];if(!o)return mt(cK);if(fs(t,"dry-run")){let n=await FB(o),i=n.firstPassChangedFiles.length,s=n.secondPassChangedFiles.length;return{success:s===0,message:[`Dry-run reconcile found ${i} first-pass changed file(s); second pass ${s===0?"converged with zero drift":`still changed ${s} file(s)`}`,...LJ("First-pass changed files:",n.firstPassChangedFiles),...LJ("Second-pass changed files:",n.secondPassChangedFiles)].join(`
|
|
798
|
-
`)}}return await yg(o,r.runner,{...r.env?{env:r.env}:{}}),{success:!0,message:"Reconciled all cohorts"}}}),
|
|
804
|
+
`)}}return await yg(o,r.runner,{...r.env?{env:r.env}:{}}),{success:!0,message:"Reconciled all cohorts"}}}),Bye=nt({name:"help",description:"Show this help message",run:()=>({success:!0,message:gO({cliName:ZJ,intro:"brains-ops \u2014 operator CLI for private brain fleet repos",commands:Mb,globalFlags:dO})})}),Uye=nt({name:"version",description:"Show version",run:()=>({success:!0,message:`brains-ops ${pf.version}`})}),dO={help:{type:"boolean",short:"h",description:"Show help"},version:{type:"boolean",short:"v",description:"Show version"}},Mb=[jJ,BJ,UJ,MJ,qJ,FJ,JJ,KJ,HJ,VJ,WJ,GJ,QJ,YJ,XJ,eK,tK,rK,oK,iK,sK,aK,cK,Bye,Uye],Mye=yO(Mb);async function lK(e,t={}){let r=Mye.get(e.command);if(!r)return{success:!1,message:`Unknown command: ${e.command}`};return r.run({args:e.args,flags:e.flags},t)}function uK(e){return pO(e,{commands:Mb,globalFlags:dO})}var uf;try{uf=await lK(uK(process.argv.slice(2)))}catch(e){if(e instanceof df)console.error(e.message),process.exit(1);throw e}if(uf.message)(uf.success?console.info:console.error)(uf.message);process.exit(uf.success?0:1);
|