@rizom/ops 0.2.0-alpha.562 → 0.2.0-alpha.563
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 +62 -62
- package/dist/index.js +7 -7
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -123,17 +123,17 @@ volumes:
|
|
|
123
123
|
`}return f.replace(/\n$/,"")}return vS=i,vS}function kr(){if(ZR)return _S;ZR=1;let e=yu(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],r=["scalar","sequence","mapping"];function i(o){let s={};if(o!==null)Object.keys(o).forEach(function(a){o[a].forEach(function(c){s[String(c)]=a})});return s}function n(o,s){if(s=s||{},Object.keys(s).forEach(function(a){if(t.indexOf(a)===-1)throw new e('Unknown option "'+a+'" is met in definition of "'+o+'" YAML type.')}),this.options=s,this.tag=o,this.kind=s.kind||null,this.resolve=s.resolve||function(){return!0},this.construct=s.construct||function(a){return a},this.instanceOf=s.instanceOf||null,this.predicate=s.predicate||null,this.represent=s.represent||null,this.representName=s.representName||null,this.defaultStyle=s.defaultStyle||null,this.multi=s.multi||!1,this.styleAliases=i(s.styleAliases||null),r.indexOf(this.kind)===-1)throw new e('Unknown kind "'+this.kind+'" is specified for "'+o+'" YAML type.')}return _S=n,_S}function uO(){if(MR)return kS;MR=1;let e=yu(),t=kr();function r(o,s){let a=[];return o[s].forEach(function(c){let l=a.length;a.forEach(function(u,f){if(u.tag===c.tag&&u.kind===c.kind&&u.multi===c.multi)l=f}),a[l]=c}),a}function i(){let o={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(a){if(a.multi)o.multi[a.kind].push(a),o.multi.fallback.push(a);else o[a.kind][a.tag]=o.fallback[a.tag]=a}for(let a=0,c=arguments.length;a<c;a+=1)arguments[a].forEach(s);return o}function n(o){return this.extend(o)}return n.prototype.extend=function(s){let a=[],c=[];if(s instanceof t)c.push(s);else if(Array.isArray(s))c=c.concat(s);else if(s&&(Array.isArray(s.implicit)||Array.isArray(s.explicit))){if(s.implicit)a=a.concat(s.implicit);if(s.explicit)c=c.concat(s.explicit)}else throw new e("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");a.forEach(function(u){if(!(u instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(u.loadKind&&u.loadKind!=="scalar")throw new e("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(u.multi)throw new e("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),c.forEach(function(u){if(!(u instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.")});let l=Object.create(n.prototype);return l.implicit=(this.implicit||[]).concat(a),l.explicit=(this.explicit||[]).concat(c),l.compiledImplicit=r(l,"implicit"),l.compiledExplicit=r(l,"explicit"),l.compiledTypeMap=i(l.compiledImplicit,l.compiledExplicit),l},kS=n,kS}function dO(){if(FR)return ES;return FR=1,ES=new(kr())("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),ES}function fO(){if(HR)return IS;return HR=1,IS=new(kr())("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),IS}function pO(){if(KR)return TS;return KR=1,TS=new(kr())("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),TS}function mO(){if(JR)return AS;return JR=1,AS=new(uO())({explicit:[dO(),fO(),pO()]}),AS}function hO(){if(VR)return $S;VR=1;let e=kr();function t(n){if(n===null)return!0;let o=n.length;return o===1&&n==="~"||o===4&&(n==="null"||n==="Null"||n==="NULL")}function r(){return null}function i(n){return n===null}return $S=new e("tag:yaml.org,2002:null",{kind:"scalar",resolve:t,construct:r,predicate:i,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"}),$S}function gO(){if(WR)return CS;WR=1;let e=kr();function t(n){if(n===null)return!1;let o=n.length;return o===4&&(n==="true"||n==="True"||n==="TRUE")||o===5&&(n==="false"||n==="False"||n==="FALSE")}function r(n){return n==="true"||n==="True"||n==="TRUE"}function i(n){return Object.prototype.toString.call(n)==="[object Boolean]"}return CS=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:t,construct:r,predicate:i,represent:{lowercase:function(n){return n?"true":"false"},uppercase:function(n){return n?"TRUE":"FALSE"},camelcase:function(n){return n?"True":"False"}},defaultStyle:"lowercase"}),CS}function yO(){if(GR)return RS;GR=1;let e=gu(),t=kr();function r(l){return l>=48&&l<=57||l>=65&&l<=70||l>=97&&l<=102}function i(l){return l>=48&&l<=55}function n(l){return l>=48&&l<=57}function o(l){if(l===null)return!1;let u=l.length,f=0,p=!1;if(!u)return!1;let m=l[f];if(m==="-"||m==="+")m=l[++f];if(m==="0"){if(f+1===u)return!0;if(m=l[++f],m==="b"){f++;for(;f<u;f++){if(m=l[f],m!=="0"&&m!=="1")return!1;p=!0}return p&&isFinite(s(l))}if(m==="x"){f++;for(;f<u;f++){if(!r(l.charCodeAt(f)))return!1;p=!0}return p&&isFinite(s(l))}if(m==="o"){f++;for(;f<u;f++){if(!i(l.charCodeAt(f)))return!1;p=!0}return p&&isFinite(s(l))}}for(;f<u;f++){if(!n(l.charCodeAt(f)))return!1;p=!0}if(!p)return!1;return isFinite(s(l))}function s(l){let u=l,f=1,p=u[0];if(p==="-"||p==="+"){if(p==="-")f=-1;u=u.slice(1),p=u[0]}if(u==="0")return 0;if(p==="0"){if(u[1]==="b")return f*parseInt(u.slice(2),2);if(u[1]==="x")return f*parseInt(u.slice(2),16);if(u[1]==="o")return f*parseInt(u.slice(2),8)}return f*parseInt(u,10)}function a(l){return s(l)}function c(l){return Object.prototype.toString.call(l)==="[object Number]"&&(l%1===0&&!e.isNegativeZero(l))}return RS=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:o,construct:a,predicate:c,represent:{binary:function(l){return l>=0?"0b"+l.toString(2):"-0b"+l.toString(2).slice(1)},octal:function(l){return l>=0?"0o"+l.toString(8):"-0o"+l.toString(8).slice(1)},decimal:function(l){return l.toString(10)},hexadecimal:function(l){return l>=0?"0x"+l.toString(16).toUpperCase():"-0x"+l.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),RS}function bO(){if(QR)return OS;QR=1;let e=gu(),t=kr(),r=new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),i=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function n(l){if(l===null)return!1;if(!r.test(l))return!1;if(isFinite(parseFloat(l,10)))return!0;return i.test(l)}function o(l){let u=l.toLowerCase(),f=u[0]==="-"?-1:1;if("+-".indexOf(u[0])>=0)u=u.slice(1);if(u===".inf")return f===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;else if(u===".nan")return NaN;return f*parseFloat(u,10)}let s=/^[-+]?[0-9]+e/;function a(l,u){if(isNaN(l))switch(u){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===l)switch(u){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===l)switch(u){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(l))return"-0.0";let f=l.toString(10);return s.test(f)?f.replace("e",".e"):f}function c(l){return Object.prototype.toString.call(l)==="[object Number]"&&(l%1!==0||e.isNegativeZero(l))}return OS=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:n,construct:o,predicate:c,represent:a,defaultStyle:"lowercase"}),OS}function SO(){if(YR)return PS;return YR=1,PS=mO().extend({implicit:[hO(),gO(),yO(),bO()]}),PS}function xO(){if(XR)return zS;return XR=1,zS=SO(),zS}function wO(){if(eO)return NS;eO=1;let e=kr(),t=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),r=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function i(s){if(s===null)return!1;if(t.exec(s)!==null)return!0;if(r.exec(s)!==null)return!0;return!1}function n(s){let a=0,c=null,l=t.exec(s);if(l===null)l=r.exec(s);if(l===null)throw Error("Date resolve error");let u=+l[1],f=+l[2]-1,p=+l[3];if(!l[4])return new Date(Date.UTC(u,f,p));let m=+l[4],y=+l[5],g=+l[6];if(l[7]){a=l[7].slice(0,3);while(a.length<3)a+="0";a=+a}if(l[9]){let _=+l[10],T=+(l[11]||0);if(c=(_*60+T)*60000,l[9]==="-")c=-c}let b=new Date(Date.UTC(u,f,p,m,y,g,a));if(c)b.setTime(b.getTime()-c);return b}function o(s){return s.toISOString()}return NS=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:i,construct:n,instanceOf:Date,represent:o}),NS}function vO(){if(tO)return DS;tO=1;let e=kr();function t(r){return r==="<<"||r===null}return DS=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),DS}function _O(){if(rO)return LS;rO=1;let e=kr(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
124
124
|
\r`;function r(s){if(s===null)return!1;let a=0,c=s.length,l=t;for(let u=0;u<c;u++){let f=l.indexOf(s.charAt(u));if(f>64)continue;if(f<0)return!1;a+=6}return a%8===0}function i(s){let a=s.replace(/[\r\n=]/g,""),c=a.length,l=t,u=0,f=[];for(let m=0;m<c;m++){if(m%4===0&&m)f.push(u>>16&255),f.push(u>>8&255),f.push(u&255);u=u<<6|l.indexOf(a.charAt(m))}let p=c%4*6;if(p===0)f.push(u>>16&255),f.push(u>>8&255),f.push(u&255);else if(p===18)f.push(u>>10&255),f.push(u>>2&255);else if(p===12)f.push(u>>4&255);return new Uint8Array(f)}function n(s){let a="",c=0,l=s.length,u=t;for(let p=0;p<l;p++){if(p%3===0&&p)a+=u[c>>18&63],a+=u[c>>12&63],a+=u[c>>6&63],a+=u[c&63];c=(c<<8)+s[p]}let f=l%3;if(f===0)a+=u[c>>18&63],a+=u[c>>12&63],a+=u[c>>6&63],a+=u[c&63];else if(f===2)a+=u[c>>10&63],a+=u[c>>4&63],a+=u[c<<2&63],a+=u[64];else if(f===1)a+=u[c>>2&63],a+=u[c<<4&63],a+=u[64],a+=u[64];return a}function o(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return LS=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:r,construct:i,predicate:o,represent:n}),LS}function kO(){if(nO)return BS;nO=1;let e=kr(),t=Object.prototype.hasOwnProperty,r=Object.prototype.toString;function i(o){if(o===null)return!0;let s={},a=o;for(let c=0,l=a.length;c<l;c+=1){let u=a[c],f=!1;if(r.call(u)!=="[object Object]")return!1;let p;for(p in u)if(t.call(u,p))if(!f)f=!0;else return!1;if(!f)return!1;if(t.call(s,p))return!1;Object.defineProperty(s,p,{value:!0})}return!0}function n(o){return o!==null?o:[]}return BS=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:i,construct:n}),BS}function EO(){if(iO)return jS;iO=1;let e=kr(),t=Object.prototype.toString;function r(n){if(n===null)return!0;let o=n,s=Array(o.length);for(let a=0,c=o.length;a<c;a+=1){let l=o[a];if(t.call(l)!=="[object Object]")return!1;let u=Object.keys(l);if(u.length!==1)return!1;s[a]=[u[0],l[u[0]]]}return!0}function i(n){if(n===null)return[];let o=n,s=Array(o.length);for(let a=0,c=o.length;a<c;a+=1){let l=o[a],u=Object.keys(l);s[a]=[u[0],l[u[0]]]}return s}return jS=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:r,construct:i}),jS}function IO(){if(oO)return US;oO=1;let e=kr(),t=Object.prototype.hasOwnProperty;function r(n){if(n===null)return!0;let o=n;for(let s in o)if(t.call(o,s)){if(o[s]!==null)return!1}return!0}function i(n){return n!==null?n:{}}return US=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:r,construct:i}),US}function MS(){if(sO)return qS;return sO=1,qS=xO().extend({implicit:[wO(),vO()],explicit:[_O(),kO(),EO(),IO()]}),qS}function F9(){if(aO)return Pp;aO=1;let e=gu(),t=yu(),r=M9(),i=MS(),n=Object.prototype.hasOwnProperty,o=1,s=2,a=3,c=4,l=1,u=2,f=3,p=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,m=/[\x85\u2028\u2029]/,y=/[,\[\]{}]/,g=/^(?:!|!!|![0-9A-Za-z-]+!)$/,b=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function _(h){return Object.prototype.toString.call(h)}function T(h){return h===10||h===13}function A(h){return h===9||h===32}function z(h){return h===9||h===32||h===10||h===13}function j(h){return h===44||h===91||h===93||h===123||h===125}function E(h){if(h>=48&&h<=57)return h-48;let q=h|32;if(q>=97&&q<=102)return q-97+10;return-1}function F(h){if(h===120)return 2;if(h===117)return 4;if(h===85)return 8;return 0}function D(h){if(h>=48&&h<=57)return h-48;return-1}function H(h){switch(h){case 48:return"\x00";case 97:return"\x07";case 98:return"\b";case 116:return"\t";case 9:return"\t";case 110:return`
|
|
125
125
|
`;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"\x85";case 95:return"\xA0";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function X(h){if(h<=65535)return String.fromCharCode(h);return String.fromCharCode((h-65536>>10)+55296,(h-65536&1023)+56320)}function Z(h,q,re){if(q==="__proto__")Object.defineProperty(h,q,{configurable:!0,enumerable:!0,writable:!0,value:re});else h[q]=re}let P=Array(256),N=Array(256);for(let h=0;h<256;h++)P[h]=H(h)?1:0,N[h]=H(h);function I(h,q){this.input=h,this.filename=q.filename||null,this.schema=q.schema||i,this.onWarning=q.onWarning||null,this.legacy=q.legacy||!1,this.json=q.json||!1,this.listener=q.listener||null,this.maxDepth=typeof q.maxDepth==="number"?q.maxDepth:100,this.maxTotalMergeKeys=typeof q.maxTotalMergeKeys==="number"?q.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=h.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function O(h,q){let re={name:h.filename,buffer:h.input.slice(0,-1),position:h.position,line:h.line,column:h.position-h.lineStart};return re.snippet=r(re),new t(q,re)}function R(h,q){throw O(h,q)}function M(h,q){if(h.onWarning)h.onWarning.call(null,O(h,q))}function L(h,q,re){let oe=h.anchorMapTransactions;if(oe.length!==0){let Y=oe[oe.length-1];if(!n.call(Y,q))Y[q]={existed:n.call(h.anchorMap,q),value:h.anchorMap[q]}}h.anchorMap[q]=re}function V(h){h.anchorMapTransactions.push(Object.create(null))}function k(h){let q=h.anchorMapTransactions.pop(),re=h.anchorMapTransactions;if(re.length===0)return;let oe=re[re.length-1],Y=Object.keys(q);for(let v=0,W=Y.length;v<W;v+=1){let G=Y[v];if(!n.call(oe,G))oe[G]=q[G]}}function te(h){let q=h.anchorMapTransactions.pop(),re=Object.keys(q);for(let oe=re.length-1;oe>=0;oe-=1){let Y=q[re[oe]];if(Y.existed)h.anchorMap[re[oe]]=Y.value;else delete h.anchorMap[re[oe]]}}function ue(h){return{position:h.position,line:h.line,lineStart:h.lineStart,lineIndent:h.lineIndent,firstTabInLine:h.firstTabInLine,tag:h.tag,anchor:h.anchor,kind:h.kind,result:h.result}}function C(h,q){h.position=q.position,h.line=q.line,h.lineStart=q.lineStart,h.lineIndent=q.lineIndent,h.firstTabInLine=q.firstTabInLine,h.tag=q.tag,h.anchor=q.anchor,h.kind=q.kind,h.result=q.result}let be={YAML:function(q,re,oe){if(q.version!==null)R(q,"duplication of %YAML directive");if(oe.length!==1)R(q,"YAML directive accepts exactly one argument");let Y=/^([0-9]+)\.([0-9]+)$/.exec(oe[0]);if(Y===null)R(q,"ill-formed argument of the YAML directive");let v=parseInt(Y[1],10),W=parseInt(Y[2],10);if(v!==1)R(q,"unacceptable YAML version of the document");if(q.version=oe[0],q.checkLineBreaks=W<2,W!==1&&W!==2)M(q,"unsupported YAML version of the document")},TAG:function(q,re,oe){let Y;if(oe.length!==2)R(q,"TAG directive accepts exactly two arguments");let v=oe[0];if(Y=oe[1],!g.test(v))R(q,"ill-formed tag handle (first argument) of the TAG directive");if(n.call(q.tagMap,v))R(q,'there is a previously declared suffix for "'+v+'" tag handle');if(!b.test(Y))R(q,"ill-formed tag prefix (second argument) of the TAG directive");try{Y=decodeURIComponent(Y)}catch(W){R(q,"tag prefix is malformed: "+Y)}q.tagMap[v]=Y}};function Ee(h,q,re,oe){if(q<re){let Y=h.input.slice(q,re);if(oe)for(let v=0,W=Y.length;v<W;v+=1){let G=Y.charCodeAt(v);if(!(G===9||G>=32&&G<=1114111))R(h,"expected valid JSON character")}else if(p.test(Y))R(h,"the stream contains non-printable characters");h.result+=Y}}function Ce(h){if(h.totalMergeKeys++,h.maxTotalMergeKeys!==-1&&h.totalMergeKeys>h.maxTotalMergeKeys)R(h,"merge keys exceeded maxTotalMergeKeys ("+h.maxTotalMergeKeys+")")}function Re(h,q,re,oe){if(!e.isObject(re))R(h,"cannot merge mappings; the provided source object is unacceptable");Ce(h);let Y=Object.keys(re);for(let v=0,W=Y.length;v<W;v+=1){let G=Y[v];if(Ce(h),!n.call(q,G))Z(q,G,re[G]),oe[G]=!0}}function _e(h,q,re,oe,Y,v,W,G,ce){if(Array.isArray(Y)){Y=Array.prototype.slice.call(Y);for(let le=0,ge=Y.length;le<ge;le+=1){if(Array.isArray(Y[le]))R(h,"nested arrays are not supported inside keys");if(typeof Y==="object"&&_(Y[le])==="[object Object]")Y[le]="[object Object]"}}if(typeof Y==="object"&&_(Y)==="[object Object]")Y="[object Object]";if(Y=String(Y),q===null)q={};if(oe==="tag:yaml.org,2002:merge")if(Array.isArray(v)){if(v.length>100)R(h,"abnormal merge sequence size");for(let le=0,ge=v.length;le<ge;le+=1)Re(h,q,v[le],re)}else Re(h,q,v,re);else{if(!h.json&&!n.call(re,Y)&&n.call(q,Y))h.line=W||h.line,h.lineStart=G||h.lineStart,h.position=ce||h.position,R(h,"duplicated mapping key");Z(q,Y,v),delete re[Y]}return q}function Je(h){let q=h.input.charCodeAt(h.position);if(q===10)h.position++;else if(q===13){if(h.position++,h.input.charCodeAt(h.position)===10)h.position++}else R(h,"a line break is expected");h.line+=1,h.lineStart=h.position,h.firstTabInLine=-1}function Ne(h,q,re){let oe=0,Y=h.input.charCodeAt(h.position);while(Y!==0){while(A(Y)){if(Y===9&&h.firstTabInLine===-1)h.firstTabInLine=h.position;Y=h.input.charCodeAt(++h.position)}if(q&&Y===35)do Y=h.input.charCodeAt(++h.position);while(Y!==10&&Y!==13&&Y!==0);if(T(Y)){Je(h),Y=h.input.charCodeAt(h.position),oe++,h.lineIndent=0;while(Y===32)h.lineIndent++,Y=h.input.charCodeAt(++h.position)}else break}if(re!==-1&&oe!==0&&h.lineIndent<re)M(h,"deficient indentation");return oe}function Ye(h){let q=h.position,re=h.input.charCodeAt(q);if((re===45||re===46)&&re===h.input.charCodeAt(q+1)&&re===h.input.charCodeAt(q+2)){if(q+=3,re=h.input.charCodeAt(q),re===0||z(re))return!0}return!1}function mt(h,q){if(q===1)h.result+=" ";else if(q>1)h.result+=e.repeat(`
|
|
126
|
-
`,q-1)}function zt(h,q,re){let oe,Y,v,W,G,ce,le=h.kind,ge=h.result,se=h.input.charCodeAt(h.position);if(z(se)||j(se)||se===35||se===38||se===42||se===33||se===124||se===62||se===39||se===34||se===37||se===64||se===96)return!1;if(se===63||se===45){let xe=h.input.charCodeAt(h.position+1);if(z(xe)||re&&j(xe))return!1}h.kind="scalar",h.result="",oe=Y=h.position,v=!1;while(se!==0){if(se===58){let xe=h.input.charCodeAt(h.position+1);if(z(xe)||re&&j(xe))break}else if(se===35){let xe=h.input.charCodeAt(h.position-1);if(z(xe))break}else if(h.position===h.lineStart&&Ye(h)||re&&j(se))break;else if(T(se))if(W=h.line,G=h.lineStart,ce=h.lineIndent,Ne(h,!1,-1),h.lineIndent>=q){v=!0,se=h.input.charCodeAt(h.position);continue}else{h.position=Y,h.line=W,h.lineStart=G,h.lineIndent=ce;break}if(v)Ee(h,oe,Y,!1),mt(h,h.line-W),oe=Y=h.position,v=!1;if(!A(se))Y=h.position+1;se=h.input.charCodeAt(++h.position)}if(Ee(h,oe,Y,!1),h.result)return!0;return h.kind=le,h.result=ge,!1}function fr(h,q){let re,oe,Y=h.input.charCodeAt(h.position);if(Y!==39)return!1;h.kind="scalar",h.result="",h.position++,re=oe=h.position;while((Y=h.input.charCodeAt(h.position))!==0)if(Y===39)if(Ee(h,re,h.position,!0),Y=h.input.charCodeAt(++h.position),Y===39)re=h.position,h.position++,oe=h.position;else return!0;else if(T(Y))Ee(h,re,oe,!0),mt(h,Ne(h,!1,q)),re=oe=h.position;else if(h.position===h.lineStart&&Ye(h))R(h,"unexpected end of the document within a single quoted scalar");else if(h.position++,!A(Y))oe=h.position;R(h,"unexpected end of the stream within a single quoted scalar")}function Kr(h,q){let re,oe,Y,v=h.input.charCodeAt(h.position);if(v!==34)return!1;h.kind="scalar",h.result="",h.position++,re=oe=h.position;while((v=h.input.charCodeAt(h.position))!==0)if(v===34)return Ee(h,re,h.position,!0),h.position++,!0;else if(v===92){if(Ee(h,re,h.position,!0),v=h.input.charCodeAt(++h.position),T(v))Ne(h,!1,q);else if(v<256&&P[v])h.result+=N[v],h.position++;else if((Y=F(v))>0){let W=Y,G=0;for(;W>0;W--)if(v=h.input.charCodeAt(++h.position),(Y=E(v))>=0)G=(G<<4)+Y;else R(h,"expected hexadecimal character");h.result+=X(G),h.position++}else R(h,"unknown escape sequence");re=oe=h.position}else if(T(v))Ee(h,re,oe,!0),mt(h,Ne(h,!1,q)),re=oe=h.position;else if(h.position===h.lineStart&&Ye(h))R(h,"unexpected end of the document within a double quoted scalar");else if(h.position++,!A(v))oe=h.position;R(h,"unexpected end of the stream within a double quoted scalar")}function Jr(h,q){let re=!0,oe,Y,v,W=h.tag,G,ce=h.anchor,le,ge,se,xe,$e=Object.create(null),De,Le,
|
|
126
|
+
`,q-1)}function zt(h,q,re){let oe,Y,v,W,G,ce,le=h.kind,ge=h.result,se=h.input.charCodeAt(h.position);if(z(se)||j(se)||se===35||se===38||se===42||se===33||se===124||se===62||se===39||se===34||se===37||se===64||se===96)return!1;if(se===63||se===45){let xe=h.input.charCodeAt(h.position+1);if(z(xe)||re&&j(xe))return!1}h.kind="scalar",h.result="",oe=Y=h.position,v=!1;while(se!==0){if(se===58){let xe=h.input.charCodeAt(h.position+1);if(z(xe)||re&&j(xe))break}else if(se===35){let xe=h.input.charCodeAt(h.position-1);if(z(xe))break}else if(h.position===h.lineStart&&Ye(h)||re&&j(se))break;else if(T(se))if(W=h.line,G=h.lineStart,ce=h.lineIndent,Ne(h,!1,-1),h.lineIndent>=q){v=!0,se=h.input.charCodeAt(h.position);continue}else{h.position=Y,h.line=W,h.lineStart=G,h.lineIndent=ce;break}if(v)Ee(h,oe,Y,!1),mt(h,h.line-W),oe=Y=h.position,v=!1;if(!A(se))Y=h.position+1;se=h.input.charCodeAt(++h.position)}if(Ee(h,oe,Y,!1),h.result)return!0;return h.kind=le,h.result=ge,!1}function fr(h,q){let re,oe,Y=h.input.charCodeAt(h.position);if(Y!==39)return!1;h.kind="scalar",h.result="",h.position++,re=oe=h.position;while((Y=h.input.charCodeAt(h.position))!==0)if(Y===39)if(Ee(h,re,h.position,!0),Y=h.input.charCodeAt(++h.position),Y===39)re=h.position,h.position++,oe=h.position;else return!0;else if(T(Y))Ee(h,re,oe,!0),mt(h,Ne(h,!1,q)),re=oe=h.position;else if(h.position===h.lineStart&&Ye(h))R(h,"unexpected end of the document within a single quoted scalar");else if(h.position++,!A(Y))oe=h.position;R(h,"unexpected end of the stream within a single quoted scalar")}function Kr(h,q){let re,oe,Y,v=h.input.charCodeAt(h.position);if(v!==34)return!1;h.kind="scalar",h.result="",h.position++,re=oe=h.position;while((v=h.input.charCodeAt(h.position))!==0)if(v===34)return Ee(h,re,h.position,!0),h.position++,!0;else if(v===92){if(Ee(h,re,h.position,!0),v=h.input.charCodeAt(++h.position),T(v))Ne(h,!1,q);else if(v<256&&P[v])h.result+=N[v],h.position++;else if((Y=F(v))>0){let W=Y,G=0;for(;W>0;W--)if(v=h.input.charCodeAt(++h.position),(Y=E(v))>=0)G=(G<<4)+Y;else R(h,"expected hexadecimal character");h.result+=X(G),h.position++}else R(h,"unknown escape sequence");re=oe=h.position}else if(T(v))Ee(h,re,oe,!0),mt(h,Ne(h,!1,q)),re=oe=h.position;else if(h.position===h.lineStart&&Ye(h))R(h,"unexpected end of the document within a double quoted scalar");else if(h.position++,!A(v))oe=h.position;R(h,"unexpected end of the stream within a double quoted scalar")}function Jr(h,q){let re=!0,oe,Y,v,W=h.tag,G,ce=h.anchor,le,ge,se,xe,$e=Object.create(null),De,Le,Me,Ve=h.input.charCodeAt(h.position);if(Ve===91)le=93,xe=!1,G=[];else if(Ve===123)le=125,xe=!0,G={};else return!1;if(h.anchor!==null)L(h,h.anchor,G);Ve=h.input.charCodeAt(++h.position);while(Ve!==0){if(Ne(h,!0,q),Ve=h.input.charCodeAt(h.position),Ve===le)return h.position++,h.tag=W,h.anchor=ce,h.kind=xe?"mapping":"sequence",h.result=G,!0;else if(!re)R(h,"missed comma between flow collection entries");else if(Ve===44)R(h,"expected the node content, but found ','");if(Le=De=Me=null,ge=se=!1,Ve===63){let co=h.input.charCodeAt(h.position+1);if(z(co))ge=se=!0,h.position++,Ne(h,!0,q)}if(oe=h.line,Y=h.lineStart,v=h.position,Jn(h,q,o,!1,!0),Le=h.tag,De=h.result,Ne(h,!0,q),Ve=h.input.charCodeAt(h.position),(se||h.line===oe)&&Ve===58)ge=!0,Ve=h.input.charCodeAt(++h.position),Ne(h,!0,q),Jn(h,q,o,!1,!0),Me=h.result;if(xe)_e(h,G,$e,Le,De,Me,oe,Y,v);else if(ge)G.push(_e(h,null,$e,Le,De,Me,oe,Y,v));else G.push(De);if(Ne(h,!0,q),Ve=h.input.charCodeAt(h.position),Ve===44)re=!0,Ve=h.input.charCodeAt(++h.position);else re=!1}R(h,"unexpected end of the stream within a flow collection")}function In(h,q){let re,oe=l,Y=!1,v=!1,W=q,G=0,ce=!1,le,ge=h.input.charCodeAt(h.position);if(ge===124)re=!1;else if(ge===62)re=!0;else return!1;h.kind="scalar",h.result="";while(ge!==0)if(ge=h.input.charCodeAt(++h.position),ge===43||ge===45)if(l===oe)oe=ge===43?f:u;else R(h,"repeat of a chomping mode identifier");else if((le=D(ge))>=0)if(le===0)R(h,"bad explicit indentation width of a block scalar; it cannot be less than one");else if(!v)W=q+le-1,v=!0;else R(h,"repeat of an indentation width identifier");else break;if(A(ge)){do ge=h.input.charCodeAt(++h.position);while(A(ge));if(ge===35)do ge=h.input.charCodeAt(++h.position);while(!T(ge)&&ge!==0)}while(ge!==0){Je(h),h.lineIndent=0,ge=h.input.charCodeAt(h.position);while((!v||h.lineIndent<W)&&ge===32)h.lineIndent++,ge=h.input.charCodeAt(++h.position);if(!v&&h.lineIndent>W)W=h.lineIndent;if(T(ge)){G++;continue}if(!v&&W===0)R(h,"missing indentation for block scalar");if(h.lineIndent<W){if(oe===f)h.result+=e.repeat(`
|
|
127
127
|
`,Y?1+G:G);else if(oe===l){if(Y)h.result+=`
|
|
128
128
|
`}break}if(re)if(A(ge))ce=!0,h.result+=e.repeat(`
|
|
129
129
|
`,Y?1+G:G);else if(ce)ce=!1,h.result+=e.repeat(`
|
|
130
130
|
`,G+1);else if(G===0){if(Y)h.result+=" "}else h.result+=e.repeat(`
|
|
131
131
|
`,G);else h.result+=e.repeat(`
|
|
132
|
-
`,Y?1+G:G);Y=!0,v=!0,G=0;let se=h.position;while(!T(ge)&&ge!==0)ge=h.input.charCodeAt(++h.position);Ee(h,se,h.position,!1)}return!0}function Ua(h,q){let{tag:re,anchor:oe}=h,Y=[],v=!1;if(h.firstTabInLine!==-1)return!1;if(h.anchor!==null)L(h,h.anchor,Y);let W=h.input.charCodeAt(h.position);while(W!==0){if(h.firstTabInLine!==-1)h.position=h.firstTabInLine,R(h,"tab characters must not be used in indentation");if(W!==45)break;let G=h.input.charCodeAt(h.position+1);if(!z(G))break;if(v=!0,h.position++,Ne(h,!0,-1)){if(h.lineIndent<=q){Y.push(null),W=h.input.charCodeAt(h.position);continue}}let ce=h.line;if(Jn(h,q,a,!1,!0),Y.push(h.result),Ne(h,!0,-1),W=h.input.charCodeAt(h.position),(h.line===ce||h.lineIndent>q)&&W!==0)R(h,"bad indentation of a sequence entry");else if(h.lineIndent<q)break}if(v)return h.tag=re,h.anchor=oe,h.kind="sequence",h.result=Y,!0;return!1}function ws(h,q,re){let oe,Y,v,W,G=h.tag,ce=h.anchor,le={},ge=Object.create(null),se=null,xe=null,$e=null,De=!1,Le=!1;if(h.firstTabInLine!==-1)return!1;if(h.anchor!==null)L(h,h.anchor,le);let
|
|
132
|
+
`,Y?1+G:G);Y=!0,v=!0,G=0;let se=h.position;while(!T(ge)&&ge!==0)ge=h.input.charCodeAt(++h.position);Ee(h,se,h.position,!1)}return!0}function Ua(h,q){let{tag:re,anchor:oe}=h,Y=[],v=!1;if(h.firstTabInLine!==-1)return!1;if(h.anchor!==null)L(h,h.anchor,Y);let W=h.input.charCodeAt(h.position);while(W!==0){if(h.firstTabInLine!==-1)h.position=h.firstTabInLine,R(h,"tab characters must not be used in indentation");if(W!==45)break;let G=h.input.charCodeAt(h.position+1);if(!z(G))break;if(v=!0,h.position++,Ne(h,!0,-1)){if(h.lineIndent<=q){Y.push(null),W=h.input.charCodeAt(h.position);continue}}let ce=h.line;if(Jn(h,q,a,!1,!0),Y.push(h.result),Ne(h,!0,-1),W=h.input.charCodeAt(h.position),(h.line===ce||h.lineIndent>q)&&W!==0)R(h,"bad indentation of a sequence entry");else if(h.lineIndent<q)break}if(v)return h.tag=re,h.anchor=oe,h.kind="sequence",h.result=Y,!0;return!1}function ws(h,q,re){let oe,Y,v,W,G=h.tag,ce=h.anchor,le={},ge=Object.create(null),se=null,xe=null,$e=null,De=!1,Le=!1;if(h.firstTabInLine!==-1)return!1;if(h.anchor!==null)L(h,h.anchor,le);let Me=h.input.charCodeAt(h.position);while(Me!==0){if(!De&&h.firstTabInLine!==-1)h.position=h.firstTabInLine,R(h,"tab characters must not be used in indentation");let Ve=h.input.charCodeAt(h.position+1),co=h.line;if((Me===63||Me===58)&&z(Ve)){if(Me===63){if(De)_e(h,le,ge,se,xe,null,Y,v,W),se=xe=$e=null;Le=!0,De=!0,oe=!0}else if(De)De=!1,oe=!0;else R(h,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");h.position+=1,Me=Ve}else{if(Y=h.line,v=h.lineStart,W=h.position,!Jn(h,re,s,!1,!0))break;if(h.line===co){Me=h.input.charCodeAt(h.position);while(A(Me))Me=h.input.charCodeAt(++h.position);if(Me===58){if(Me=h.input.charCodeAt(++h.position),!z(Me))R(h,"a whitespace character is expected after the key-value separator within a block mapping");if(De)_e(h,le,ge,se,xe,null,Y,v,W),se=xe=$e=null;Le=!0,De=!1,oe=!1,se=h.tag,xe=h.result}else if(Le)R(h,"can not read an implicit mapping pair; a colon is missed");else return h.tag=G,h.anchor=ce,!0}else if(Le)R(h,"can not read a block mapping entry; a multiline key may not be an implicit key");else return h.tag=G,h.anchor=ce,!0}if(h.line===co||h.lineIndent>q){if(De)Y=h.line,v=h.lineStart,W=h.position;if(Jn(h,q,c,!0,oe))if(De)xe=h.result;else $e=h.result;if(!De)_e(h,le,ge,se,xe,$e,Y,v,W),se=xe=$e=null;Ne(h,!0,-1),Me=h.input.charCodeAt(h.position)}if((h.line===co||h.lineIndent>q)&&Me!==0)R(h,"bad indentation of a mapping entry");else if(h.lineIndent<q)break}if(De)_e(h,le,ge,se,xe,null,Y,v,W);if(Le)h.tag=G,h.anchor=ce,h.kind="mapping",h.result=le;return Le}function vs(h){let q=!1,re=!1,oe,Y,v=h.input.charCodeAt(h.position);if(v!==33)return!1;if(h.tag!==null)R(h,"duplication of a tag property");if(v=h.input.charCodeAt(++h.position),v===60)q=!0,v=h.input.charCodeAt(++h.position);else if(v===33)re=!0,oe="!!",v=h.input.charCodeAt(++h.position);else oe="!";let W=h.position;if(q){do v=h.input.charCodeAt(++h.position);while(v!==0&&v!==62);if(h.position<h.length)Y=h.input.slice(W,h.position),v=h.input.charCodeAt(++h.position);else R(h,"unexpected end of the stream within a verbatim tag")}else{while(v!==0&&!z(v)){if(v===33)if(!re){if(oe=h.input.slice(W-1,h.position+1),!g.test(oe))R(h,"named tag handle cannot contain such characters");re=!0,W=h.position+1}else R(h,"tag suffix cannot contain exclamation marks");v=h.input.charCodeAt(++h.position)}if(Y=h.input.slice(W,h.position),y.test(Y))R(h,"tag suffix cannot contain flow indicator characters")}if(Y&&!b.test(Y))R(h,"tag name cannot contain such characters: "+Y);try{Y=decodeURIComponent(Y)}catch(G){R(h,"tag name is malformed: "+Y)}if(q)h.tag=Y;else if(n.call(h.tagMap,oe))h.tag=h.tagMap[oe]+Y;else if(oe==="!")h.tag="!"+Y;else if(oe==="!!")h.tag="tag:yaml.org,2002:"+Y;else R(h,'undeclared tag handle "'+oe+'"');return!0}function qa(h){let q=h.input.charCodeAt(h.position);if(q!==38)return!1;if(h.anchor!==null)R(h,"duplication of an anchor property");q=h.input.charCodeAt(++h.position);let re=h.position;while(q!==0&&!z(q)&&!j(q))q=h.input.charCodeAt(++h.position);if(h.position===re)R(h,"name of an anchor node must contain at least one character");return h.anchor=h.input.slice(re,h.position),!0}function du(h){let q=h.input.charCodeAt(h.position);if(q!==42)return!1;q=h.input.charCodeAt(++h.position);let re=h.position;while(q!==0&&!z(q)&&!j(q))q=h.input.charCodeAt(++h.position);if(h.position===re)R(h,"name of an alias node must contain at least one character");let oe=h.input.slice(re,h.position);if(!n.call(h.anchorMap,oe))R(h,'unidentified alias "'+oe+'"');return h.result=h.anchorMap[oe],Ne(h,!0,-1),!0}function Za(h,q,re,oe){let Y=ue(h);if(V(h),C(h,q),h.tag=null,h.anchor=null,h.kind=null,h.result=null,ws(h,re,oe)&&h.kind==="mapping")return k(h),!0;return te(h),C(h,Y),!1}function Jn(h,q,re,oe,Y){let v,W,G=1,ce=!1,le=!1,ge=null,se,xe,$e;if(h.depth>=h.maxDepth)R(h,"nesting exceeded maxDepth ("+h.maxDepth+")");if(h.depth+=1,h.listener!==null)h.listener("open",h);h.tag=null,h.anchor=null,h.kind=null,h.result=null;let De=v=W=c===re||a===re;if(oe){if(Ne(h,!0,-1)){if(ce=!0,h.lineIndent>q)G=1;else if(h.lineIndent===q)G=0;else if(h.lineIndent<q)G=-1}}if(G===1)while(!0){let Le=h.input.charCodeAt(h.position),Me=ue(h);if(ce&&(Le===33&&h.tag!==null||Le===38&&h.anchor!==null))break;if(!vs(h)&&!qa(h))break;if(ge===null)ge=Me;if(Ne(h,!0,-1)){if(ce=!0,W=De,h.lineIndent>q)G=1;else if(h.lineIndent===q)G=0;else if(h.lineIndent<q)G=-1}else W=!1}if(W)W=ce||Y;if(G===1||c===re){if(o===re||s===re)xe=q;else xe=q+1;if($e=h.position-h.lineStart,G===1)if(W&&(Ua(h,$e)||ws(h,$e,xe))||Jr(h,xe))le=!0;else{let Le=h.input.charCodeAt(h.position);if(ge!==null&&De&&!W&&Le!==124&&Le!==62&&Za(h,ge,ge.position-ge.lineStart,xe))le=!0;else if(v&&In(h,xe)||fr(h,xe)||Kr(h,xe))le=!0;else if(du(h)){if(le=!0,h.tag!==null||h.anchor!==null)R(h,"alias node should not have any properties")}else if(zt(h,xe,o===re)){if(le=!0,h.tag===null)h.tag="?"}if(h.anchor!==null)L(h,h.anchor,h.result)}else if(G===0)le=W&&Ua(h,$e)}if(h.tag===null){if(h.anchor!==null)L(h,h.anchor,h.result)}else if(h.tag==="?"){if(h.result!==null&&h.kind!=="scalar")R(h,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+h.kind+'"');for(let Le=0,Me=h.implicitTypes.length;Le<Me;Le+=1)if(se=h.implicitTypes[Le],se.resolve(h.result)){if(h.result=se.construct(h.result),h.tag=se.tag,h.anchor!==null)L(h,h.anchor,h.result);break}}else if(h.tag!=="!"){if(n.call(h.typeMap[h.kind||"fallback"],h.tag))se=h.typeMap[h.kind||"fallback"][h.tag];else{se=null;let Le=h.typeMap.multi[h.kind||"fallback"];for(let Me=0,Ve=Le.length;Me<Ve;Me+=1)if(h.tag.slice(0,Le[Me].tag.length)===Le[Me].tag){se=Le[Me];break}}if(!se)R(h,"unknown tag !<"+h.tag+">");if(h.result!==null&&se.kind!==h.kind)R(h,"unacceptable node kind for !<"+h.tag+'> tag; it should be "'+se.kind+'", not "'+h.kind+'"');if(!se.resolve(h.result,h.tag))R(h,"cannot resolve a node with !<"+h.tag+"> explicit tag");else if(h.result=se.construct(h.result,h.tag),h.anchor!==null)L(h,h.anchor,h.result)}if(h.listener!==null)h.listener("close",h);return h.depth-=1,h.tag!==null||h.anchor!==null||le}function fu(h){let q=h.position,re=!1,oe;h.version=null,h.checkLineBreaks=h.legacy,h.tagMap=Object.create(null),h.anchorMap=Object.create(null);while((oe=h.input.charCodeAt(h.position))!==0){if(Ne(h,!0,-1),oe=h.input.charCodeAt(h.position),h.lineIndent>0||oe!==37)break;re=!0,oe=h.input.charCodeAt(++h.position);let Y=h.position;while(oe!==0&&!z(oe))oe=h.input.charCodeAt(++h.position);let v=h.input.slice(Y,h.position),W=[];if(v.length<1)R(h,"directive name must not be less than one character in length");while(oe!==0){while(A(oe))oe=h.input.charCodeAt(++h.position);if(oe===35){do oe=h.input.charCodeAt(++h.position);while(oe!==0&&!T(oe));break}if(T(oe))break;Y=h.position;while(oe!==0&&!z(oe))oe=h.input.charCodeAt(++h.position);W.push(h.input.slice(Y,h.position))}if(oe!==0)Je(h);if(n.call(be,v))be[v](h,v,W);else M(h,'unknown document directive "'+v+'"')}if(Ne(h,!0,-1),h.lineIndent===0&&h.input.charCodeAt(h.position)===45&&h.input.charCodeAt(h.position+1)===45&&h.input.charCodeAt(h.position+2)===45)h.position+=3,Ne(h,!0,-1);else if(re)R(h,"directives end mark is expected");if(Jn(h,h.lineIndent-1,c,!1,!0),Ne(h,!0,-1),h.checkLineBreaks&&m.test(h.input.slice(q,h.position)))M(h,"non-ASCII line breaks are interpreted as content");if(h.documents.push(h.result),h.position===h.lineStart&&Ye(h)){if(h.input.charCodeAt(h.position)===46)h.position+=3,Ne(h,!0,-1);return}if(h.position<h.length-1)R(h,"end of the stream or a document separator is expected")}function ee(h,q){if(h=String(h),q=q||{},h.length!==0){if(h.charCodeAt(h.length-1)!==10&&h.charCodeAt(h.length-1)!==13)h+=`
|
|
133
133
|
`;if(h.charCodeAt(0)===65279)h=h.slice(1)}let re=new I(h,q),oe=h.indexOf("\x00");if(oe!==-1)re.position=oe,R(re,"null byte is not allowed in input");re.input+="\x00";while(re.input.charCodeAt(re.position)===32)re.lineIndent+=1,re.position+=1;while(re.position<re.length-1)fu(re);return re.documents}function ie(h,q,re){if(q!==null&&typeof q==="object"&&typeof re>"u")re=q,q=null;let oe=ee(h,re);if(typeof q!=="function")return oe;for(let Y=0,v=oe.length;Y<v;Y+=1)q(oe[Y])}function Ie(h,q){let re=ee(h,q);if(re.length===0)return;else if(re.length===1)return re[0];throw new t("expected a single document in the stream, but found more")}return Pp.loadAll=ie,Pp.load=Ie,Pp}function H9(){if(cO)return ZS;cO=1;let e=gu(),t=yu(),r=MS(),i=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=65279,s=9,a=10,c=13,l=32,u=33,f=34,p=35,m=37,y=38,g=39,b=42,_=44,T=45,A=58,z=61,j=62,E=63,F=64,D=91,H=93,X=96,Z=123,P=124,N=125,I={};I[0]="\\0",I[7]="\\a",I[8]="\\b",I[9]="\\t",I[10]="\\n",I[11]="\\v",I[12]="\\f",I[13]="\\r",I[27]="\\e",I[34]="\\\"",I[92]="\\\\",I[133]="\\N",I[160]="\\_",I[8232]="\\L",I[8233]="\\P";let O=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],R=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function M(v,W){if(W===null)return{};let G={},ce=Object.keys(W);for(let le=0,ge=ce.length;le<ge;le+=1){let se=ce[le],xe=String(W[se]);if(se.slice(0,2)==="!!")se="tag:yaml.org,2002:"+se.slice(2);let $e=v.compiledTypeMap.fallback[se];if($e&&n.call($e.styleAliases,xe))xe=$e.styleAliases[xe];G[se]=xe}return G}function L(v){let W,G,ce=v.toString(16).toUpperCase();if(v<=255)W="x",G=2;else if(v<=65535)W="u",G=4;else if(v<=4294967295)W="U",G=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+W+e.repeat("0",G-ce.length)+ce}let V=1,k=2;function te(v){this.schema=v.schema||r,this.indent=Math.max(1,v.indent||2),this.noArrayIndent=v.noArrayIndent||!1,this.skipInvalid=v.skipInvalid||!1,this.flowLevel=e.isNothing(v.flowLevel)?-1:v.flowLevel,this.styleMap=M(this.schema,v.styles||null),this.sortKeys=v.sortKeys||!1,this.lineWidth=v.lineWidth||80,this.noRefs=v.noRefs||!1,this.noCompatMode=v.noCompatMode||!1,this.condenseFlow=v.condenseFlow||!1,this.quotingType=v.quotingType==='"'?k:V,this.forceQuotes=v.forceQuotes||!1,this.replacer=typeof v.replacer==="function"?v.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function ue(v,W){let G=e.repeat(" ",W),ce=0,le="",ge=v.length;while(ce<ge){let se,xe=v.indexOf(`
|
|
134
134
|
`,ce);if(xe===-1)se=v.slice(ce),ce=ge;else se=v.slice(ce,xe+1),ce=xe+1;if(se.length&&se!==`
|
|
135
135
|
`)le+=G;le+=se}return le}function C(v,W){return`
|
|
136
|
-
`+e.repeat(" ",v.indent*W)}function be(v,W){for(let G=0,ce=v.implicitTypes.length;G<ce;G+=1)if(v.implicitTypes[G].resolve(W))return!0;return!1}function Ee(v){return v===l||v===s}function Ce(v){return v>=32&&v<=126||v>=161&&v<=55295&&v!==8232&&v!==8233||v>=57344&&v<=65533&&v!==o||v>=65536&&v<=1114111}function Re(v){return Ce(v)&&v!==o&&v!==c&&v!==a}function _e(v,W,G){let ce=Re(v),le=ce&&!Ee(v);return(G?ce:ce&&v!==_&&v!==D&&v!==H&&v!==Z&&v!==N)&&v!==p&&!(W===A&&!le)||Re(W)&&!Ee(W)&&v===p||W===A&&le}function Je(v){return Ce(v)&&v!==o&&!Ee(v)&&v!==T&&v!==E&&v!==A&&v!==_&&v!==D&&v!==H&&v!==Z&&v!==N&&v!==p&&v!==y&&v!==b&&v!==u&&v!==P&&v!==z&&v!==j&&v!==g&&v!==f&&v!==m&&v!==F&&v!==X}function Ne(v){return!Ee(v)&&v!==A}function Ye(v,W){let G=v.charCodeAt(W),ce;if(G>=55296&&G<=56319&&W+1<v.length){if(ce=v.charCodeAt(W+1),ce>=56320&&ce<=57343)return(G-55296)*1024+ce-56320+65536}return G}function mt(v){return/^\n* /.test(v)}let zt=1,fr=2,Kr=3,Jr=4,In=5;function Ua(v,W,G,ce,le,ge,se,xe){let $e,De=0,Le=null,
|
|
136
|
+
`+e.repeat(" ",v.indent*W)}function be(v,W){for(let G=0,ce=v.implicitTypes.length;G<ce;G+=1)if(v.implicitTypes[G].resolve(W))return!0;return!1}function Ee(v){return v===l||v===s}function Ce(v){return v>=32&&v<=126||v>=161&&v<=55295&&v!==8232&&v!==8233||v>=57344&&v<=65533&&v!==o||v>=65536&&v<=1114111}function Re(v){return Ce(v)&&v!==o&&v!==c&&v!==a}function _e(v,W,G){let ce=Re(v),le=ce&&!Ee(v);return(G?ce:ce&&v!==_&&v!==D&&v!==H&&v!==Z&&v!==N)&&v!==p&&!(W===A&&!le)||Re(W)&&!Ee(W)&&v===p||W===A&&le}function Je(v){return Ce(v)&&v!==o&&!Ee(v)&&v!==T&&v!==E&&v!==A&&v!==_&&v!==D&&v!==H&&v!==Z&&v!==N&&v!==p&&v!==y&&v!==b&&v!==u&&v!==P&&v!==z&&v!==j&&v!==g&&v!==f&&v!==m&&v!==F&&v!==X}function Ne(v){return!Ee(v)&&v!==A}function Ye(v,W){let G=v.charCodeAt(W),ce;if(G>=55296&&G<=56319&&W+1<v.length){if(ce=v.charCodeAt(W+1),ce>=56320&&ce<=57343)return(G-55296)*1024+ce-56320+65536}return G}function mt(v){return/^\n* /.test(v)}let zt=1,fr=2,Kr=3,Jr=4,In=5;function Ua(v,W,G,ce,le,ge,se,xe){let $e,De=0,Le=null,Me=!1,Ve=!1,co=ce!==-1,pu=-1,mu=Je(Ye(v,0))&&Ne(Ye(v,v.length-1));if(W||se)for($e=0;$e<v.length;De>=65536?$e+=2:$e++){if(De=Ye(v,$e),!Ce(De))return In;mu=mu&&_e(De,Le,xe),Le=De}else{for($e=0;$e<v.length;De>=65536?$e+=2:$e++){if(De=Ye(v,$e),De===a){if(Me=!0,co)Ve=Ve||$e-pu-1>ce&&v[pu+1]!==" ",pu=$e}else if(!Ce(De))return In;mu=mu&&_e(De,Le,xe),Le=De}Ve=Ve||co&&($e-pu-1>ce&&v[pu+1]!==" ")}if(!Me&&!Ve){if(mu&&!se&&!le(v))return zt;return ge===k?In:fr}if(G>9&&mt(v))return In;if(!se)return Ve?Jr:Kr;return ge===k?In:fr}function ws(v,W,G,ce,le){v.dump=function(){if(W.length===0)return v.quotingType===k?'""':"''";if(!v.noCompatMode){if(O.indexOf(W)!==-1||R.test(W))return v.quotingType===k?'"'+W+'"':"'"+W+"'"}let ge=v.indent*Math.max(1,G),se=v.lineWidth===-1?-1:Math.max(Math.min(v.lineWidth,40),v.lineWidth-ge),xe=ce||v.flowLevel>-1&&G>=v.flowLevel;function $e(De){return be(v,De)}switch(Ua(W,xe,v.indent,se,$e,v.quotingType,v.forceQuotes&&!ce,le)){case zt:return W;case fr:return"'"+W.replace(/'/g,"''")+"'";case Kr:return"|"+vs(W,v.indent)+qa(ue(W,ge));case Jr:return">"+vs(W,v.indent)+qa(ue(du(W,se),ge));case In:return'"'+Jn(W)+'"';default:throw new t("impossible error: invalid scalar style")}}()}function vs(v,W){let G=mt(v)?String(W):"",ce=v[v.length-1]===`
|
|
137
137
|
`,ge=ce&&(v[v.length-2]===`
|
|
138
138
|
`||v===`
|
|
139
139
|
`)?"+":ce?"":"-";return G+ge+`
|
|
@@ -144,7 +144,7 @@ volumes:
|
|
|
144
144
|
`:"")+Za($e,W),le=ge}return ce}function Za(v,W){if(v===""||v[0]===" ")return v;let G=/ [^ ]/g,ce,le=0,ge,se=0,xe=0,$e="";while(ce=G.exec(v)){if(xe=ce.index,xe-le>W)ge=se>le?se:xe,$e+=`
|
|
145
145
|
`+v.slice(le,ge),le=ge+1;se=xe}if($e+=`
|
|
146
146
|
`,v.length-le>W&&se>le)$e+=v.slice(le,se)+`
|
|
147
|
-
`+v.slice(se+1);else $e+=v.slice(le);return $e.slice(1)}function Jn(v){let W="",G=0;for(let ce=0;ce<v.length;G>=65536?ce+=2:ce++){G=Ye(v,ce);let le=I[G];if(!le&&Ce(G)){if(W+=v[ce],G>=65536)W+=v[ce+1]}else W+=le||L(G)}return W}function fu(v,W,G){let ce="",le=v.tag;for(let ge=0,se=G.length;ge<se;ge+=1){let xe=G[ge];if(v.replacer)xe=v.replacer.call(G,String(ge),xe);if(q(v,W,xe,!1,!1)||typeof xe>"u"&&q(v,W,null,!1,!1)){if(ce!=="")ce+=","+(!v.condenseFlow?" ":"");ce+=v.dump}}v.tag=le,v.dump="["+ce+"]"}function ee(v,W,G,ce){let le="",ge=v.tag;for(let se=0,xe=G.length;se<xe;se+=1){let $e=G[se];if(v.replacer)$e=v.replacer.call(G,String(se),$e);if(q(v,W+1,$e,!0,!0,!1,!0)||typeof $e>"u"&&q(v,W+1,null,!0,!0,!1,!0)){if(!ce||le!=="")le+=C(v,W);if(v.dump&&a===v.dump.charCodeAt(0))le+="-";else le+="- ";le+=v.dump}}v.tag=ge,v.dump=le||"[]"}function ie(v,W,G){let ce="",le=v.tag,ge=Object.keys(G);for(let se=0,xe=ge.length;se<xe;se+=1){let $e="";if(ce!=="")$e+=", ";if(v.condenseFlow)$e+='"';let De=ge[se],Le=G[De];if(v.replacer)Le=v.replacer.call(G,De,Le);if(!q(v,W,De,!1,!1))continue;if(v.dump.length>1024)$e+="? ";if($e+=v.dump+(v.condenseFlow?'"':"")+":"+(v.condenseFlow?"":" "),!q(v,W,Le,!1,!1))continue;$e+=v.dump,ce+=$e}v.tag=le,v.dump="{"+ce+"}"}function Ie(v,W,G,ce){let le="",ge=v.tag,se=Object.keys(G);if(v.sortKeys===!0)se.sort();else if(typeof v.sortKeys==="function")se.sort(v.sortKeys);else if(v.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let xe=0,$e=se.length;xe<$e;xe+=1){let De="";if(!ce||le!=="")De+=C(v,W);let Le=se[xe],
|
|
147
|
+
`+v.slice(se+1);else $e+=v.slice(le);return $e.slice(1)}function Jn(v){let W="",G=0;for(let ce=0;ce<v.length;G>=65536?ce+=2:ce++){G=Ye(v,ce);let le=I[G];if(!le&&Ce(G)){if(W+=v[ce],G>=65536)W+=v[ce+1]}else W+=le||L(G)}return W}function fu(v,W,G){let ce="",le=v.tag;for(let ge=0,se=G.length;ge<se;ge+=1){let xe=G[ge];if(v.replacer)xe=v.replacer.call(G,String(ge),xe);if(q(v,W,xe,!1,!1)||typeof xe>"u"&&q(v,W,null,!1,!1)){if(ce!=="")ce+=","+(!v.condenseFlow?" ":"");ce+=v.dump}}v.tag=le,v.dump="["+ce+"]"}function ee(v,W,G,ce){let le="",ge=v.tag;for(let se=0,xe=G.length;se<xe;se+=1){let $e=G[se];if(v.replacer)$e=v.replacer.call(G,String(se),$e);if(q(v,W+1,$e,!0,!0,!1,!0)||typeof $e>"u"&&q(v,W+1,null,!0,!0,!1,!0)){if(!ce||le!=="")le+=C(v,W);if(v.dump&&a===v.dump.charCodeAt(0))le+="-";else le+="- ";le+=v.dump}}v.tag=ge,v.dump=le||"[]"}function ie(v,W,G){let ce="",le=v.tag,ge=Object.keys(G);for(let se=0,xe=ge.length;se<xe;se+=1){let $e="";if(ce!=="")$e+=", ";if(v.condenseFlow)$e+='"';let De=ge[se],Le=G[De];if(v.replacer)Le=v.replacer.call(G,De,Le);if(!q(v,W,De,!1,!1))continue;if(v.dump.length>1024)$e+="? ";if($e+=v.dump+(v.condenseFlow?'"':"")+":"+(v.condenseFlow?"":" "),!q(v,W,Le,!1,!1))continue;$e+=v.dump,ce+=$e}v.tag=le,v.dump="{"+ce+"}"}function Ie(v,W,G,ce){let le="",ge=v.tag,se=Object.keys(G);if(v.sortKeys===!0)se.sort();else if(typeof v.sortKeys==="function")se.sort(v.sortKeys);else if(v.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let xe=0,$e=se.length;xe<$e;xe+=1){let De="";if(!ce||le!=="")De+=C(v,W);let Le=se[xe],Me=G[Le];if(v.replacer)Me=v.replacer.call(G,Le,Me);if(!q(v,W+1,Le,!0,!0,!0))continue;let Ve=v.tag!==null&&v.tag!=="?"||v.dump&&v.dump.length>1024;if(Ve)if(v.dump&&a===v.dump.charCodeAt(0))De+="?";else De+="? ";if(De+=v.dump,Ve)De+=C(v,W);if(!q(v,W+1,Me,!0,Ve))continue;if(v.dump&&a===v.dump.charCodeAt(0))De+=":";else De+=": ";De+=v.dump,le+=De}v.tag=ge,v.dump=le||"{}"}function h(v,W,G){let ce=G?v.explicitTypes:v.implicitTypes;for(let le=0,ge=ce.length;le<ge;le+=1){let se=ce[le];if((se.instanceOf||se.predicate)&&(!se.instanceOf||typeof W==="object"&&W instanceof se.instanceOf)&&(!se.predicate||se.predicate(W))){if(G)if(se.multi&&se.representName)v.tag=se.representName(W);else v.tag=se.tag;else v.tag="?";if(se.represent){let xe=v.styleMap[se.tag]||se.defaultStyle,$e;if(i.call(se.represent)==="[object Function]")$e=se.represent(W,xe);else if(n.call(se.represent,xe))$e=se.represent[xe](W,xe);else throw new t("!<"+se.tag+'> tag resolver accepts not "'+xe+'" style');v.dump=$e}return!0}}return!1}function q(v,W,G,ce,le,ge,se){if(v.tag=null,v.dump=G,!h(v,G,!1))h(v,G,!0);let xe=i.call(v.dump),$e=ce;if(ce)ce=v.flowLevel<0||v.flowLevel>W;let De=xe==="[object Object]"||xe==="[object Array]",Le,Me;if(De)Le=v.duplicates.indexOf(G),Me=Le!==-1;if(v.tag!==null&&v.tag!=="?"||Me||v.indent!==2&&W>0)le=!1;if(Me&&v.usedDuplicates[Le])v.dump="*ref_"+Le;else{if(De&&Me&&!v.usedDuplicates[Le])v.usedDuplicates[Le]=!0;if(xe==="[object Object]"){if(ce&&Object.keys(v.dump).length!==0){if(Ie(v,W,v.dump,le),Me)v.dump="&ref_"+Le+v.dump}else if(ie(v,W,v.dump),Me)v.dump="&ref_"+Le+" "+v.dump}else if(xe==="[object Array]"){if(ce&&v.dump.length!==0){if(v.noArrayIndent&&!se&&W>0)ee(v,W-1,v.dump,le);else ee(v,W,v.dump,le);if(Me)v.dump="&ref_"+Le+v.dump}else if(fu(v,W,v.dump),Me)v.dump="&ref_"+Le+" "+v.dump}else if(xe==="[object String]"){if(v.tag!=="?")ws(v,v.dump,W,ge,$e)}else if(xe==="[object Undefined]")return!1;else{if(v.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+xe)}if(v.tag!==null&&v.tag!=="?"){let Ve=encodeURI(v.tag[0]==="!"?v.tag.slice(1):v.tag).replace(/!/g,"%21");if(v.tag[0]==="!")Ve="!"+Ve;else if(Ve.slice(0,18)==="tag:yaml.org,2002:")Ve="!!"+Ve.slice(18);else Ve="!<"+Ve+">";v.dump=Ve+" "+v.dump}}return!0}function re(v,W){let G=[],ce=[];oe(v,G,ce);let le=ce.length;for(let ge=0;ge<le;ge+=1)W.duplicates.push(G[ce[ge]]);W.usedDuplicates=Array(le)}function oe(v,W,G){if(v!==null&&typeof v==="object"){let ce=W.indexOf(v);if(ce!==-1){if(G.indexOf(ce)===-1)G.push(ce)}else if(W.push(v),Array.isArray(v))for(let le=0,ge=v.length;le<ge;le+=1)oe(v[le],W,G);else{let le=Object.keys(v);for(let ge=0,se=le.length;ge<se;ge+=1)oe(v[le[ge]],W,G)}}}function Y(v,W){W=W||{};let G=new te(W);if(!G.noRefs)re(v,G);let ce=v;if(G.replacer)ce=G.replacer.call({"":ce},"",ce);if(q(G,0,ce,!0,!0))return G.dump+`
|
|
148
148
|
`;return""}return ZS.dump=Y,ZS}function K9(){if(lO)return mr;lO=1;let e=F9(),t=H9();function r(i,n){return function(){throw Error("Function yaml."+i+" is removed in js-yaml 4. Use yaml."+n+" instead, which is now safe by default.")}}return mr.Type=kr(),mr.Schema=uO(),mr.FAILSAFE_SCHEMA=mO(),mr.JSON_SCHEMA=SO(),mr.CORE_SCHEMA=xO(),mr.DEFAULT_SCHEMA=MS(),mr.load=e.load,mr.loadAll=e.loadAll,mr.dump=t.dump,mr.YAMLException=yu(),mr.types={binary:_O(),float:bO(),map:pO(),null:hO(),pairs:EO(),set:IO(),timestamp:wO(),bool:gO(),int:yO(),merge:vO(),omap:kO(),seq:fO(),str:dO()},mr.safeLoad=r("safeLoad","load"),mr.safeLoadAll=r("safeLoadAll","loadAll"),mr.safeDump=r("safeDump","dump"),mr}var mr,Pp,uo,jR,wS,UR,vS,qR,_S,ZR,kS,MR,ES,FR,IS,HR,TS,KR,AS,JR,$S,VR,CS,WR,RS,GR,OS,QR,PS,YR,zS,XR,NS,eO,DS,tO,LS,rO,BS,nO,jS,iO,US,oO,qS,sO,aO,ZS,cO,lO,J9,TO,Fa,V9,W9,G9,Q9,FS,Ha,Y9,bu,X9,eV,tV,rV,nV;var Ka=S(()=>{mr={},Pp={},uo={};ZS={};J9=K9(),TO=Z9(J9),{Type:Fa,Schema:V9,FAILSAFE_SCHEMA:W9,JSON_SCHEMA:G9,CORE_SCHEMA:Q9,DEFAULT_SCHEMA:FS,load:Ha,loadAll:Y9,dump:bu,YAMLException:X9,types:eV,safeLoad:tV,safeLoadAll:rV,safeDump:nV}=TO});function at(e,t){if(e instanceof Error)return e.message;return t??String(e)}function Ja(e){return bu(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function AO(e){return Ha(e)}function An(e,t){if(!e.trim())return{ok:!1,error:"file is empty"};let r;try{r=Ha(e)}catch(n){return{ok:!1,error:at(n,"YAML parse error")}}if(!iV(r))return{ok:!1,error:"expected a YAML mapping (key: value pairs)"};if(!t)return{ok:!0,data:r};let i=t.safeParse(r);if(!i.success)return{ok:!1,error:`invalid field(s): ${i.error.issues.map((o)=>o.path.map(String).join(".")).join(", ")}`};return{ok:!0,data:i.data}}function iV(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var ki=S(()=>{Ka()});function K(e,t,r){function i(a,c){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let f=0;f<u.length;f++){let p=u[f];if(!(p in a))a[p]=l[p].bind(a)}}let n=r?.Parent??Object;class o extends n{}Object.defineProperty(o,"name",{value:e});function s(a){var c;let l=r?.Parent?new o:this;i(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}function kt(e){if(e)Object.assign(Es,e);return Es}var $O,HS,KS,Vn,Is,Es;var Ts=S(()=>{HS=Object.freeze({status:"aborted"});KS=Symbol("zod_brand");Vn=class Vn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};Is=class Is extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}};($O=globalThis).__zod_globalConfig??($O.__zod_globalConfig={});Es=globalThis.__zod_globalConfig});var me={};Ht(me,{BIGINT_FORMAT_RANGES:()=>tx,Class:()=>PO,NUMBER_FORMAT_RANGES:()=>ex,aborted:()=>ho,allowsEval:()=>GS,assert:()=>lV,assertEqual:()=>oV,assertIs:()=>aV,assertNever:()=>cV,assertNotEqual:()=>sV,assignProp:()=>po,base64ToUint8Array:()=>RO,base64urlToUint8Array:()=>IV,cached:()=>Wa,captureStackTrace:()=>Np,cleanEnum:()=>EV,cleanRegex:()=>wu,clone:()=>Er,cloneDef:()=>dV,createTransparentProxy:()=>yV,defineLazy:()=>We,esc:()=>zp,escapeRegex:()=>cn,explicitlyAborted:()=>rx,extend:()=>xV,finalizeIssue:()=>Ir,floatSafeRemainder:()=>VS,getElementAtPath:()=>fV,getEnumValues:()=>xu,getLengthableOrigin:()=>ku,getParsedType:()=>gV,getSizableOrigin:()=>_u,hexToUint8Array:()=>AV,isObject:()=>As,isPlainObject:()=>mo,issue:()=>Ga,joinValues:()=>Q,jsonStringifyReplacer:()=>Va,merge:()=>vV,mergeDefs:()=>Ei,normalizeParams:()=>ye,nullish:()=>fo,numKeys:()=>hV,objectClone:()=>uV,omit:()=>SV,optionalKeys:()=>XS,parsedType:()=>pe,partial:()=>_V,pick:()=>bV,prefixIssues:()=>Br,primitiveTypes:()=>YS,promiseAllObject:()=>pV,propertyKeyTypes:()=>vu,randomString:()=>mV,required:()=>kV,safeExtend:()=>wV,shallowClone:()=>QS,slugify:()=>WS,stringifyPrimitive:()=>fe,uint8ArrayToBase64:()=>OO,uint8ArrayToBase64url:()=>TV,uint8ArrayToHex:()=>$V,unwrapMessage:()=>Su});function oV(e){return e}function sV(e){return e}function aV(e){}function cV(e){throw Error("Unexpected value in exhaustive check")}function lV(e){}function xu(e){let t=Object.values(e).filter((i)=>typeof i==="number");return Object.entries(e).filter(([i,n])=>t.indexOf(+i)===-1).map(([i,n])=>n)}function Q(e,t="|"){return e.map((r)=>fe(r)).join(t)}function Va(e,t){if(typeof t==="bigint")return t.toString();return t}function Wa(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function fo(e){return e===null||e===void 0}function wu(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function VS(e,t){let r=e/t,i=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-i)<n)return 0;return r-i}function We(e,t,r){let i=void 0;Object.defineProperty(e,t,{get(){if(i===CO)return;if(i===void 0)i=CO,i=r();return i},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function uV(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function po(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ei(...e){let t={};for(let r of e){let i=Object.getOwnPropertyDescriptors(r);Object.assign(t,i)}return Object.defineProperties({},t)}function dV(e){return Ei(e._zod.def)}function fV(e,t){if(!t)return e;return t.reduce((r,i)=>r?.[i],e)}function pV(e){let t=Object.keys(e),r=t.map((i)=>e[i]);return Promise.all(r).then((i)=>{let n={};for(let o=0;o<t.length;o++)n[t[o]]=i[o];return n})}function mV(e=10){let r="";for(let i=0;i<e;i++)r+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return r}function zp(e){return JSON.stringify(e)}function WS(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function As(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function mo(e){if(As(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(As(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function QS(e){if(mo(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}function hV(e){let t=0;for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r))t++;return t}function cn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Er(e,t,r){let i=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)i._zod.parent=e;return i}function ye(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function yV(e){let t;return new Proxy({},{get(r,i,n){return t??(t=e()),Reflect.get(t,i,n)},set(r,i,n,o){return t??(t=e()),Reflect.set(t,i,n,o)},has(r,i){return t??(t=e()),Reflect.has(t,i)},deleteProperty(r,i){return t??(t=e()),Reflect.deleteProperty(t,i)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,i){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,i)},defineProperty(r,i,n){return t??(t=e()),Reflect.defineProperty(t,i,n)}})}function fe(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function XS(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function bV(e,t){let r=e._zod.def,i=r.checks;if(i&&i.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let o=Ei(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;s[a]=r.shape[a]}return po(this,"shape",s),s},checks:[]});return Er(e,o)}function SV(e,t){let r=e._zod.def,i=r.checks;if(i&&i.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let o=Ei(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete s[a]}return po(this,"shape",s),s},checks:[]});return Er(e,o)}function xV(e,t){if(!mo(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let o=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=Ei(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return po(this,"shape",o),o}});return Er(e,n)}function wV(e,t){if(!mo(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=Ei(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return po(this,"shape",i),i}});return Er(e,r)}function vV(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Ei(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t._zod.def.shape};return po(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Er(e,r)}function _V(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=Ei(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw Error(`Unrecognized key: "${l}"`);if(!r[l])continue;c[l]=e?new e({type:"optional",innerType:a[l]}):a[l]}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return po(this,"shape",c),c},checks:[]});return Er(t,s)}function kV(e,t,r){let i=Ei(t._zod.def,{get shape(){let n=t._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw Error(`Unrecognized key: "${s}"`);if(!r[s])continue;o[s]=new e({type:"nonoptional",innerType:n[s]})}else for(let s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return po(this,"shape",o),o}});return Er(t,i)}function ho(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function rx(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Br(e,t){return t.map((r)=>{var i;return(i=r).path??(i.path=[]),r.path.unshift(e),r})}function Su(e){return typeof e==="string"?e:e?.message}function Ir(e,t,r){let i=e.message?e.message:Su(e.inst?._zod.def?.error?.(e))??Su(t?.error?.(e))??Su(r.customError?.(e))??Su(r.localeError?.(e))??"Invalid input",{inst:n,continue:o,input:s,...a}=e;if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=s;return a}function _u(e){if(e instanceof Set)return"set";if(e instanceof Map)return"map";if(e instanceof File)return"file";return"unknown"}function ku(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function pe(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Ga(...e){let[t,r,i]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:i};return{...t}}function EV(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map((t)=>t[1])}function RO(e){let t=atob(e),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}function OO(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function IV(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return RO(t+r)}function TV(e){return OO(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function AV(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)r[i/2]=Number.parseInt(t.slice(i,i+2),16);return r}function $V(e){return Array.from(e).map((t)=>t.toString(16).padStart(2,"0")).join("")}class PO{constructor(...e){}}var CO,Np,GS,gV=(e)=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(e===null)return"null";if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return"promise";if(typeof Map<"u"&&e instanceof Map)return"map";if(typeof Set<"u"&&e instanceof Set)return"set";if(typeof Date<"u"&&e instanceof Date)return"date";if(typeof File<"u"&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},vu,YS,ex,tx;var Oe=S(()=>{Ts();CO=Symbol("evaluating");Np="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};GS=Wa(()=>{if(Es.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});vu=new Set(["string","number","symbol"]),YS=new Set(["string","number","bigint","boolean","symbol","undefined"]);ex={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},tx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function Iu(e,t=(r)=>r.message){let r={},i=[];for(let n of e.issues)if(n.path.length>0)r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n));else i.push(t(n));return{formErrors:i,fieldErrors:r}}function Tu(e,t=(r)=>r.message){let r={_errors:[]},i=(n,o=[])=>{for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>i({issues:a},[...o,...s.path]));else if(s.code==="invalid_key")i({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")i({issues:s.issues},[...o,...s.path]);else{let a=[...o,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,l=0;while(l<a.length){let u=a[l];if(l!==a.length-1)c[u]=c[u]||{_errors:[]};else c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(s));c=c[u],l++}}}};return i(e),r}function nx(e,t=(r)=>r.message){let r={errors:[]},i=(n,o=[])=>{var s,a;for(let c of n.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map((l)=>i({issues:l},[...o,...c.path]));else if(c.code==="invalid_key")i({issues:c.issues},[...o,...c.path]);else if(c.code==="invalid_element")i({issues:c.issues},[...o,...c.path]);else{let l=[...o,...c.path];if(l.length===0){r.errors.push(t(c));continue}let u=r,f=0;while(f<l.length){let p=l[f],m=f===l.length-1;if(typeof p==="string")u.properties??(u.properties={}),(s=u.properties)[p]??(s[p]={errors:[]}),u=u.properties[p];else u.items??(u.items=[]),(a=u.items)[p]??(a[p]={errors:[]}),u=u.items[p];if(m)u.errors.push(t(c));f++}}};return i(e),r}function NO(e){let t=[],r=e.map((i)=>typeof i==="object"?i.key:i);for(let i of r)if(typeof i==="number")t.push(`[${i}]`);else if(typeof i==="symbol")t.push(`[${JSON.stringify(String(i))}]`);else if(/[^\w$]/.test(i))t.push(`[${JSON.stringify(i)}]`);else{if(t.length)t.push(".");t.push(i)}return t.join("")}function ix(e){let t=[],r=[...e.issues].sort((i,n)=>(i.path??[]).length-(n.path??[]).length);for(let i of r)if(t.push(`\u2716 ${i.message}`),i.path?.length)t.push(` \u2192 at ${NO(i.path)}`);return t.join(`
|
|
149
149
|
`)}var zO=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Va,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Eu,jr;var ox=S(()=>{Ts();Oe();Eu=K("$ZodError",zO),jr=K("$ZodError",zO,{Parent:Error})});var Qa=(e)=>(t,r,i,n)=>{let o=i?{...i,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Vn;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map((c)=>Ir(c,o,kt())));throw Np(a,n?.callee),a}return s.value},Dp,Ya=(e)=>async(t,r,i,n)=>{let o=i?{...i,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map((c)=>Ir(c,o,kt())));throw Np(a,n?.callee),a}return s.value},Lp,Xa=(e)=>(t,r,i)=>{let n=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},n);if(o instanceof Promise)throw new Vn;return o.issues.length?{success:!1,error:new(e??Eu)(o.issues.map((s)=>Ir(s,n,kt())))}:{success:!0,data:o.value}},sx,ec=(e)=>async(t,r,i)=>{let n=i?{...i,async:!0}:{async:!0},o=t._zod.run({value:r,issues:[]},n);if(o instanceof Promise)o=await o;return o.issues.length?{success:!1,error:new e(o.issues.map((s)=>Ir(s,n,kt())))}:{success:!0,data:o.value}},ax,Bp=(e)=>(t,r,i)=>{let n=i?{...i,direction:"backward"}:{direction:"backward"};return Qa(e)(t,r,n)},RV,jp=(e)=>(t,r,i)=>Qa(e)(t,r,i),OV,Up=(e)=>async(t,r,i)=>{let n=i?{...i,direction:"backward"}:{direction:"backward"};return Ya(e)(t,r,n)},PV,qp=(e)=>async(t,r,i)=>Ya(e)(t,r,i),zV,Zp=(e)=>(t,r,i)=>{let n=i?{...i,direction:"backward"}:{direction:"backward"};return Xa(e)(t,r,n)},NV,Mp=(e)=>(t,r,i)=>Xa(e)(t,r,i),DV,Fp=(e)=>async(t,r,i)=>{let n=i?{...i,direction:"backward"}:{direction:"backward"};return ec(e)(t,r,n)},LV,Hp=(e)=>async(t,r,i)=>ec(e)(t,r,i),BV;var cx=S(()=>{Ts();ox();Oe();Dp=Qa(jr),Lp=Ya(jr),sx=Xa(jr),ax=ec(jr),RV=Bp(jr),OV=jp(jr),PV=Up(jr),zV=qp(jr),NV=Zp(jr),DV=Mp(jr),LV=Fp(jr),BV=Hp(jr)});var Vr={};Ht(Vr,{base64:()=>kx,base64url:()=>Kp,bigint:()=>Rx,boolean:()=>Px,browserEmail:()=>KV,cidrv4:()=>vx,cidrv6:()=>_x,cuid:()=>lx,cuid2:()=>ux,date:()=>Tx,datetime:()=>$x,domain:()=>WV,duration:()=>hx,e164:()=>Ix,email:()=>yx,emoji:()=>bx,extendedDuration:()=>jV,guid:()=>gx,hex:()=>GV,hostname:()=>VV,html5Email:()=>MV,httpProtocol:()=>Ex,idnEmail:()=>HV,integer:()=>Ox,ipv4:()=>Sx,ipv6:()=>xx,ksuid:()=>px,lowercase:()=>Dx,mac:()=>wx,md5_base64:()=>YV,md5_base64url:()=>XV,md5_hex:()=>QV,nanoid:()=>mx,null:()=>zx,number:()=>Au,rfc5322Email:()=>FV,sha1_base64:()=>t7,sha1_base64url:()=>r7,sha1_hex:()=>e7,sha256_base64:()=>i7,sha256_base64url:()=>o7,sha256_hex:()=>n7,sha384_base64:()=>a7,sha384_base64url:()=>c7,sha384_hex:()=>s7,sha512_base64:()=>u7,sha512_base64url:()=>d7,sha512_hex:()=>l7,string:()=>Cx,time:()=>Ax,ulid:()=>dx,undefined:()=>Nx,unicodeEmail:()=>DO,uppercase:()=>Lx,uuid:()=>$s,uuid4:()=>UV,uuid6:()=>qV,uuid7:()=>ZV,xid:()=>fx});function bx(){return new RegExp(JV,"u")}function BO(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Ax(e){return new RegExp(`^${BO(e)}$`)}function $x(e){let t=BO({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let i=`${t}(?:${r.join("|")})`;return new RegExp(`^${LO}T(?:${i})$`)}function $u(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Cu(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var lx,ux,dx,fx,px,mx,hx,jV,gx,$s=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},UV,qV,ZV,yx,MV,FV,DO,HV,KV,JV="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Sx,xx,wx=(e)=>{let t=cn(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},vx,_x,kx,Kp,VV,WV,Ex,Ix,LO="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Tx,Cx=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Rx,Ox,Au,Px,zx,Nx,Dx,Lx,GV,QV,YV,XV,e7,t7,r7,n7,i7,o7,s7,a7,c7,l7,u7,d7;var Jp=S(()=>{Oe();lx=/^[cC][0-9a-z]{6,}$/,ux=/^[0-9a-z]+$/,dx=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fx=/^[0-9a-vA-V]{20}$/,px=/^[A-Za-z0-9]{27}$/,mx=/^[a-zA-Z0-9_-]{21}$/,hx=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jV=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,gx=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,UV=$s(4),qV=$s(6),ZV=$s(7),yx=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,MV=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,FV=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,DO=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,HV=DO,KV=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;Sx=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xx=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,vx=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,_x=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,kx=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Kp=/^[A-Za-z0-9_-]*$/,VV=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,WV=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Ex=/^https?$/,Ix=/^\+[1-9]\d{6,14}$/,Tx=new RegExp(`^${LO}$`);Rx=/^-?\d+n?$/,Ox=/^-?\d+$/,Au=/^-?\d+(?:\.\d+)?$/,Px=/^(?:true|false)$/i,zx=/^null$/i,Nx=/^undefined$/i,Dx=/^[^A-Z]*$/,Lx=/^[^a-z]*$/,GV=/^[0-9a-fA-F]*$/;QV=/^[0-9a-fA-F]{32}$/,YV=$u(22,"=="),XV=Cu(22),e7=/^[0-9a-fA-F]{40}$/,t7=$u(27,"="),r7=Cu(27),n7=/^[0-9a-fA-F]{64}$/,i7=$u(43,"="),o7=Cu(43),s7=/^[0-9a-fA-F]{96}$/,a7=$u(64,""),c7=Cu(64),l7=/^[0-9a-fA-F]{128}$/,u7=$u(86,"=="),d7=Cu(86)});function jO(e,t,r){if(e.issues.length)t.issues.push(...Br(r,e.issues))}var dt,UO,Vp,Wp,Bx,jx,Ux,qx,Zx,Mx,Fx,Hx,Kx,tc,Jx,Vx,Wx,Gx,Qx,Yx,Xx,ew,tw;var Gp=S(()=>{Ts();Jp();Oe();dt=K("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),UO={number:"number",bigint:"bigint",object:"date"},Vp=K("$ZodCheckLessThan",(e,t)=>{dt.init(e,t);let r=UO[typeof t.value];e._zod.onattach.push((i)=>{let n=i._zod.bag,o=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<o)if(t.inclusive)n.maximum=t.value;else n.exclusiveMaximum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value<=t.value:i.value<t.value)return;i.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Wp=K("$ZodCheckGreaterThan",(e,t)=>{dt.init(e,t);let r=UO[typeof t.value];e._zod.onattach.push((i)=>{let n=i._zod.bag,o=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>o)if(t.inclusive)n.minimum=t.value;else n.exclusiveMinimum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value>=t.value:i.value>t.value)return;i.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Bx=K("$ZodCheckMultipleOf",(e,t)=>{dt.init(e,t),e._zod.onattach.push((r)=>{var i;(i=r._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):VS(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),jx=K("$ZodCheckNumberFormat",(e,t)=>{dt.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),i=r?"int":"number",[n,o]=ex[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=n,a.maximum=o,r)a.pattern=Ox}),e._zod.check=(s)=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});return}}if(a<n)s.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort});if(a>o)s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Ux=K("$ZodCheckBigIntFormat",(e,t)=>{dt.init(e,t);let[r,i]=tx[t.format];e._zod.onattach.push((n)=>{let o=n._zod.bag;o.format=t.format,o.minimum=r,o.maximum=i}),e._zod.check=(n)=>{let o=n.value;if(o<r)n.issues.push({origin:"bigint",input:o,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(o>i)n.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),qx=K("$ZodCheckMaxSize",(e,t)=>{var r;dt.init(e,t),(r=e._zod.def).when??(r.when=(i)=>{let n=i.value;return!fo(n)&&n.size!==void 0}),e._zod.onattach.push((i)=>{let n=i._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)i._zod.bag.maximum=t.maximum}),e._zod.check=(i)=>{let n=i.value;if(n.size<=t.maximum)return;i.issues.push({origin:_u(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Zx=K("$ZodCheckMinSize",(e,t)=>{var r;dt.init(e,t),(r=e._zod.def).when??(r.when=(i)=>{let n=i.value;return!fo(n)&&n.size!==void 0}),e._zod.onattach.push((i)=>{let n=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)i._zod.bag.minimum=t.minimum}),e._zod.check=(i)=>{let n=i.value;if(n.size>=t.minimum)return;i.issues.push({origin:_u(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Mx=K("$ZodCheckSizeEquals",(e,t)=>{var r;dt.init(e,t),(r=e._zod.def).when??(r.when=(i)=>{let n=i.value;return!fo(n)&&n.size!==void 0}),e._zod.onattach.push((i)=>{let n=i._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size}),e._zod.check=(i)=>{let n=i.value,o=n.size;if(o===t.size)return;let s=o>t.size;i.issues.push({origin:_u(n),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),Fx=K("$ZodCheckMaxLength",(e,t)=>{var r;dt.init(e,t),(r=e._zod.def).when??(r.when=(i)=>{let n=i.value;return!fo(n)&&n.length!==void 0}),e._zod.onattach.push((i)=>{let n=i._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)i._zod.bag.maximum=t.maximum}),e._zod.check=(i)=>{let n=i.value;if(n.length<=t.maximum)return;let s=ku(n);i.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Hx=K("$ZodCheckMinLength",(e,t)=>{var r;dt.init(e,t),(r=e._zod.def).when??(r.when=(i)=>{let n=i.value;return!fo(n)&&n.length!==void 0}),e._zod.onattach.push((i)=>{let n=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)i._zod.bag.minimum=t.minimum}),e._zod.check=(i)=>{let n=i.value;if(n.length>=t.minimum)return;let s=ku(n);i.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Kx=K("$ZodCheckLengthEquals",(e,t)=>{var r;dt.init(e,t),(r=e._zod.def).when??(r.when=(i)=>{let n=i.value;return!fo(n)&&n.length!==void 0}),e._zod.onattach.push((i)=>{let n=i._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=(i)=>{let n=i.value,o=n.length;if(o===t.length)return;let s=ku(n),a=o>t.length;i.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),tc=K("$ZodCheckStringFormat",(e,t)=>{var r,i;if(dt.init(e,t),e._zod.onattach.push((n)=>{let o=n._zod.bag;if(o.format=t.format,t.pattern)o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(i=e._zod).check??(i.check=()=>{})}),Jx=K("$ZodCheckRegex",(e,t)=>{tc.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Vx=K("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Dx),tc.init(e,t)}),Wx=K("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Lx),tc.init(e,t)}),Gx=K("$ZodCheckIncludes",(e,t)=>{dt.init(e,t);let r=cn(t.includes),i=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=i,e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),e._zod.check=(n)=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Qx=K("$ZodCheckStartsWith",(e,t)=>{dt.init(e,t);let r=new RegExp(`^${cn(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((i)=>{let n=i._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(i)=>{if(i.value.startsWith(t.prefix))return;i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),Yx=K("$ZodCheckEndsWith",(e,t)=>{dt.init(e,t);let r=new RegExp(`.*${cn(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((i)=>{let n=i._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(i)=>{if(i.value.endsWith(t.suffix))return;i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}});Xx=K("$ZodCheckProperty",(e,t)=>{dt.init(e,t),e._zod.check=(r)=>{let i=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(i instanceof Promise)return i.then((n)=>jO(n,r,t.property));jO(i,r,t.property);return}}),ew=K("$ZodCheckMimeType",(e,t)=>{dt.init(e,t);let r=new Set(t.mime);e._zod.onattach.push((i)=>{i._zod.bag.mime=t.mime}),e._zod.check=(i)=>{if(r.has(i.value.type))return;i.issues.push({code:"invalid_value",values:t.mime,input:i.value.type,inst:e,continue:!t.abort})}}),tw=K("$ZodCheckOverwrite",(e,t)=>{dt.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}})});class Qp{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
|
|
150
150
|
`).filter((o)=>o),i=Math.min(...r.map((o)=>o.length-o.trimStart().length)),n=r.map((o)=>o.slice(i)).map((o)=>" ".repeat(this.indent*2)+o);for(let o of n)this.content.push(o)}compile(){let e=Function,t=this?.args,i=[...(this?.content??[""]).map((n)=>` ${n}`)];return new e(...t,i.join(`
|
|
@@ -406,7 +406,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
406
406
|
`)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
407
407
|
`,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=ey(e),r=Yc(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=ey(e),r=Yc(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()}}}Xle.Parser=Dq});var qq=Se(function(cue){var Lq=W1(),tue=zd(),Ud=Nd(),rue=o1(),nue=Ge(),iue=oT(),Bq=sT();function jq(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new iue.LineCounter||null,prettyErrors:t}}function oue(e,t={}){let{lineCounter:r,prettyErrors:i}=jq(t),n=new Bq.Parser(r?.addNewLine),o=new Lq.Composer(t),s=Array.from(o.compose(n.parse(e)));if(i&&r)for(let a of s)a.errors.forEach(Ud.prettifyError(e,r)),a.warnings.forEach(Ud.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},o.streamInfo())}function Uq(e,t={}){let{lineCounter:r,prettyErrors:i}=jq(t),n=new Bq.Parser(r?.addNewLine),o=new Lq.Composer(t),s=null;for(let a of o.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new Ud.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(i&&r)s.errors.forEach(Ud.prettifyError(e,r)),s.warnings.forEach(Ud.prettifyError(e,r));return s}function sue(e,t,r){let i=void 0;if(typeof t==="function")i=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=Uq(e,r);if(!n)return null;if(n.warnings.forEach((o)=>rue.warn(n.options.logLevel,o)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:i},r))}function aue(e,t,r){let i=null;if(typeof t==="function"||Array.isArray(t))i=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(nue.isDocument(e)&&!i)return e.toString(r);return new tue.Document(e,i,r).toString(r)}cue.parse=sue;cue.parseAllDocuments=oue;cue.parseDocument=Uq;cue.stringify=aue});var pue,mue,hue,aT,gue,Bo,yue,bue,Sue,xue,iBe,wue,vue,_ue,ry,Zq,kue,Eue,Iue,Tue,Aue,$ue,Cue,Rue,Oue,Pue,Pi,zi,zue,Xc,cT,Nue,Due,Lue,Bue,jue,Uue,que,Zue,Mue,ii,Fue,Hue,Kue;var qd=S(()=>{pue=W1(),mue=zd(),hue=P1(),aT=Nd(),gue=xd(),Bo=Ge(),yue=Po(),bue=Nt(),Sue=No(),xue=Do(),iBe=Yg(),wue=iT(),vue=oT(),_ue=sT(),ry=qq(),Zq=bd();kue=pue.Composer,Eue=mue.Document,Iue=hue.Schema,Tue=aT.YAMLError,Aue=aT.YAMLParseError,$ue=aT.YAMLWarning,Cue=gue.Alias,Rue=Bo.isAlias,Oue=Bo.isCollection,Pue=Bo.isDocument,Pi=Bo.isMap,zi=Bo.isNode,zue=Bo.isPair,Xc=Bo.isScalar,cT=Bo.isSeq,Nue=yue.Pair,Due=bue.Scalar,Lue=Sue.YAMLMap,Bue=xue.YAMLSeq,jue=wue.Lexer,Uue=vue.LineCounter,que=_ue.Parser,Zue=ry.parse,Mue=ry.parseAllDocuments,ii=ry.parseDocument,Fue=ry.stringify,Hue=Zq.visit,Kue=Zq.visitAsync});var Vq={};Ht(Vq,{assertPilotUsersRemoved:()=>uT,createPilotOffboardDriver:()=>lT,offboardPilotUsers:()=>Fq});import{access as Jue,readdir as Vue,readFile as Wue,rm as Zd,writeFile as Gue}from"fs/promises";import{basename as Que,join as Ni}from"path";async function Fq(e,t){let r=[...new Set(t.handles.map((f)=>$r.parse(f)))].sort((f,p)=>f.localeCompare(p));if(r.length===0)throw Error("At least one pilot handle is required");let i=t.dryRun??!0,n=`sunset:${r.join(",")}`;if(!i&&t.confirmation!==n)throw Error(`Exact confirmation required: ${n}`);let o=t.env??process.env,s=t.logger??console.info,a=await xt(e),c=r.map((f)=>Yue(a,f,o)),l=t.driver??lT({env:o,fetchImpl:t.fetchImpl,contentRepoTokenName:a.pilot.contentRepoAdminToken}),u=await Promise.all(c.map(async(f)=>({target:f,inspection:await l.inspect(f)})));if(ede(u),tde(u,i,s),!i){for(let f of u)if(!f.inspection.contentRepoArchived)await l.archiveContentRepo(f.target),s(`[${f.target.handle}] archived ${f.target.contentRepo}`);for(let f of u)for(let p of f.inspection.dnsRecords)await l.deleteDnsRecord(f.target,p),s(`[${f.target.handle}] deleted DNS ${p.name}`);for(let f of u)if(f.inspection.server)await l.deleteServer(f.target,f.inspection.server),s(`[${f.target.handle}] deleted ${f.target.instanceName}`);await Xue(c,l,t.sleep??((f)=>new Promise((p)=>setTimeout(p,f)))),await rde(e,r),await Ai(e),await uT(e,r),s(`Removed desired state for ${r.length} pilot user(s)`)}return{dryRun:i,handles:r,confirmation:n,plans:u}}function Yue(e,t,r){let i=e.users.find((u)=>u.handle===t),n=`${t}${e.pilot.domainSuffix}`,o=i?.domain??n,s=MI(o,{sharedDomain:e.pilot.domainSuffix}),a=i?.cloudflareZoneId??ny(r,"CF_ZONE_ID"),c=i?.contentRepo??`${e.pilot.contentRepoPrefix}${t}-content`,l=c.includes("/")?c:`${e.pilot.githubOrg}/${c}`;return{handle:t,instanceName:`rover-${t}`,domain:o,previewDomain:s,...o===n?{}:{wwwDomain:`www.${o}`},contentRepo:l,cloudflareZoneId:a}}async function Xue(e,t,r){for(let i of e)for(let n=1;n<=20;n+=1){let o=await t.inspect(i);if(!o.server&&o.dnsRecords.length===0&&o.contentRepoArchived)break;if(n===20)throw Error(`[${i.handle}] provider cleanup did not converge`);await r(1500)}}function ede(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 i=new Set([t.domain,t.previewDomain,...t.wwwDomain?[t.wwwDomain]:[]]);for(let n of r.dnsRecords){if(!i.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 tde(e,t,r){r(`${t?"Dry run":"Apply"}: ${e.map(({target:i})=>i.handle).join(", ")}`);for(let{target:i,inspection:n}of e){let o=n.server?`delete ${i.instanceName}`:"already absent",s=n.dnsRecords.length>0?n.dnsRecords.map((c)=>`${c.type} ${c.name}`).join(", "):"already absent",a=n.contentRepoArchived?"already archived":`archive ${i.contentRepo}`;r(`[${i.handle}] server: ${o}; DNS: ${s}; repo: ${a}`)}r("Runtime backups: none")}async function rde(e,t){let r=new Set(t),i=Ni(e,"cohorts");for(let n of(await Vue(i)).filter((o)=>o.endsWith(".yaml"))){let o=Ni(i,n),s=await Wue(o,"utf8"),a=ii(s);if(a.errors.length>0)throw Error(`${n}: ${a.errors[0]?.message??"invalid YAML"}`);let c=a.get("members",!0);if(!cT(c))throw Error(`${n}: members must be a sequence`);let l=c.items.filter((u)=>!Xc(u)||typeof u.value!=="string"||!r.has(u.value));if(l.length===c.items.length)continue;if(l.length===0){await Zd(o);continue}c.items=l,ln.parse(a.toJS()),await Gue(o,a.toString())}for(let n of t)await Promise.all([Zd(Ni(e,"users",`${n}.yaml`),{force:!0}),Zd(Ni(e,"users",`${n}.secrets.yaml`),{force:!0}),Zd(Ni(e,"users",`${n}.secrets.yaml.age`),{force:!0}),Zd(Ni(e,"users",n),{recursive:!0,force:!0})])}function lT(e){let t=e.fetchImpl??fetch,r=ny(e.env,"HCLOUD_TOKEN"),i=ny(e.env,"CF_API_TOKEN"),n=ny(e.env,e.contentRepoTokenName);return{async inspect(o){let[s,a,c]=await Promise.all([nde(t,r,o.instanceName),Promise.all([o.domain,o.previewDomain,...o.wwwDomain?[o.wwwDomain]:[]].map((l)=>ide(t,i,o.cloudflareZoneId,l))).then((l)=>l.flat()),ode(t,n,o.contentRepo)]);if(s.length>1)throw Error(`[${o.handle}] expected at most one server, found ${s.length}`);return{...s[0]?{server:s[0]}:{},dnsRecords:a,contentRepoArchived:c.archived}},async archiveContentRepo(o){await el(t,`https://api.github.com/repos/${o.contentRepo}`,{method:"PATCH",headers:Hq(n),body:JSON.stringify({archived:!0})},"GitHub repository archive")},async deleteDnsRecord(o,s){if(tl(await el(t,`https://api.cloudflare.com/client/v4/zones/${o.cloudflareZoneId}/dns_records/${s.id}`,{method:"DELETE",headers:Kq(i)},"Cloudflare DNS delete")).success!==!0)throw Error(`Cloudflare DNS delete failed for ${s.name}`)},async deleteServer(o,s){await el(t,`https://api.hetzner.cloud/v1/servers/${s.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}},"Hetzner server delete",!0)}}}async function nde(e,t,r){let i=new URL("https://api.hetzner.cloud/v1/servers");i.searchParams.set("label_selector",`brain=${r}`);let o=tl(await el(e,i.toString(),{headers:{Authorization:`Bearer ${t}`}},"Hetzner server lookup")).servers;if(!Array.isArray(o))throw Error("Hetzner server lookup returned an invalid payload");return o.map((s)=>{let a=tl(s),c=Mq(a.public_net),l=Mq(c?.ipv4);return{id:sde(a.id,"Hetzner server id"),name:Md(a.name,"Hetzner server name"),...typeof l?.ip==="string"?{ip:l.ip}:{}}})}async function ide(e,t,r,i){let n=new URL(`https://api.cloudflare.com/client/v4/zones/${r}/dns_records`);n.searchParams.set("name",i);let o=tl(await el(e,n.toString(),{headers:Kq(t)},"Cloudflare DNS lookup")),s=o.result;if(o.success!==!0||!Array.isArray(s))throw Error(`Cloudflare DNS lookup failed for ${i}`);return s.map((a)=>{let c=tl(a),l=Md(c.type,"Cloudflare record type");if(l!=="A"&&l!=="CNAME")throw Error(`Unsupported Cloudflare record type ${l} for ${i}`);return{id:Md(c.id,"Cloudflare record id"),name:Md(c.name,"Cloudflare record name"),type:l,content:Md(c.content,"Cloudflare record content")}})}async function ode(e,t,r){let i=tl(await el(e,`https://api.github.com/repos/${r}`,{headers:Hq(t)},"GitHub repository lookup"));if(typeof i.archived!=="boolean")throw Error(`Invalid repository archive state for ${r}`);return{archived:i.archived}}async function el(e,t,r,i,n=!1){let o=await e(t,r),s=await o.text();if(!o.ok)throw Error(`${i} failed (${o.status}): ${s}`);if(!s&&n)return{};try{return JSON.parse(s)}catch{throw Error(`${i} returned an invalid JSON response`)}}function Hq(e){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"}}function Kq(e){return{Authorization:`Bearer ${e}`}}function ny(e,t){let r=e[t];if(!r)throw Error(`Missing required environment variable: ${t}`);return r}function Jq(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function tl(e){if(!Jq(e))throw Error("Provider returned an unexpected payload");return e}function Mq(e){return Jq(e)?e:void 0}function Md(e,t){if(typeof e!=="string"||e.length===0)throw Error(`Missing ${t}`);return e}function sde(e,t){if(typeof e!=="number")throw Error(`Missing ${t}`);return e}async function ade(e){try{return await Jue(e),!0}catch{return!1}}async function uT(e,t){for(let r of t)for(let i of[Ni(e,"users",`${r}.yaml`),Ni(e,"users",`${r}.secrets.yaml.age`),Ni(e,"users",r)])if(await ade(i))throw Error(`Offboarded user state remains: ${Que(i)}`)}var dT=S(()=>{qd();un();FI();Ec();Xn()});var KF={};Ht(KF,{upgradePilotRepo:()=>whe});import{readFile as yhe}from"fs/promises";import{join as bhe}from"path";async function HF(e){let t=bhe(e,"package.json"),i=She.parse(JSON.parse(await yhe(t,"utf8"))).devDependencies?.["@rizom/ops"];if(!i)throw Error(`${t} does not pin @rizom/ops as a devDependency`);return i}async function xhe(e,t){let i=await Bun.spawn(e,{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(i!==0)throw Error(`${e.join(" ")} failed with exit ${i}`)}async function whe(e,t={}){let r=t.exec??xhe,i=await HF(e),n=t.version??"latest";await r(["bun","add","--dev","--exact",`@rizom/ops@${n}`],e);let o=await HF(e);return await r(["bun","x","brains-ops","init","."],e),{from:i,to:o}}var She;var JF=S(()=>{Ae();She=d.object({devDependencies:d.record(d.string(),d.string()).optional()})});function VF(e){if(e===null||typeof e!=="object"||Array.isArray(e))return!1;let t=vhe(e);return t===Object.prototype||t===null}var vhe;var WF=S(()=>{vhe=Object.getPrototypeOf});function XF(e){if(e==="core")return{bundles:["core","media","web","chat"]};if(e==="default")return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"],remove:[...Ehe]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"]}}function Ihe(e){let t=_he.parse(e);return vo.parse({brainVersion:t.brainVersion,bundleContract:wo,...XF(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,aiApiKey:t.aiApiKey,gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function The(e){let t=khe.parse(e),r=t.presetOverride?XF(t.presetOverride):void 0;return ln.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?{aiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function e3(e){let t=ii(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!Pi(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function d$(e,t){if(!Pi(e.contents))return;return e.contents.items.find((r)=>Xc(r.key)&&r.key.value===t)}function GF(e,t){if(!zi(e)||!zi(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 QF(e,t){if(!e||!zi(t))return;let r=[zi(e.key)?e.key.commentBefore:void 0,zi(e.key)?e.key.comment:void 0,zi(e.value)?e.value.commentBefore:void 0,zi(e.value)?e.value.comment:void 0].filter((i)=>i!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((i)=>i!==void 0).join(`
|
|
408
408
|
`)}function t3(e,t,r,i){if(!Pi(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>Xc(s.key)&&s.key.value===t),o=e.createPair(r,[...i]);if(n>=0){let s=e.contents.items[n];GF(s?.key,o.key),GF(s?.value,o.value),e.contents.items.splice(n,1,o)}else e.contents.add(o);return o}function r3(e){let t=e3(e),r=Ihe(t.toJS()),i=d$(t,"schemaVersion"),n=d$(t,"model");QF(i,d$(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",wo);let o=t3(t,"preset","bundles",r.bundles);if(QF(n,o.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 vo.parse(t.toJS()),t.toString({lineWidth:0})}function n3(e){let t=e3(e),r=The(t.toJS());if(r.bundlesOverride)t3(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 ln.parse(t.toJS()),t.toString({lineWidth:0})}var YF,Cf,_he,khe,Ehe;var i3=S(()=>{ki();Ae();qd();Xn();YF=d.enum(["core","default","pro"]),Cf=d.string().min(1),_he=d.strictObject({schemaVersion:d.literal(1),brainVersion:jt,model:d.literal("rover"),githubOrg:d.string().min(1),contentRepoPrefix:d.string().min(1),domainSuffix:d.string().min(1),preset:YF,aiApiKey:Cf,gitSyncToken:Cf,contentRepoAdminToken:Cf,agePublicKey:d.string().startsWith("age1").min(1)}),khe=d.strictObject({members:d.array($r).min(1),brainVersionOverride:jt.optional(),presetOverride:YF.optional(),aiApiKeyOverride:Cf.optional(),gitSyncTokenOverride:Cf.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:d.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),Ehe=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function s3(e,t){let r=ii(e,{keepSourceTokens:!0});if(r.errors.length>0||!Pi(r.contents))throw Error(`Invalid ${t} YAML`);return r}function Ohe(e,t){return e.length===t.length&&e.every((r,i)=>r===t[i])}function a3(e,t,r){if(!Ohe(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function c3(e){let t=An(e,Rhe);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function l3(e,t){let r=s3(e,"pilot desired-state"),i=$he.parse(r.toJS());return a3("pilot.yaml",i.bundles,t),r.set("bundleContract",wo),r.set("bundles",t.targetBundles),vo.parse(r.toJS()),r.toString({lineWidth:0})}function u3(e,t,r){let i=s3(e,`cohort ${t}`),n=Che.parse(i.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`);a3(`cohort ${t}`,n.bundlesOverride,r),i.set("bundlesOverride",r.targetBundles)}return ln.parse(i.toJS()),i.toString({lineWidth:0})}var Ahe,f$,nb,$he,Che,o3,Rhe;var d3=S(()=>{ki();Ae();qd();Xn();Ahe=d.enum(["core","site","publishing","team"]),f$=d.array(Ahe).min(1),nb=d.array(d.string().min(1)),$he=d.strictObject({brainVersion:jt,bundles:f$,add:nb.optional(),remove:nb.optional(),githubOrg:d.string().min(1),contentRepoPrefix:d.string().min(1),domainSuffix:d.string().min(1),aiApiKey:d.string().min(1),gitSyncToken:d.string().min(1),contentRepoAdminToken:d.string().min(1),agePublicKey:d.string().startsWith("age1").min(1)}),Che=d.strictObject({members:d.array($r).min(1),brainVersionOverride:jt.optional(),bundlesOverride:f$.optional(),addOverride:nb.optional(),removeOverride:nb.optional(),aiApiKeyOverride:d.string().min(1).optional(),gitSyncTokenOverride:d.string().min(1).optional()}),o3=d.strictObject({sourceBundles:f$,targetBundles:d.array(gh).min(1)}),Rhe=d.strictObject({bundleContract:d.literal(wo),pilot:o3,cohorts:d.record($r,o3)})});var g3={};Ht(g3,{loadCapabilityBundleReview:()=>qhe,loadReviewedSitePins:()=>Uhe,parseReviewedSitePins:()=>h3,stageLegacyCrossover:()=>Mhe});import{access as Phe,cp as zhe,mkdir as f3,readFile as Al,readdir as m3,writeFile as Tl}from"fs/promises";import{basename as Nhe,join as mi,relative as ib,resolve as p3}from"path";import{fileURLToPath as Dhe}from"url";function h3(e){let t=An(e,Lhe);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function Uhe(e){return h3(await Al(e,"utf8"))}async function qhe(e){return c3(await Al(e,"utf8"))}async function Zhe(e,t){let r=mi(e,"users"),i=(await m3(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),o=[];for(let s of i){let a=mi(r,s),c=await Al(a,"utf8"),l=ii(c,{keepSourceTokens:!0});if(l.errors.length>0||!Pi(l.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let u=Bhe.parse(l.toJS());if(!u.siteOverride)continue;let f=t?.[u.handle];if(!f)throw Error(`User ${u.handle} has a siteOverride but no reviewed site pin`);if(n.delete(u.handle),f.package!==u.siteOverride.package||f.theme!==u.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${u.handle}`);if(u.siteOverride.version!==void 0&&u.siteOverride.version!==f.version)throw Error(`Reviewed site version does not match the existing pin for user ${u.handle}`);if(u.siteOverride.themeVersion!==void 0&&u.siteOverride.themeVersion!==f.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${u.handle}`);if(l.setIn(["siteOverride","version"],f.version),f.themeVersion!==void 0)l.setIn(["siteOverride","themeVersion"],f.themeVersion);else l.deleteIn(["siteOverride","themeVersion"]);yh.parse(l.toJS());let p=l.toString({lineWidth:0});if(p!==c)await Tl(a,p),o.push(ib(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return o}async function Mhe(e,t,r={}){let i=p3(e),n=p3(t);if(i===n||n.startsWith(`${i}/`))throw Error("Crossover output must be outside the source repository");await zhe(i,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(A)=>{let z=Nhe(A);return z!==".git"&&z!==".operator"&&z!==".brains-ops"&&z!==".turbo"&&z!=="dist"&&z!=="node_modules"&&z!==".env"&&z!==".env.local"&&!z.endsWith(".secrets.yaml")}});let o=[],s=mi(n,"docs","canonical-crossover-record.md");try{await Phe(s)}catch{await f3(mi(n,"docs"),{recursive:!0}),await Tl(s,await Al(jhe,"utf8")),o.push("docs/canonical-crossover-record.md")}let a=mi(n,"pilot.yaml"),c=await Al(a,"utf8"),u=ii(c).toJS();if(!VF(u))throw Error(`${a} is not a YAML mapping`);let f=Array.isArray(u.bundles),p=r.bundleReview,m;if(f){if(!p)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");m=l3(c,p.pilot)}else m=r3(c);await Tl(a,m),o.push("pilot.yaml");let y=mi(n,"cohorts"),g=(await m3(y,{withFileTypes:!0})).filter((A)=>A.isFile()&&/\.ya?ml$/.test(A.name)).map((A)=>A.name).sort(),b=new Set(Object.keys(p?.cohorts??{}));for(let A of g){let z=mi(y,A),j=await Al(z,"utf8"),E=A.replace(/\.ya?ml$/,""),F=p?.cohorts[E];if(F)b.delete(E);await Tl(z,f?u3(j,E,F):n3(j)),o.push(ib(n,z))}if(f&&b.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...b].sort().join(", ")}`);o.push(...await Zhe(n,r.sitePins));let _=await xt(n),T=fg(_.pilot.githubOrg);for(let A of _.users){let z=await T(A),j=mi(n,"users",A.handle);if(await f3(j,{recursive:!0}),z.brainYaml){let E=mi(j,"brain.yaml");await Tl(E,z.brainYaml),o.push(ib(n,E))}if(z.envFile){let E=mi(j,".env");await Tl(E,z.envFile),o.push(ib(n,E))}}return await Ai(n,{registry:_}),o.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(o)].sort()}}var Lhe,Bhe,jhe;var y3=S(()=>{ki();WF();Ae();qd();JI();i3();d3();un();Ec();Xn();Lhe=d.strictObject({sites:d.record($r,tE)}),Bhe=d.object({handle:$r,siteOverride:d.object({package:d.string().min(1),version:jt.optional(),theme:d.string().min(1).optional(),themeVersion:jt.optional()}).optional()}).passthrough(),jhe=Dhe(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var b3="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as S3}from"crypto";function Hhe(e){if(e<0)throw RangeError("Wrong ID size");try{if(!is||is.length<e)is=Buffer.allocUnsafe(e*Fhe),S3.getRandomValues(is),$l=0;else if($l+e>is.length)S3.getRandomValues(is),$l=0}catch(t){throw is=void 0,t}$l+=e}function x3(e=21){Hhe(e|=0);let t="";for(let r=$l-e;r<$l;r++)t+=b3[is[r]&63];return t}var Fhe=128,is,$l;var w3=()=>{};function Gi(e=12){return x3(e)}var Rf=S(()=>{w3()});import{openSync as Khe,writeSync as Jhe}from"fs";class on{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??_a.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=Khe(this.logFile,"a")}catch{}}static getInstance(e){if(!on.instance)on.instance=new on(e);else if(e?.useStderr!==void 0)on.instance.useStderr=e.useStderr;return on.instance}static resetInstance(){on.instance=null}static createFresh(e){return new on(e)}formatEntry(e,t,r){let i=new Date().toISOString();if(this.format==="json"){let n={ts:i,level:e,msg:t};if(this.context)n.ctx=this.context;if(r.length>0)n.data=r;return JSON.stringify(n)}return this.context?`[${i}] [${this.context}] ${t}`:`[${i}] ${t}`}write(e,t,r,i){if(this.format==="json")e(this.formatEntry(t,r,i));else if(i.length>0)e(this.formatEntry(t,r,[]),...i);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,i);try{Jhe(this.fileHandle,n+`
|
|
409
|
-
`)}catch{}}}formatJsonEntry(e,t,r){let i={ts:new Date().toISOString(),level:e,msg:t};if(this.context)i.ctx=this.context;if(r.length>0)i.data=r;return JSON.stringify(i)}silly(e,...t){if(this.level<=_a.SILLY)this.write(console.debug.bind(console),"silly",e,t)}verbose(e,...t){if(this.level<=_a.VERBOSE)this.write(console.debug.bind(console),"verbose",e,t)}debug(e,...t){if(this.level<=_a.DEBUG)this.write(console.debug.bind(console),"debug",e,t)}info(e,...t){if(this.level<=_a.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<=_a.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=_a.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new on({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var _a,uZe;var p$=S(()=>{_a={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};uZe=on.getInstance()});var m$,Vhe,Cl,mZe;var Of=S(()=>{ti();Ae();m$=d.enum(["file_operations","content_operations","data_processing","batch_processing"]),Vhe=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:m$,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:Ac.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:_o.optional()}),Cl=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:m$,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:Ac.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:_o.optional(),rootJobId:d.string()}),mZe=d.enum(["none","skip","replace","coalesce"])});var Whe,os=15000;var Pf=S(()=>{Of();Ae();Whe=d.object({id:d.string(),type:d.string(),data:d.string(),status:d.enum(["pending","processing","completed","failed"]),source:d.string().nullable(),priority:d.number(),retryCount:d.number(),maxRetries:d.number(),lastError:d.string().nullable(),createdAt:d.number(),scheduledFor:d.number(),startedAt:d.number().nullable(),completedAt:d.number().nullable(),attemptId:d.string().nullable(),workerSlotId:d.string().nullable(),workerSessionId:d.string().nullable(),leaseExpiresAt:d.number().nullable(),attemptHeartbeatAt:d.number().nullable(),runtimeUpdatedAt:d.number().nullable(),metadata:Cl,progress:d.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:d.unknown().nullable().optional()})});var h$,v3,Me,Ghe,Qhe,_3,Yhe;var ss=S(()=>{Ae();Of();h$=d.enum(["pending","processing","completed","failed"]),v3=d.enum(["completed","failed"]),Me={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Ghe=d.object({id:d.string(),type:d.string(),status:h$,data:d.unknown(),result:d.unknown().optional(),lastError:d.string().optional().nullable(),attempts:d.number(),maxRetries:d.number(),priority:d.number(),createdAt:d.date(),updatedAt:d.date(),processedAt:d.date().optional().nullable(),completedAt:d.date().optional().nullable(),failedAt:d.date().optional().nullable()}),Qhe=d.object({jobId:d.string(),type:d.string(),status:v3,result:d.unknown().optional(),error:d.string().optional()}),_3=d.object({success:d.literal(!1),error:d.string().optional()}),Yhe=d.object({id:d.string(),type:d.enum(["job","batch"]),status:h$,message:d.string().optional(),progress:d.object({current:d.number(),total:d.number(),percentage:d.number()}).optional(),aggregationKey:d.string().optional(),batchDetails:d.object({totalOperations:d.number(),completedOperations:d.number(),failedOperations:d.number(),currentOperation:d.string().optional(),errors:d.array(d.string()).optional()}).optional(),jobDetails:d.object({jobType:d.string(),priority:d.number(),retryCount:d.number()}).optional(),metadata:Cl})});var Be,cr;var jn=S(()=>{Be=class Be extends Error{code;extendedCode;rawCode;constructor(e,t,r,i,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=i,this.name="LibsqlError"}};cr=class cr extends Be{statementIndex;constructor(e,t,r,i,n,o){super(e,r,i,n,o);this.statementIndex=t,this.name="LibsqlBatchError"}}});function k3(e){let t=Xhe.exec(e);if(t===null)throw new Be(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,i=r.scheme,n=r.authority!==void 0?ege(r.authority):void 0,o=ka(r.path),s=r.query!==void 0?rge(r.query):void 0,a=r.fragment!==void 0?ka(r.fragment):void 0;return{scheme:i,authority:n,path:o,query:s,fragment:a}}function ege(e){let t=tge.exec(e);if(t===null)throw new Be("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,i=ka(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,o=r.username!==void 0?{username:ka(r.username),password:r.password!==void 0?ka(r.password):void 0}:void 0;return{host:i,port:n,userinfo:o}}function rge(e){let t=e.split("&"),r=[];for(let i of t){if(i==="")continue;let n,o,s=i.indexOf("=");if(s<0)n=i,o="";else n=i.substring(0,s),o=i.substring(s+1);r.push({key:ka(n.replaceAll("+"," ")),value:ka(o.replaceAll("+"," "))})}return{pairs:r}}function ka(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Be(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function zf(e,t,r){if(t===void 0)throw new Be(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let i=`${e}:`,n=nge(t.host),o=ige(t.port),a=`//${oge(t.userinfo)}${n}${o}`,c=r.split("/").map(encodeURIComponent).join("/");if(c!==""&&!c.startsWith("/"))c="/"+c;return new URL(`${i}${a}${c}`)}function nge(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function ige(e){return e!==void 0?`:${e}`:""}function oge(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var Xhe,tge;var ob=S(()=>{jn();Xhe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();tge=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var Ol,E3,I3,Nf,sb,sge,lr,T3,C3=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),R3=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),O3=(e)=>{let t,r,i,n,o="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(i=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|i<<8|n,o+=Nf[t>>18&63]+Nf[t>>12&63]+Nf[t>>6&63]+Nf[t&63]}return s?o.slice(0,s-3)+"===".substring(s):o},b$,g$,ab=(e,t=!1)=>t?C3(g$(e)):g$(e),age=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?lr(192|t>>>6)+lr(128|t&63):lr(224|t>>>12&15)+lr(128|t>>>6&63)+lr(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return lr(240|t>>>18&7)+lr(128|t>>>12&63)+lr(128|t>>>6&63)+lr(128|t&63)}},cge,P3=(e)=>e.replace(cge,age),A3,Rl=(e,t=!1)=>t?C3(A3(e)):A3(e),$3=(e)=>Rl(e,!0),lge,uge=(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 lr((r>>>10)+55296)+lr((r&1023)+56320);case 3:return lr((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return lr((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},z3=(e)=>e.replace(lge,uge),N3=(e)=>{if(e=e.replace(/\s+/g,""),!sge.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,i,n=[];for(let o=0;o<e.length;)if(t=sb[e.charAt(o++)]<<18|sb[e.charAt(o++)]<<12|(r=sb[e.charAt(o++)])<<6|(i=sb[e.charAt(o++)]),r===64)n.push(lr(t>>16&255));else if(i===64)n.push(lr(t>>16&255,t>>8&255));else n.push(lr(t>>16&255,t>>8&255,t&255));return n.join("")},S$,D3,L3=(e)=>D3(B3(e)),dge,B3=(e)=>R3(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),y$=(e)=>dge(B3(e)),fge=(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)},j3=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),U3=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,j3(r));e("fromBase64",function(){return y$(this)}),e("toBase64",function(t){return Rl(this,t)}),e("toBase64URI",function(){return Rl(this,!0)}),e("toBase64URL",function(){return Rl(this,!0)}),e("toUint8Array",function(){return L3(this)})},q3=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,j3(r));e("toBase64",function(t){return ab(this,t)}),e("toBase64URI",function(){return ab(this,!0)}),e("toBase64URL",function(){return ab(this,!0)})},pge=()=>{U3(),q3()},Pl;var cb=S(()=>{Ol=typeof Buffer==="function",E3=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,I3=typeof TextEncoder==="function"?new TextEncoder:void 0,Nf=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),sb=((e)=>{let t={};return e.forEach((r,i)=>t[r]=i),t})(Nf),sge=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,lr=String.fromCharCode.bind(String),T3=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),b$=typeof btoa==="function"?(e)=>btoa(e):Ol?(e)=>Buffer.from(e,"binary").toString("base64"):O3,g$=Ol?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let i=0,n=e.length;i<n;i+=4096)r.push(lr.apply(null,e.subarray(i,i+4096)));return b$(r.join(""))},cge=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,A3=Ol?(e)=>Buffer.from(e,"utf8").toString("base64"):I3?(e)=>g$(I3.encode(e)):(e)=>b$(P3(e)),lge=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,S$=typeof atob==="function"?(e)=>atob(R3(e)):Ol?(e)=>Buffer.from(e,"base64").toString("binary"):N3,D3=Ol?(e)=>T3(Buffer.from(e,"base64")):(e)=>T3(S$(e).split("").map((t)=>t.charCodeAt(0))),dge=Ol?(e)=>Buffer.from(e,"base64").toString("utf8"):E3?(e)=>E3.decode(D3(e)):(e)=>z3(S$(e)),Pl={version:"3.8.0",VERSION:"3.8.0",atob:S$,atobPolyfill:N3,btoa:b$,btoaPolyfill:O3,fromBase64:y$,toBase64:Rl,encode:Rl,encodeURI:$3,encodeURL:$3,utob:P3,btou:z3,decode:y$,isValid:fge,fromUint8Array:ab,toUint8Array:L3,extendString:U3,extendUint8Array:q3,extendBuiltins:pge}});function as(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 zl{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,i,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=i,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(mge),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function mge(e){return Array.prototype.map.call(e,hge)}function hge(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return Pl.fromUint8Array(new Uint8Array(e));else return e}var hi="https://github.com/libsql/libsql-client-ts#supported-urls";var Nl=S(()=>{cb()});function M3(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function Df(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:i,tls:n,intMode:o,concurrency:s}=e;s=Math.max(0,s||20),o??="number";let a=[];if(r===Z3)r="file::memory:";let c=k3(r),l=c.scheme.toLowerCase(),u=l==="file"&&c.path===Z3&&c.authority===void 0,f;if(u)f={cache:{values:["shared","private"],update:(g,b)=>a.push(`${g}=${b}`)}};else f={tls:{values:["0","1"],update:(g,b)=>n=b==="1"},authToken:{update:(g,b)=>i=b}};for(let{key:g,value:b}of c.query?.pairs??[]){if(!Object.hasOwn(f,g))throw new Be(`Unsupported URL query parameter ${JSON.stringify(g)}`,"URL_PARAM_NOT_SUPPORTED");let _=f[g];if(_.values!==void 0&&!_.values.includes(b))throw new Be(`Unknown value for the "${g}" query argument: ${JSON.stringify(b)}. Supported values are: [${_.values.map((T)=>'"'+T+'"').join(", ")}]`,"URL_INVALID");if(_.update!==void 0)_?.update(g,b)}let p=a.length===0?"":`?${a.join("&")}`,m=c.path+p,y;if(l==="libsql")if(n===!1){if(c.authority?.port===void 0)throw new Be('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");y=t?"http":"ws"}else y=t?"https":"wss";else y=l;if(y==="http"||y==="ws")n??=!1;else n??=!0;if(y!=="http"&&y!=="ws"&&y!=="https"&&y!=="wss"&&y!=="file")throw new Be(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(c.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(o!=="number"&&o!=="bigint"&&o!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(o)}`);if(c.fragment!==void 0)throw new Be(`URL fragments are not supported: ${JSON.stringify("#"+c.fragment)}`,"URL_INVALID");if(u)return{scheme:"file",tls:!1,path:m,intMode:o,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:y,tls:n,authority:c.authority,path:m,authToken:i,intMode:o,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 Z3=":memory:";var Lf=S(()=>{jn();ob();Nl()});var H3=Se(function(xn){var gge=xn&&xn.__createBinding||(Object.create?function(e,t,r,i){if(i===void 0)i=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,i,n)}:function(e,t,r,i){if(i===void 0)i=r;e[i]=t[r]}),yge=xn&&xn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),F3=xn&&xn.__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))gge(t,e,r)}return yge(t,e),t};Object.defineProperty(xn,"__esModule",{value:!0});xn.load=xn.currentTarget=void 0;var bge=F3(pr("path")),Sge=F3(pr("fs"));function xge(){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 wge()?`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}`)}xn.currentTarget=xge;function wge(){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 vge(e){let t=bge.join(e,"index.node");return Sge.existsSync(t)?pr(t):null}xn.load=vge});var V3=Se(function(zZe,J3){var K3=()=>process.platform==="linux",x$=null,_ge=()=>{if(!x$)x$=K3()&&process.report?process.report.getReport():{};return x$};J3.exports={isLinux:K3,getReport:_ge}});var Q3=Se(function(NZe,G3){var W3=pr("fs"),kge=(e)=>W3.readFileSync(e,"utf-8"),Ege=(e)=>new Promise((t,r)=>{W3.readFile(e,"utf-8",(i,n)=>{if(i)r(i);else t(n)})});G3.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:kge,readFile:Ege}});var m5=Se(function(DZe,p5){var X3=pr("child_process"),{isLinux:Dl,getReport:e5}=V3(),{LDD_PATH:lb,readFile:t5,readFileSync:r5}=Q3(),gi,yi,cs="",n5=()=>{if(!cs)return new Promise((e)=>{X3.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{cs=t?" ":r,e(cs)})});return cs},i5=()=>{if(!cs)try{cs=X3.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){cs=" "}return cs},Qi="glibc",o5=/GLIBC\s(\d+\.\d+)/,Ea="musl",Ige=Qi.toUpperCase(),Tge=Ea.toLowerCase(),Age=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),s5=()=>{let e=e5();if(e.header&&e.header.glibcVersionRuntime)return Qi;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Age))return Ea}return null},a5=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Qi))return Qi;if(r&&r.includes(Ea))return Ea;return null},c5=(e)=>{if(e.includes(Tge))return Ea;if(e.includes(Ige))return Qi;return null},$ge=async()=>{if(gi!==void 0)return gi;gi=null;try{let e=await t5(lb);gi=c5(e)}catch(e){}return gi},Cge=()=>{if(gi!==void 0)return gi;gi=null;try{let e=r5(lb);gi=c5(e)}catch(e){}return gi},l5=async()=>{let e=null;if(Dl()){if(e=await $ge(),!e)e=s5();if(!e){let t=await n5();e=a5(t)}}return e},u5=()=>{let e=null;if(Dl()){if(e=Cge(),!e)e=s5();if(!e){let t=i5();e=a5(t)}}return e},Rge=async()=>Dl()&&await l5()!==Qi,Oge=()=>Dl()&&u5()!==Qi,Pge=async()=>{if(yi!==void 0)return yi;yi=null;try{let t=(await t5(lb)).match(o5);if(t)yi=t[1]}catch(e){}return yi},zge=()=>{if(yi!==void 0)return yi;yi=null;try{let t=r5(lb).match(o5);if(t)yi=t[1]}catch(e){}return yi},d5=()=>{let e=e5();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},Y3=(e)=>e.trim().split(/\s+/)[1],f5=(e)=>{let[t,r,i]=e.split(/[\r\n]+/);if(t&&t.includes(Qi))return Y3(t);if(r&&i&&r.includes(Ea))return Y3(i);return null},Nge=async()=>{let e=null;if(Dl()){if(e=await Pge(),!e)e=d5();if(!e){let t=await n5();e=f5(t)}}return e},Dge=()=>{let e=null;if(Dl()){if(e=zge(),!e)e=d5();if(!e){let t=i5();e=f5(t)}}return e};p5.exports={GLIBC:Qi,MUSL:Ea,family:l5,familySync:u5,isNonGlibcLinux:Rge,isNonGlibcLinuxSync:Oge,version:Nge,versionSync:Dge}});var g5=Se(function(LZe,h5){var Lge={ALLOW:0,DENY:1};h5.exports=Lge});var b5=Se(function(BZe,y5){var w$={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function Ia(e,t,r){if(new.target!==Ia)return new Ia(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),w$.value=""+e,Object.defineProperty(this,"message",w$),Error.captureStackTrace(this,Ia),this.code=t,this.rawCode=r}Object.setPrototypeOf(Ia,Error);Object.setPrototypeOf(Ia.prototype,Error.prototype);Object.defineProperty(Ia.prototype,"name",w$);y5.exports=Ia});var I5=Se(function(jZe,ub){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Bge,currentTarget:jge}=H3(),{familySync:S5,GLIBC:Uge,MUSL:qge}=m5();function Zge(){if(process.env.LIBSQL_JS_DEV)return Bge(__dirname);let e=jge();if(S5()==Uge)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"&&S5()==qge)e="linux-arm-musleabihf";return pr(`@libsql/${e}`)}var{databaseOpen:Mge,databaseOpenWithSync:Fge,databaseInTransaction:Hge,databaseInterrupt:Kge,databaseClose:Jge,databaseSyncSync:Vge,databaseSyncUntilSync:Wge,databaseExecSync:Gge,databasePrepareSync:Qge,databaseDefaultSafeIntegers:Yge,databaseAuthorizer:Xge,databaseLoadExtension:eye,databaseMaxWriteReplicationIndex:tye,statementRaw:rye,statementIsReader:nye,statementGet:x5,statementRun:w5,statementInterrupt:iye,statementRowsSync:v5,statementColumns:oye,statementSafeIntegers:sye,rowsNext:aye}=Zge(),cye=g5(),_5=b5();function Ll(e){if(e.libsqlError)return new _5(e.message,e.code,e.rawCode);return e}class k5{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var i="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),i=t.syncAuth;else if(t.authToken)i=t.authToken;let o=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,c=t?.offline??!1,l=t?.remoteEncryptionKey??"";this.db=Fge(e,t.syncUrl,i,r,o,s,a,c,l)}else{let o=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,c=t?.remoteEncryptionKey??"";this.db=Mge(e,o,r,s,a,c)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return Hge(n)}}})}sync(){return Vge.call(this.db)}syncUntil(e){return Wge.call(this.db,e)}prepare(e){try{let t=Qge.call(this.db,e);return new E5(t)}catch(t){throw Ll(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...o)=>{t.exec("BEGIN "+n);try{let s=e(...o);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},i={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(i.default.value,i),Object.defineProperties(i.deferred.value,i),Object.defineProperties(i.immediate.value,i),Object.defineProperties(i.exclusive.value,i),i.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,i=this.prepare(`PRAGMA ${e}`,this,!0);return r?i.pluck().get():i.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){Xge.call(this.db,e)}loadExtension(...e){eye.call(this.db,...e)}maxWriteReplicationIndex(){return tye.call(this.db)}exec(e){try{Gge.call(this.db,e)}catch(t){throw Ll(t)}}interrupt(){Kge.call(this.db)}close(){Jge.call(this.db),this.open=!1}defaultSafeIntegers(e){return Yge.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class E5{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return rye.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return nye.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return w5.call(this.stmt,e[0]);else return w5.call(this.stmt,e.flat())}catch(t){throw Ll(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return x5.call(this.stmt,e[0]);else return x5.call(this.stmt,e.flat())}catch(t){throw Ll(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=v5.call(this.stmt,e[0]);else t=v5.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)aye.call(t,this.nextRows),this.nextRowIndex=0;let i=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!i)return{done:!0};return this.nextRowIndex++,{value:i,done:!1}}catch(i){throw Ll(i)}},[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 Ll(t)}}interrupt(){iye.call(this.stmt)}columns(){return oye.call(this.stmt)}safeIntegers(e){return sye.call(this.stmt,e??!0),this}}ub.exports=k5;ub.exports.Authorization=cye;ub.exports.SqliteError=_5});import{Buffer as A5}from"buffer";function $5(e){if(e.scheme!=="file")throw new Be(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Be(`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 ${hi}`,"URL_INVALID");if(t.port!==void 0)throw new Be("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Be("File URL cannot have username and password","URL_INVALID")}let r=M3(e);if(r&&e.syncUrl)throw new Be(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let i=e.path;if(r)i=`${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},o=new Bf.default(i,n);return Mt(o,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new C5(i,n,o,e.intMode)}class C5{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,i){this.#e=e,this.#t=t,this.#r=r,this.#n=i,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.#i(),Mt(this.#o(),r,this.#n)}async batch(e,t="deferred"){this.#i();let r=this.#o();try{Mt(r,as(t),this.#n);let i=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new cr("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let o=e[n],s=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;i.push(Mt(r,s,this.#n))}catch(o){if(o instanceof cr)throw o;if(o instanceof Be)throw new cr(o.message,n,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return Mt(r,"COMMIT",this.#n),i}finally{if(r.inTransaction)Mt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#i();let t=this.#o();try{Mt(t,"PRAGMA foreign_keys=off",this.#n),Mt(t,as("deferred"),this.#n);let r=[];for(let i=0;i<e.length;i++)try{if(!t.inTransaction)throw new cr("The transaction has been rolled back",i,"TRANSACTION_CLOSED");r.push(Mt(t,e[i],this.#n))}catch(n){if(n instanceof cr)throw n;if(n instanceof Be)throw new cr(n.message,i,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Mt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n);Mt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#o();return Mt(t,as(e),this.#n),this.#r=null,new R5(t,this.#n)}async executeMultiple(e){this.#i();let t=this.#o();try{return O5(t,e)}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n)}}async sync(){this.#i();let e=await this.#o().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 Bf.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#i(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED")}#o(){if(this.#r===null)this.#r=new Bf.default(this.#e,this.#t);return this.#r}}class R5{#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(),Mt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let i=e[r],n=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;t.push(Mt(this.#e,n,this.#t))}catch(i){if(i instanceof cr)throw i;if(i instanceof Be)throw new cr(i.message,r,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return t}async executeMultiple(e){return this.#r(),O5(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Mt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Mt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Mt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Be("The transaction is closed","TRANSACTION_CLOSED")}}function Mt(e,t,r){let i,n;if(typeof t==="string")i=t,n=[];else if(i=t.sql,Array.isArray(t.args))n=t.args.map((o)=>T5(o,r));else{n={};for(let o in t.args){let s=o[0]==="@"||o[0]==="$"||o[0]===":"?o.substring(1):o;n[s]=T5(t.args[o],r)}}try{let o=e.prepare(i);o.safeIntegers(!0);let s=!0;try{o.raw(!0)}catch{s=!1}if(s){let a=Array.from(o.columns().map((p)=>p.name)),c=Array.from(o.columns().map((p)=>p.type??"")),l=o.all(n).map((p)=>lye(p,a,r)),u=0,f=void 0;return new zl(a,c,l,0,void 0)}else{let a=o.run(n),c=a.changes,l=BigInt(a.lastInsertRowid);return new zl([],[],[],c,l)}}catch(o){throw P5(o)}}function lye(e,t,r){let i={};Object.defineProperty(i,"length",{value:e.length});for(let n=0;n<e.length;++n){let o=uye(e[n],r);Object.defineProperty(i,n,{value:o});let s=t[n];if(!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function uye(e,t){if(typeof e==="bigint")if(t==="number"){if(e<dye||e>fye)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 A5)return e.buffer;return e}function T5(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<pye||e>mye)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 A5.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 O5(e,t){try{e.exec(t)}catch(r){throw P5(r)}}function P5(e){if(e instanceof Bf.default.SqliteError){let t=e.code,r=hye(e.rawCode);return new Be(e.message,r,t,e.rawCode,e)}return e}function hye(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return gye[t]??`SQLITE_UNKNOWN_${t.toString()}`}var Bf,dye,fye=9007199254740991n,pye,mye=9223372036854775807n,gye;var z5=S(()=>{jn();Lf();Nl();Bf=hu(I5(),1);jn();dye=-9007199254740991n;pye=-9223372036854775808n;gye={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 ls;var v$=S(()=>{if(typeof WebSocket<"u")ls=WebSocket;else if(typeof global<"u")ls=global.WebSocket;else if(typeof window<"u")ls=window.WebSocket;else if(typeof self<"u")ls=self.WebSocket});class Bl{constructor(){this.intMode="number"}intMode}var st,je,jf,Ot,Uf,jl,Ta,Un,xr,bi;var Pt=S(()=>{st=class st extends Error{constructor(e){super(e);this.name="ClientError"}};je=class je extends st{constructor(e){super(e);this.name="ProtoError"}};jf=class jf extends st{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};Ot=class Ot extends st{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Uf=class Uf extends st{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};jl=class jl extends st{constructor(e){super(e);this.name="WebSocketError"}};Ta=class Ta extends st{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};Un=class Un extends st{constructor(e){super(e);this.name="ProtocolVersionError"}};xr=class xr extends st{constructor(e){super(e);this.name="InternalError"}};bi=class bi extends st{constructor(e){super(e);this.name="MisuseError"}}});function Fr(e){if(typeof e==="string")return e;throw Ul(e,"string")}function sn(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw Ul(e,"string or null")}function Yi(e){if(typeof e==="number")return e;throw Ul(e,"number")}function us(e){if(typeof e==="boolean")return e;throw Ul(e,"boolean")}function qf(e){if(Array.isArray(e))return e;throw Ul(e,"array")}function Lt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw Ul(e,"object")}function qn(e,t){return qf(e).map((r)=>t(Lt(r)))}function Ul(e,t){if(e===void 0)return new je(`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 je(`Expected ${t}, received ${r}`)}function Aa(e,t){return t(Lt(e))}var ql=S(()=>{Pt()});class N5{#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 i=0;i<t.length;++i){if(i!==0)this.#e.push(",");this.begin(),r(this,t[i]),this.end()}this.#e.push("]")}}function Zf(e,t){let r=[],i=new N5(r);return i.begin(),t(i,e),i.end(),r.join("")}var $a=0,Mf=1,Ff=2,D5=5;class L5{#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 B5{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new je(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(Ff);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return ds(this.bytes(),e)}int32(){return this.#r($a),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r($a),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(Mf),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===$a)this.#e.skipVarint();else if(this.#t===Mf)this.#e.skip(8);else if(this.#t===Ff){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===D5)this.#e.skip(4);else throw new je(`Unexpected wire type ${this.#t}`);this.#t=-1}}function ds(e,t){let r=new L5(e),i=new B5(r),n=t.default();while(!r.eof()){let o=r.varint(),s=o>>3,a=o&7;i.setup(a);let c=t[s];if(c!==void 0){let l=c(i,n);if(l!==void 0)n=l}i.maybeSkip()}return n}var _$=S(()=>{Pt()});class k${#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}#i(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),i=new Uint8Array(r),n=new DataView(r);i.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=i,this.#r=n}#o(e){this.#i(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.#i(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.#o(e<<3|t)}bytes(e,t){this.#s(e,Ff),this.#o(t.byteLength),this.#i(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 i=new k$;r(i,t),this.bytes(e,i.data())}int32(e,t){this.#s(e,$a),this.#o(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,$a),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,Mf),this.#i(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Hf(e,t){let r=new k$;return t(r,e),r.data()}var j5=()=>{};var E$=S(()=>{ql();_$();j5()});class fs{#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 xr("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var I$=S(()=>{Pt()});function rt(e,t){throw new xr(t)}var wn=S(()=>{Pt()});function Zl(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<bye||e>Sye)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 T$(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 bi("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new je("Received unrecognized type of Value");else throw rt(e,"Impossible type of Value")}var bye,Sye=9223372036854775807n;var A$=S(()=>{Pt();wn();bye=-9223372036854775808n});function Ca(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function fb(e,t){let r=Ca(e),i=e.rows.map((n)=>U5(r.columnNames,n,t));return{...r,rows:i}}function pb(e,t){let r=Ca(e),i;if(e.rows.length>0)i=U5(r.columnNames,e.rows[0],t);return{...r,row:i}}function mb(e,t){let r=Ca(e),i;if(e.rows.length>0&&r.columnNames.length>0)i=T$(e.rows[0][0],t);return{...r,value:i}}function U5(e,t,r){let i={};Object.defineProperty(i,"length",{value:t.length});for(let n=0;n<t.length;++n){let o=T$(t[n],r);Object.defineProperty(i,n,{value:o});let s=e[n];if(s!==void 0&&!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function Xi(e){return new jf(e.message,e)}var Kf=S(()=>{Pt();A$()});class Ra{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new bi("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new Ot("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new st("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 Jf(e,t){if(t instanceof Ra)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var Ml=S(()=>{Pt()});class ps{#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 Vf{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(Zl(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]=Zl(t),this}bindName(e,t){return this._namedArgs.set(e,Zl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function hb(e,t,r){let i,n=[],o=[];if(t instanceof Vf){i=t.sql,n=t._args;for(let[c,l]of t._namedArgs.entries())o.push({name:c,value:l})}else if(Array.isArray(t))if(i=t[0],Array.isArray(t[1]))n=t[1].map((c)=>Zl(c));else o=Object.entries(t[1]).map(([c,l])=>({name:c,value:Zl(l)}));else i=t;let{sql:s,sqlId:a}=Jf(e,i);return{sql:s,sqlId:a,args:n,namedArgs:o,wantRows:r}}var gb=S(()=>{Ml();A$()});class yb{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new $$(this)}execute(){if(this.#t)throw new bi("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return wye(this._stream,this._steps,e);else return xye(this._stream,this._steps,e)}}function xye(e,t,r){return e._batch(r).then((i)=>{for(let n=0;n<t.length;++n){let o=i.stepResults.get(n),s=i.stepErrors.get(n);t[n].callback(o,s)}})}async function wye(e,t,r){let i=await e._openCursor(r);try{let n=0,o=void 0,s=[];for(;;){let a=await i.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new je("Server produced StepBeginEntry for unexpected step");else if(o!==void 0)throw new je("Server produced StepBeginEntry before terminating previous step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0);n=a.step+1,o=a,s=[]}else if(a.type==="step_end"){if(o===void 0)throw new je("Server produced StepEndEntry but no step is active");let c={cols:o.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[o.step].callback(c,void 0),o=void 0,s=[]}else if(a.type==="step_error"){if(o===void 0){if(a.step>=t.length)throw new je("Server produced StepErrorEntry for unexpected step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0)}else{if(a.step!==o.step)throw new je("Server produced StepErrorEntry for unexpected step");o=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(o===void 0)throw new je("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Xi(a.error);else if(a.type==="none")throw new je("Server produced unrecognized CursorEntry");else throw rt(a,"Impossible CursorEntry")}if(o!==void 0)throw new je("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{i.close()}}class $${_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,fb)}queryRow(e){return this.#t(e,!0,pb)}queryValue(e){return this.#t(e,!0,mb)}run(e){return this.#t(e,!1,Ca)}#t(e,t,r){if(this._index!==void 0)throw new bi("This BatchStep has already been added to the batch");let i=hb(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 o={stmt:i,condition:n};return new Promise((s,a)=>{let c=(l,u)=>{if(l!==void 0&&u!==void 0)a(new je("Server returned both result and error"));else if(u!==void 0)a(Xi(u));else if(l!==void 0)s(r(l,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:o,callback:c})})}}class wt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new wt(e._batch,{type:"ok",step:q5(e)})}static error(e){return new wt(e._batch,{type:"error",step:q5(e)})}static not(e){return new wt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)Z5(e,r);return new wt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)Z5(e,r);return new wt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new wt(e,{type:"is_autocommit"})}}function q5(e){if(e._index===void 0)throw new bi("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function Z5(e,t){if(t._batch!==e)throw new bi("Cannot mix BatchCond objects for different Batch objects")}var C$=S(()=>{Pt();Kf();gb();wn()});function M5(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class Fl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,fb)}queryRow(e){return this.#e(e,!0,pb)}queryValue(e){return this.#e(e,!0,mb)}run(e){return this.#e(e,!1,Ca)}#e(e,t,r){let i=hb(this._sqlOwner(),e,t);return this._execute(i).then((n)=>r(n,this.intMode))}batch(e=!1){return new yb(this,e)}describe(e){let t=Jf(this._sqlOwner(),e);return this._describe(t).then(M5)}sequence(e){let t=Jf(this._sqlOwner(),e);return this._sequence(t)}intMode}var bb=S(()=>{C$();Kf();Ml();gb()});class Wf{}var vye=1000,_ye=10,R$;var F5=S(()=>{Pt();R$=class R$ extends Wf{#e;#t;#r;#n;#i;#o;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new ps,this.#i=new ps,this.#o=void 0,this.#a=!1}async next(){for(;;){if(this.#o!==void 0)throw new Ot("Cursor is closed",this.#o);while(!this.#a&&this.#i.length<_ye)this.#i.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#i.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:vye}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#o!==void 0)return;this.#o=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new st("Cursor was manually closed"))}get closed(){return this.#o!==void 0}}});var Gf;var O$=S(()=>{Pt();bb();F5();Gf=class Gf extends Fl{#e;#t;#r;#n;#i;#o;static open(e){let t=e._streamIdAlloc.alloc(),r=new Gf(e,t),i=()=>{return},n=(s)=>r.#l(s),o={type:"open_stream",streamId:t};return e._sendRequest(o,{responseCallback:i,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new ps,this.#n=void 0,this.#i=!1,this.#o=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 xr("Cursor not associated with the stream attempted to execute a request");return new Promise((r,i)=>{if(this.#o!==void 0)i(new Ot("Stream is closed",this.#o));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})})}_cursorClosed(e){if(e!==this.#n)throw new xr("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#o!==void 0)e.errorCallback(new Ot("Stream is closed",this.#o));else if(this.#i)e.errorCallback(new Ot("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.#i){this.#l(new st("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:i}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let i=this.#e._cursorIdAlloc.alloc(),n=new R$(this.#e,this,i),o={type:"open_cursor",streamId:this.#t,cursorId:i,batch:t},s=()=>{return},a=(c)=>n._setClosed(c);this.#e._sendRequest(o,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#o!==void 0)return;if(this.#o=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),i=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}close(){this.#l(new st("Stream was manually closed"))}closeGracefully(){this.#i=!0,this.#c()}get closed(){return this.#o!==void 0||this.#i}}});function Qf(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,H5),e.arrayObjects("named_args",t.namedArgs,kye),e.boolean("want_rows",t.wantRows)}function kye(e,t){e.string("name",t.name),e.object("value",t.value,H5)}function Hl(e,t){e.arrayObjects("steps",t.steps,Eye)}function Eye(e,t){if(t.condition!==void 0)e.object("condition",t.condition,P$);e.object("stmt",t.stmt,Qf)}function P$(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,P$);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,P$);else if(t.type==="is_autocommit");else throw rt(t,"Impossible type of BatchCond")}function H5(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",Pl.fromUint8Array(t));else if(t===void 0);else throw rt(t,"Impossible type of Value")}var z$=S(()=>{cb();wn()});function K5(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,Iye);else throw rt(t,"Impossible type of ClientMsg")}function Iye(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,Qf);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,Hl);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,Hl);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 rt(t,"Impossible type of Request")}var J5=S(()=>{z$();wn()});function Yf(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,W5);for(let r of t.namedArgs)e.message(4,r,Tye);e.bool(5,t.wantRows)}function Tye(e,t){e.string(1,t.name),e.message(2,t.value,W5)}function Kl(e,t){for(let r of t.steps)e.message(1,r,Aye)}function Aye(e,t){if(t.condition!==void 0)e.message(1,t.condition,N$);e.message(2,t.stmt,Yf)}function N$(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,N$);else if(t.type==="and")e.message(4,t.conds,V5);else if(t.type==="or")e.message(5,t.conds,V5);else if(t.type==="is_autocommit")e.message(6,void 0,G5);else throw rt(t,"Impossible type of BatchCond")}function V5(e,t){for(let r of t)e.message(1,r,N$)}function W5(e,t){if(t===null)e.message(1,void 0,G5);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 rt(t,"Impossible type of Value")}function G5(e,t){}var D$=S(()=>{wn()});function Q5(e,t){if(t.type==="hello")e.message(1,t,$ye);else if(t.type==="request")e.message(2,t,Cye);else throw rt(t,"Impossible type of ClientMsg")}function $ye(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Cye(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Rye);else if(r.type==="close_stream")e.message(3,r,Oye);else if(r.type==="execute")e.message(4,r,Pye);else if(r.type==="batch")e.message(5,r,zye);else if(r.type==="open_cursor")e.message(6,r,Nye);else if(r.type==="close_cursor")e.message(7,r,Dye);else if(r.type==="fetch_cursor")e.message(8,r,Lye);else if(r.type==="sequence")e.message(9,r,Bye);else if(r.type==="describe")e.message(10,r,jye);else if(r.type==="store_sql")e.message(11,r,Uye);else if(r.type==="close_sql")e.message(12,r,qye);else if(r.type==="get_autocommit")e.message(13,r,Zye);else throw rt(r,"Impossible type of Request")}function Rye(e,t){e.int32(1,t.streamId)}function Oye(e,t){e.int32(1,t.streamId)}function Pye(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Yf)}function zye(e,t){e.int32(1,t.streamId),e.message(2,t.batch,Kl)}function Nye(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,Kl)}function Dye(e,t){e.int32(1,t.cursorId)}function Lye(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Bye(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 jye(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 Uye(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function qye(e,t){e.int32(1,t.sqlId)}function Zye(e,t){e.int32(1,t.streamId)}var Y5=S(()=>{D$();wn()});function ms(e){let t=Fr(e.message),r=sn(e.code);return{message:t,code:r}}function Xf(e){let t=qn(e.cols,X5),r=qf(e.rows).map((s)=>qn(s,e8)),i=Yi(e.affected_row_count),n=sn(e.last_insert_rowid),o=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:i,lastInsertRowid:o}}function X5(e){let t=sn(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function Sb(e){let t=new Map;qf(e.step_results).forEach((i,n)=>{if(i!==null)t.set(n,Xf(Lt(i)))});let r=new Map;return qf(e.step_errors).forEach((i,n)=>{if(i!==null)r.set(n,ms(Lt(i)))}),{stepResults:t,stepErrors:r}}function xb(e){let t=Fr(e.type);if(t==="step_begin"){let r=Yi(e.step),i=qn(e.cols,X5);return{type:"step_begin",step:r,cols:i}}else if(t==="step_end"){let r=Yi(e.affected_row_count),i=sn(e.last_insert_rowid),n=i!==void 0?BigInt(i):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Yi(e.step),i=ms(Lt(e.error));return{type:"step_error",step:r,error:i}}else if(t==="row")return{type:"row",row:qn(e.row,e8)};else if(t==="error")return{type:"error",error:ms(Lt(e.error))};else throw new je("Unexpected type of CursorEntry")}function wb(e){let t=qn(e.params,Mye),r=qn(e.cols,Fye),i=us(e.is_explain),n=us(e.is_readonly);return{params:t,cols:r,isExplain:i,isReadonly:n}}function Mye(e){return{name:sn(e.name)}}function Fye(e){let t=Fr(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function e8(e){let t=Fr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Fr(e.value);return BigInt(r)}else if(t==="float")return Yi(e.value);else if(t==="text")return Fr(e.value);else if(t==="blob")return Pl.toUint8Array(Fr(e.base64));else throw new je("Unexpected type of Value")}var vb=S(()=>{cb();Pt();ql()});function t8(e){let t=Fr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:ms(Lt(e.error))};else if(t==="response_ok"){let r=Yi(e.request_id),i=Hye(Lt(e.response));return{type:"response_ok",requestId:r,response:i}}else if(t==="response_error"){let r=Yi(e.request_id),i=ms(Lt(e.error));return{type:"response_error",requestId:r,error:i}}else throw new je("Unexpected type of ServerMsg")}function Hye(e){let t=Fr(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:Xf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:Sb(Lt(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=qn(e.entries,xb),i=us(e.done);return{type:"fetch_cursor",entries:r,done:i}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:wb(Lt(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:us(e.is_autocommit)};else throw new je("Unexpected type of Response")}var r8=S(()=>{Pt();ql();vb()});var vn,hs,n8,i8,Jl,Kye,Jye,_b,Vye,Wye,Gye,Vl,Qye,Yye,Xye;var kb=S(()=>{vn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},hs={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(n8))},2(e,t){t.rows.push(e.message(i8))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},n8={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},i8={default(){return[]},1(e,t){t.push(e.message(Xye))}},Jl={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,i]=e.message(Kye);t.stepResults.set(r,i)},2(e,t){let[r,i]=e.message(Jye);t.stepErrors.set(r,i)}},Kye={default(){return[0,hs.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(hs)}},Jye={default(){return[0,vn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(vn)}},_b={default(){return{type:"none"}},1(e){return e.message(Vye)},2(e){return e.message(Wye)},3(e){return e.message(Gye)},4(e){return{type:"row",row:e.message(i8)}},5(e){return{type:"error",error:e.message(vn)}}},Vye={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(n8))}},Wye={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Gye={default(){return{type:"step_error",step:0,error:vn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(vn)}},Vl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Qye))},2(e,t){t.cols.push(e.message(Yye))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Qye={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Yye={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},Xye={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 o8,ebe,tbe,rbe,nbe,ibe,obe,sbe,abe;var s8=S(()=>{kb();o8={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(ebe)},3(e){return e.message(rbe)},4(e){return e.message(tbe)}},ebe={default(){return{type:"hello_error",error:vn.default()}},1(e,t){t.error=e.message(vn)}},tbe={default(){return{type:"response_error",requestId:0,error:vn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(vn)}},rbe={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(nbe)},5(e,t){t.response=e.message(ibe)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(obe)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(sbe)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(abe)}},nbe={default(){return{type:"execute",result:hs.default()}},1(e,t){t.result=e.message(hs)}},ibe={default(){return{type:"batch",result:Jl.default()}},1(e,t){t.result=e.message(Jl)}},obe={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(_b))},2(e,t){t.done=e.bool()}},sbe={default(){return{type:"describe",result:Vl.default()}},1(e,t){t.result=e.message(Vl)}},abe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var a8,L$,Eb;var Ib=S(()=>{E$();Pt();I$();Kf();Ml();wn();O$();J5();Y5();r8();s8();a8=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),L$=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Eb=class Eb extends Bl{#e;#t;#r;#n;#i;#o;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#i=!1,this.#o=void 0,this.#a=!1,this.#s=new Map,this.#c=new fs,this._streamIdAlloc=new fs,this._cursorIdAlloc=new fs,this.#l=new fs,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#f()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#p(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new xr("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})}}#f(){let e=this.#e.protocol;if(e===void 0){this.#u(new st("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.#o={version:1,encoding:"json"};else if(this.#o=L$.get(e),this.#o===void 0){this.#u(new je(`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.#o.encoding;if(t==="json"){let r=Zf(e,K5);this.#e.send(r)}else if(t==="protobuf"){let r=Hf(e,Q5);this.#e.send(r)}else throw rt(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.#o.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#o.version)})}_ensureVersion(e,t){if(this.#o===void 0||!this.#a)throw new Un(`${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.#o.version<e)throw new Un(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#o.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new Ot("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})}#p(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new jl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new jl(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.#o.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new je("Received non-text message from server with JSON encoding"));return}t=Aa(JSON.parse(e.data),t8)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new je("Received non-binary message from server with Protobuf encoding"));return}t=ds(new Uint8Array(e.data),o8)}else throw rt(r,"Impossible encoding");this.#h(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#h(e){if(e.type==="none")throw new je("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#i)throw new je("Received a duplicated hello response");if(this.#i=!0,e.type==="hello_error")throw Xi(e.error);return}else if(!this.#i)throw new je("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 je("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new je("Received unexpected type of response");r.responseCallback(e.response)}catch(i){throw r.errorCallback(i),i}}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 je("Received unexpected error response");this.#c.free(t),r.errorCallback(Xi(e.error))}else throw rt(e,"Impossible ServerMsg type")}openStream(){return Gf.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new Ra(this,t),i=()=>{return},n=(s)=>r._setClosed(s),o={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(o,{responseCallback:i,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),i={type:"close_sql",sqlId:e};this._sendRequest(i,{responseCallback:t,errorCallback:r})}close(){this.#u(new st("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var Oa;var c8=S(()=>{if(typeof queueMicrotask<"u")Oa=queueMicrotask;else{let e=Promise.resolve();Oa=(t)=>{e.then(t)}}});class B${#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 i=new Uint8Array(new ArrayBuffer(r));i.set(this.#e.slice(this.#t,this.#r),0),this.#e=i}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function l8(e){let t=sn(e.baton),r=sn(e.base_url),i=qn(e.results,cbe);return{baton:t,baseUrl:r,results:i}}function cbe(e){let t=Fr(e.type);if(t==="ok")return{type:"ok",response:lbe(Lt(e.response))};else if(t==="error")return{type:"error",error:ms(Lt(e.error))};else throw new je("Unexpected type of StreamResult")}function lbe(e){let t=Fr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Xf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:Sb(Lt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:wb(Lt(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:us(e.is_autocommit)};else throw new je("Unexpected type of StreamResponse")}function u8(e){let t=sn(e.baton),r=sn(e.base_url);return{baton:t,baseUrl:r}}var j$=S(()=>{Pt();ql();vb()});var d8,ube,dbe,fbe,pbe,mbe,hbe,f8;var U$=S(()=>{kb();d8={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(ube))}},ube={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(dbe)}},2(e){return{type:"error",error:e.message(vn)}}},dbe={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(fbe)},3(e){return e.message(pbe)},4(e){return{type:"sequence"}},5(e){return e.message(mbe)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(hbe)}},fbe={default(){return{type:"execute",result:hs.default()}},1(e,t){t.result=e.message(hs)}},pbe={default(){return{type:"batch",result:Jl.default()}},1(e,t){t.result=e.message(Jl)}},mbe={default(){return{type:"describe",result:Vl.default()}},1(e,t){t.result=e.message(Vl)}},hbe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},f8={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var q$;var p8=S(()=>{ql();_$();Pt();wn();j$();U$();vb();kb();q$=class q$ extends Wf{#e;#t;#r;#n;#i;#o;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new B$(16384),this.#i=void 0,this.#o=!1}async open(e){if(e.body===null)throw new je("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(u8,f8);if(t===void 0)throw new je("Empty response to cursor request");return t}next(){return this.#a(xb,_b)}close(){this._setClosed(new st("Cursor was manually closed"))}_setClosed(e){if(this.#i!==void 0)return;if(this.#i=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#i!==void 0}async#a(e,t){for(;;){if(this.#o)return;else if(this.#i!==void 0)throw new Ot("Cursor is closed",this.#i);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let o=new TextDecoder().decode(n),s=JSON.parse(o);return Aa(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return ds(n,t)}else throw rt(this.#t,"Impossible encoding");if(this.#r===void 0)throw new xr("Attempted to read from HTTP cursor before it was opened");let{value:r,done:i}=await this.#r.next();if(i&&this.#n.length===0)this.#o=!0;else if(i)throw new je("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 i=e.slice(0,r);return this.#n.shift(r+1),i}#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 i=e.slice(r,r+t);return this.#n.shift(r+t),i}}});function m8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,gbe)}function gbe(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Qf);else if(t.type==="batch")e.object("batch",t.batch,Hl);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 rt(t,"Impossible type of StreamRequest")}function h8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,Hl)}var Z$=S(()=>{z$();wn()});function g8(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,ybe)}function ybe(e,t){if(t.type==="close")e.message(1,t,bbe);else if(t.type==="execute")e.message(2,t,Sbe);else if(t.type==="batch")e.message(3,t,xbe);else if(t.type==="sequence")e.message(4,t,wbe);else if(t.type==="describe")e.message(5,t,vbe);else if(t.type==="store_sql")e.message(6,t,_be);else if(t.type==="close_sql")e.message(7,t,kbe);else if(t.type==="get_autocommit")e.message(8,t,Ebe);else throw rt(t,"Impossible type of StreamRequest")}function bbe(e,t){}function Sbe(e,t){e.message(1,t.stmt,Yf)}function xbe(e,t){e.message(1,t.batch,Kl)}function wbe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function vbe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function _be(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function kbe(e,t){e.int32(1,t.sqlId)}function Ebe(e,t){}function y8(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,Kl)}var M$=S(()=>{D$();wn()});function Ibe(e,t){if(t.results.length!==e.length)throw new je("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let i=t.results[r],n=e[r];if(i.type==="ok"){if(i.response.type!==n.request.type)throw new je("Received unexpected type of response");n.responseCallback(i.response)}else if(i.type==="error")n.errorCallback(Xi(i.error));else if(i.type==="none")throw new je("Received unrecognized type of StreamResult");else throw rt(i,"Received impossible type of StreamResult")}}async function Tbe(e,t){if(t==="json"){let r=await e.json();return Aa(r,l8)}if(t==="protobuf"){let r=await e.arrayBuffer();return ds(new Uint8Array(r),d8)}throw await e.body?.cancel(),rt(t,"Impossible encoding")}async function Abe(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let i=await e.json();if("message"in i)return Xi(i);return new Ta(r,e.status)}if(t==="text/plain"){let i=(await e.text()).trim();if(i!=="")r+=`: ${i}`;return new Ta(r,e.status)}return await e.body?.cancel(),new Ta(r,e.status)}var Tb;var F$=S(()=>{Pt();E$();I$();c8();Kf();Ml();bb();wn();p8();Z$();M$();Z$();M$();j$();U$();Tb=class Tb extends Fl{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;#f;#m;constructor(e,t,r,i,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=i,this.#i=n,this.#o=void 0,this.#a=new ps,this.#s=!1,this.#l=!1,this.#d=!1,this.#f=void 0,this.#m=new fs}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#p({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new Ra(this,t)}_closeSql(e){if(this.#f!==void 0)return;this.#p({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#p({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#p({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#p({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#p({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#p({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#p(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 xr("Cursor was closed, but it was not associated with the stream");this.#c=void 0,Oa(()=>this.#u())}close(){this._setClosed(new st("Stream was manually closed"))}closeGracefully(){this.#l=!0,Oa(()=>this.#u())}get closed(){return this.#f!==void 0||this.#l}_setClosed(e){if(this.#f!==void 0)return;if(this.#f=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.#o!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,Oa(()=>this.#u())}#g(e){if(this.#f!==void 0)throw new Ot("Stream is closed",this.#f);else if(this.#l)throw new Ot("Stream is closing",void 0);else this.#a.push(e),Oa(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new st("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 i=this.#a.first();if(i!==void 0&&i.type==="pipeline")r.push(i),this.#a.shift();else if(i===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.#h(e,t);else throw rt(t,"Impossible type of QueueEntry")}#y(e,t){this.#b(()=>this.#S(t,e),(r)=>Tbe(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Ibe(t,r),(r)=>t.forEach((i)=>i.errorCallback(r)))}#h(e,t){let r=new q$(this,e.encoding);this.#c=r,this.#b(()=>this.#w(t,e),(i)=>r.open(i),(i)=>i.baton,(i)=>i.baseUrl,(i)=>t.cursorCallback(r),(i)=>t.errorCallback(i))}#b(e,t,r,i,n,o){let s;try{let a=e(),c=this.#n;s=c(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Abe(a).then((c)=>{throw c});return t(a)}).then((a)=>{this.#o=r(a),this.#t=i(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),o(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#x(new URL(t.pipelinePath,this.#t),{baton:this.#o,requests:e.map((r)=>r.request)},t.encoding,m8,g8)}#w(e,t){if(t.cursorPath===void 0)throw new Un(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#x(new URL(t.cursorPath,this.#t),{baton:this.#o,batch:e.batch},t.encoding,h8,y8)}#x(e,t,r,i,n){let o,s;if(r==="json")o=Zf(t,i),s="application/json";else if(r==="protobuf")o=Hf(t,n),s="application/x-protobuf";else throw rt(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.#i!==void 0)a.set("x-turso-encryption-key",this.#i);return new Request(e.toString(),{method:"POST",headers:a,body:o})}}});async function Cbe(e,t){let r=e;for(let i of $be){let n=new URL(i.versionPath,t),o=new Request(n.toString(),{method:"GET"}),s=await r(o);if(await s.arrayBuffer(),s.ok)return i}return H$}var $be,H$,Ab;var K$=S(()=>{Pt();F$();$be=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],H$={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};Ab=class Ab extends Bl{#e;#t;#r;#n;#i;#o;_endpointPromise;_endpoint;constructor(e,t,r,i,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=i,this.#i=void 0,this.#o=new Set,n==3)this._endpointPromise=Cbe(this.#r,this.#e),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o));else this._endpointPromise=Promise.resolve(H$),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=H$.version)return;else if(this._endpoint===void 0)throw new Un(`${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 Un(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#i!==void 0)throw new Ot("Client is closed",this.#i);let e=new Tb(this,this.#e,this.#t,this.#r,this.#n);return this.#o.add(e),e}_streamClosed(e){this.#o.delete(e)}close(){this.#a(new st("Client was manually closed"))}get closed(){return this.#i!==void 0}#a(e){if(this.#i!==void 0)return;this.#i=e;for(let t of Array.from(this.#o))t._setClosed(new Ot("Client was closed",e))}}});var b8=S(()=>{Pt()});function J$(e,t,r=2){if(typeof ls>"u")throw new Uf("WebSockets are not supported in this environment");var i=void 0;if(r==3)i=Array.from(L$.keys());else i=Array.from(a8.keys());let n=new ls(e,i);return new Eb(n,t)}function V$(e,t,r,i,n=2){return new Ab(e instanceof URL?e:new URL(e),t,r,i,n)}var $b=S(()=>{v$();Ib();Pt();K$();Ib();v$();C$();b8();Ml();gb();bb();K$();F$();Ib();O$();Pt()});class ep{#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 Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(eo),i;if(this.#r===void 0){this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=o.step(),a=s.run(as(this.#e)),c=s;i=r.map((l)=>{let u=o.step().condition(wt.ok(c));if(this.#t>=3)u.condition(wt.not(wt.isAutocommit(o)));let f=u.query(l);return f.catch(()=>{return}),c=u,f}),this.#r=o.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(l){throw this.close(),l}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=void 0;i=r.map((a)=>{let c=o.step();if(s!==void 0)c.condition(wt.ok(s));if(this.#t>=3)c.condition(wt.not(wt.isAutocommit(o)));let l=c.query(a);return l.catch(()=>{return}),s=c,l}),await o.execute()}let n=[];for(let o=0;o<i.length;o++)try{let s=await i[o];if(s===void 0)throw new cr("Statement in a transaction was not executed, probably because the transaction has been rolled back",o,"TRANSACTION_CLOSED");n.push(Gl(s))}catch(s){if(s instanceof cr)throw s;let a=yt(s);if(a instanceof Be)throw new cr(a.message,o,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw yt(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(as(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 yt(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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Be("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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}}async function Wl(e,t,r,i,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let o=r.step(),s=o.run(as(e)),a=o,c=i.map((m)=>{let y=r.step().condition(wt.ok(a));if(t>=3)y.condition(wt.not(wt.isAutocommit(r)));let g=y.query(m);return a=y,g}),l=r.step().condition(wt.ok(a));if(t>=3)l.condition(wt.not(wt.isAutocommit(r)));let u=l.run("COMMIT");if(r.step().condition(wt.not(wt.ok(l))).run("ROLLBACK").catch((m)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let p=[];await s;for(let m=0;m<c.length;m++)try{let y=await c[m];if(y===void 0)throw new cr("Statement in a batch was not executed, probably because the transaction has been rolled back",m,"TRANSACTION_CLOSED");p.push(Gl(y))}catch(y){if(y instanceof cr)throw y;let g=yt(y);if(g instanceof Be)throw new cr(g.message,m,g.code,g.extendedCode,g.rawCode,g.cause instanceof Error?g.cause:void 0);throw g}return await u,p}function eo(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 i=new Vf(t);if(r)if(Array.isArray(r))i.bindIndexes(r);else for(let[n,o]of Object.entries(r))i.bindName(n,o);return i}function Gl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),i=e.rows,n=e.affectedRowCount,o=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new zl(t,r,i,n,o)}function yt(e){if(e instanceof st){let t=S8(e);return new Be(e.message,t,void 0,void 0,e)}return e}function S8(e){if(e instanceof jf&&e.code!==void 0)return e.code;else if(e instanceof je)return"HRANA_PROTO_ERROR";else if(e instanceof Ot)return e.cause instanceof st?S8(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof jl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof Ta)return"SERVER_ERROR";else if(e instanceof Un)return"PROTOCOL_VERSION_ERROR";else if(e instanceof xr)return"INTERNAL_ERROR";else return"UNKNOWN"}var G$=S(()=>{$b();jn();Nl()});class Ql{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new x8,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 i=r.sql;if(i.length>=5000)continue;let n=this.#t.get(i);if(n===void 0){while(this.#t.size+1>this.capacity){let[o,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(o)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(i),this.#t.set(i,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class x8{#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 Q$=Se(function(j3e,v8){function Rbe(e){var t=0,r=[];function i(){if(t--,t<e)n()}function n(){var c=r.shift();if(a.queue=r.length,c)s(c.fn).then(c.resolve).catch(c.reject)}function o(c){return new Promise(function(l,u){r.push({fn:c,resolve:l,reject:u}),a.queue=r.length})}function s(c){t++;try{return Promise.resolve(c()).then(function(l){return i(),l},function(l){throw i(),l})}catch(l){return i(),Promise.reject(l)}}var a=function(c){if(t>=e)return o(c);else return s(c)};return a}function Obe(e,t){var r=!1,i=this;return Promise.all(e.map(function(){var n=arguments;return i(function(){if(!r)return t.apply(void 0,n).catch(function(o){throw r=!0,o})})}))}function w8(e){return e.queue=0,e.map=Obe,e}v8.exports=function(e){if(e)return w8(Rbe(e));else return w8(function(t){return t()})}});function E8(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Be(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Be('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Be('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=zf(e.scheme,e.authority,e.path),r;try{r=J$(t,e.authToken)}catch(i){if(i instanceof Uf){let n=e.scheme==="wss"?"https":"http",o=zf(n,e.authority,e.path);throw new Be(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(o)}). For more information, please read ${hi}`,"WEBSOCKETS_NOT_SUPPORTED")}throw yt(i)}return new I8(r,t,e.authToken,e.intMode,e.concurrency)}class I8{#e;#t;#r;#n;#i;closed;protocol;#o;#a;constructor(e,t,r,i,n){this.#e=t,this.#t=r,this.#r=i,this.#n=this.#c(e),this.#i=void 0,this.closed=!1,this.protocol="ws",this.#a=k8.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 i=await this.#s();try{let n=eo(r);i.conn.sqlCache.apply([n]);let o=i.stream.query(n);i.stream.closeGracefully();let s=await o;return Gl(s)}catch(n){throw yt(n)}finally{this._closeStream(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(eo),o=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(o>=3);return await Wl(t,o,s,n)}catch(i){throw yt(i)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(eo),i=await t.conn.client.getVersion(),n=t.stream.batch(i>=3);return await Wl("deferred",i,n,r,!0)}catch(r){throw yt(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 T8(this,t,e,r)}catch(r){throw this._closeStream(t),yt(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 yt(r)}finally{this._closeStream(t)}})}sync(){throw new Be("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Pbe&&this.#i===void 0){let i=this.#c();this.#i=i,i.client.getVersion().then((n)=>{if(this.#n!==i){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=i,this.#i=void 0},(n)=>{this.#i=void 0})}if(this.#n.client.closed)try{if(this.#i!==void 0)this.#n=this.#i;else this.#n=this.#c()}catch(i){throw yt(i)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=_8}let i=r.client.openStream();i.intMode=this.#r;let n={conn:r,stream:i};return r.streamStates.add(n),n}catch(i){throw yt(i)}}#c(e){try{return e??=J$(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Ql(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw yt(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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=_8;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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}this.closed=!0}}var k8,Pbe=60000,_8=100,T8;var A8=S(()=>{$b();jn();Lf();G$();ob();Nl();k8=hu(Q$(),1);jn();T8=class T8 extends ep{#e;#t;constructor(e,t,r,i){super(r,i);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 C8(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Be(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Be('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Be('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=zf(e.scheme,e.authority,e.path);return new O8(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class O8{#e;protocol;#t;#r;#n;#i;#o;#a;#s;constructor(e,t,r,i,n,o){this.#t=e,this.#o=t,this.#r=r,this.#n=i,this.#i=n,this.#a=o,this.#e=V$(this.#t,this.#o,this.#n,o),this.#e.intMode=this.#r,this.protocol="http",this.#s=$8.default(this.#i)}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 i=eo(r),n,o=this.#e.openStream();try{n=o.query(i)}finally{o.closeGracefully()}let s=await n;return Gl(s)}catch(i){throw yt(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let i=e.map((c)=>{if(Array.isArray(c))return{sql:c[0],args:c[1]||[]};return c}).map(eo),n=await this.#e.getVersion(),o,s=this.#e.openStream();try{new Ql(s,R8).apply(i);let l=s.batch(!1);o=Wl(t,n,l,i)}finally{s.closeGracefully()}return await o}catch(r){throw yt(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(eo),r=await this.#e.getVersion(),i,n=this.#e.openStream();try{let s=n.batch(!1);i=Wl("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await i}catch(t){throw yt(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new P8(this.#e.openStream(),e,t)}catch(t){throw yt(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 yt(t)}})}sync(){throw new Be("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=V$(this.#t,this.#o,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var $8,R8=30,P8;var z8=S(()=>{$b();jn();Lf();G$();ob();Nl();$8=hu(Q$(),1);jn();P8=class P8 extends ep{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Ql(e,R8)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Yl(e){return zbe(Df(e,!0))}function zbe(e){if(e.scheme==="wss"||e.scheme==="ws")return E8(e);else if(e.scheme==="https"||e.scheme==="http")return C8(e);else return $5(e)}var Y$=S(()=>{Lf();z5();A8();z8();jn()});function ae(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,J))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(J in r&&r[J]===t[J])return!0;r=Object.getPrototypeOf(r)}return!1}var J;var ze=S(()=>{J=Symbol.for("drizzle:entityKind")});var nt;var Zn=S(()=>{ze();nt=class nt{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[J]="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 tp;var Cb=S(()=>{ze();tp=class tp{static[J]="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 wr;var Xl=S(()=>{wr=Symbol.for("drizzle:Name")});var X$,N8;var D8=S(()=>{ze();Xl();X$=class X${static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 N8(e,this)}};N8=class N8{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function Rb(e,...t){return e(...t)}var eC=()=>{};function tC(e,t){return`${e[wr]}_${t.join("_")}_unique`}var L8,Nbe,B8;var j8=S(()=>{ze();Xl();L8=class L8{constructor(e,t){this.name=t,this.columns=e}static[J]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new B8(e,this.columns,this.nullsNotDistinctConfig,this.name)}};Nbe=class Nbe{static[J]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new L8(e,this.name)}};B8=class B8{constructor(e,t,r,i){this.table=e,this.columns=t,this.name=i??tC(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[J]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function U8(e,t,r){for(let i=t;i<e.length;i++){let n=e[i];if(n==="\\"){i++;continue}if(n==='"')return[e.slice(t,i).replace(/\\/g,""),i+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,i).replace(/\\/g,""),i]}return[e.slice(t).replace(/\\/g,""),e.length]}function q8(e,t=0){let r=[],i=t,n=!1;while(i<e.length){let o=e[i];if(o===","){if(n||i===t)r.push("");n=!0,i++;continue}if(n=!1,o==="\\"){i+=2;continue}if(o==='"'){let[c,l]=U8(e,i+1,!0);r.push(c),i=l;continue}if(o==="}")return[r,i+1];if(o==="{"){let[c,l]=q8(e,i+1);r.push(c),i=l;continue}let[s,a]=U8(e,i,!1);r.push(s),i=a}return[r,i]}function Z8(e){let[t]=q8(e,1);return t}function rC(e){return`{${e.map((t)=>{if(Array.isArray(t))return rC(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var M8=()=>{};var rp,eu,F8,Dbe,H8,nC;var K8=S(()=>{Cb();Zn();ze();D8();eC();j8();M8();rp=class rp extends tp{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(e){return new H8(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:i})=>Rb((n,o)=>{let s=new X$(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)},r,i))}buildExtraConfigColumn(e){return new F8(e,this.config)}};eu=class eu extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=tC(e,[t.name]);super(e,t);this.table=e}static[J]="PgColumn"};F8=class F8 extends eu{static[J]="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}};Dbe=class Dbe{static[J]="IndexedColumn";constructor(e,t,r,i){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=i}name;keyAsName;type;indexConfig};H8=class H8 extends rp{static[J]="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 nC(e,this.config,t)}};nC=class nC extends eu{constructor(e,t,r,i){super(e,t);this.baseColumn=r,this.range=i,this.size=t.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=Z8(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((i)=>i===null?null:ae(this.baseColumn,nC)?this.baseColumn.mapToDriverValue(i,!0):this.baseColumn.mapToDriverValue(i));if(t)return r;return rC(r)}}});function W8(e){return!!e&&typeof e==="function"&&J8 in e&&e[J8]===!0}var Lbe,V8,J8,Bbe,G8;var Q8=S(()=>{ze();K8();Lbe=class Lbe extends rp{static[J]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new V8(e,this.config)}};V8=class V8 extends eu{static[J]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};J8=Symbol.for("drizzle:isPgEnum");Bbe=class Bbe extends rp{static[J]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new G8(e,this.config)}};G8=class G8 extends eu{static[J]="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 vt,np;var Mn=S(()=>{ze();vt=class vt{static[J]="Subquery";constructor(e,t,r,i=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:i,usedTables:n}}};np=class np extends vt{static[J]="WithSubquery"}});var Y8="0.45.2";var X8=()=>{};var iC,oC,eH;var tH=S(()=>{eC();X8();eH={startActiveSpan(e,t){if(!iC)return t();if(!oC)oC=iC.trace.getTracer("drizzle-orm",Y8);return Rb((r,i)=>i.startActiveSpan(e,(n)=>{try{return t(n)}catch(o){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{n.end()}}),iC,oC)}}});var _t;var to=S(()=>{_t=Symbol.for("drizzle:ViewBaseConfig")});function gs(e){return e[wr]}function Pa(e){return`${e[Ob]??"public"}.${e[wr]}`}var Ob,Pb,rH,sC,aC,ip,nH,jbe,we;var vr=S(()=>{ze();Xl();Ob=Symbol.for("drizzle:Schema"),Pb=Symbol.for("drizzle:Columns"),rH=Symbol.for("drizzle:ExtraConfigColumns"),sC=Symbol.for("drizzle:OriginalName"),aC=Symbol.for("drizzle:BaseName"),ip=Symbol.for("drizzle:IsAlias"),nH=Symbol.for("drizzle:ExtraConfigBuilder"),jbe=Symbol.for("drizzle:IsDrizzleTable");we=class we{static[J]="Table";static Symbol={Name:wr,Schema:Ob,OriginalName:sC,Columns:Pb,ExtraConfigColumns:rH,BaseName:aC,IsAlias:ip,ExtraConfigBuilder:nH};[wr];[sC];[Ob];[Pb];[rH];[aC];[ip]=!1;[jbe]=!0;[nH]=void 0;constructor(e,t,r){this[wr]=this[sC]=e,this[Ob]=t,this[aC]=r}}});function cC(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function qbe(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 iH(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function U(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Ft(e[0]));for(let[i,n]of t.entries())r.push(n,new Ft(e[i+1]));return new Te(r)}function op(e,t){return e.map((r)=>{if(ae(r,ys)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(ae(r,an)&&ae(r.value,ys)){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 Ube,Ft,Te,zb,oH,sH,G5e,an,ys,Zbe,_n;var ur=S(()=>{ze();Q8();Mn();tH();to();Zn();vr();Ube=class Ube{static[J]="FakePrimitiveParam"};Ft=class Ft{static[J]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Te([this])}};Te=class Te{constructor(e){this.queryChunks=e;for(let t of e)if(ae(t,we)){let r=t[we.Symbol.Schema];this.usedTables.push(r===void 0?t[we.Symbol.Name]:r+"."+t[we.Symbol.Name])}}static[J]="SQL";decoder=oH;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return eH.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:i,escapeName:n,escapeParam:o,prepareTyping:s,inlineParams:a,paramStartIndex:c}=r;return qbe(e.map((l)=>{if(ae(l,Ft))return{sql:l.value.join(""),params:[]};if(ae(l,zb))return{sql:n(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){let u=[new Ft("(")];for(let[f,p]of l.entries())if(u.push(p),f<l.length-1)u.push(new Ft(", "));return u.push(new Ft(")")),this.buildQueryFromSourceParams(u,r)}if(ae(l,Te))return this.buildQueryFromSourceParams(l.queryChunks,{...r,inlineParams:a||l.shouldInlineParams});if(ae(l,we)){let u=l[we.Symbol.Schema],f=l[we.Symbol.Name];return{sql:u===void 0||l[ip]?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,nt)){let u=i.getColumnCasing(l);if(t.invokeSource==="indexes")return{sql:n(u),params:[]};let f=l.table[we.Symbol.Schema];return{sql:l.table[ip]||f===void 0?n(l.table[we.Symbol.Name])+"."+n(u):n(f)+"."+n(l.table[we.Symbol.Name])+"."+n(u),params:[]}}if(ae(l,_n)){let u=l[_t].schema,f=l[_t].name;return{sql:u===void 0||l[_t].isAlias?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,an)){if(ae(l.value,ys))return{sql:o(c.value++,l),params:[l],typings:["none"]};let u=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(ae(u,Te))return this.buildQueryFromSourceParams([u],r);if(a)return{sql:this.mapInlineParam(u,r),params:[]};let f=["none"];if(s)f=[s(l.encoder)];return{sql:o(c.value++,u),params:[u],typings:f}}if(ae(l,ys))return{sql:o(c.value++,l),params:[l],typings:["none"]};if(ae(l,Te.Aliased)&&l.fieldAlias!==void 0)return{sql:n(l.fieldAlias),params:[]};if(ae(l,vt)){if(l._.isWith)return{sql:n(l._.alias),params:[]};return this.buildQueryFromSourceParams([new Ft("("),l._.sql,new Ft(") "),new zb(l._.alias)],r)}if(W8(l)){if(l.schema)return{sql:n(l.schema)+"."+n(l.enumName),params:[]};return{sql:n(l.enumName),params:[]}}if(cC(l)){if(l.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([l.getSQL()],r);return this.buildQueryFromSourceParams([new Ft("("),l.getSQL(),new Ft(")")],r)}if(a)return{sql:this.mapInlineParam(l,r),params:[]};return{sql:o(c.value++,l),params:[l],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 Te.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}};zb=class zb{constructor(e){this.value=e}static[J]="Name";brand;getSQL(){return new Te([this])}};oH={mapFromDriverValue:(e)=>e},sH={mapToDriverValue:(e)=>e},G5e={...oH,...sH};an=class an{constructor(e,t=sH){this.value=e,this.encoder=t}static[J]="Param";brand;getSQL(){return new Te([this])}};((e)=>{function t(){return new Te([])}e.empty=t;function r(c){return new Te(c)}e.fromList=r;function i(c){return new Te([new Ft(c)])}e.raw=i;function n(c,l){let u=[];for(let[f,p]of c.entries()){if(f>0&&l!==void 0)u.push(l);u.push(p)}return new Te(u)}e.join=n;function o(c){return new zb(c)}e.identifier=o;function s(c){return new ys(c)}e.placeholder=s;function a(c,l){return new an(c,l)}e.param=a})(U||(U={}));((e)=>{class t{constructor(r,i){this.sql=r,this.fieldAlias=i}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Te||(Te={}));ys=class ys{constructor(e){this.name=e}static[J]="Placeholder";getSQL(){return new Te([this])}};Zbe=Symbol.for("drizzle:IsDrizzleView");_n=class _n{static[J]="View";[_t];[Zbe]=!0;constructor({name:e,schema:t,selectedFields:r,query:i}){this[_t]={name:e,originalName:e,schema:t,selectedFields:r,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new Te([this])}};nt.prototype.getSQL=function(){return new Te([this])};we.prototype.getSQL=function(){return new Te([this])};vt.prototype.getSQL=function(){return new Te([this])}});function lC(e,t,r){let i={},n=e.reduce((o,{path:s,field:a},c)=>{let l;if(ae(a,nt))l=a;else if(ae(a,Te))l=a.decoder;else if(ae(a,vt))l=a._.sql.decoder;else l=a.sql.decoder;let u=o;for(let[f,p]of s.entries())if(f<s.length-1){if(!(p in u))u[p]={};u=u[p]}else{let m=t[c],y=u[p]=m===null?null:l.mapFromDriverValue(m);if(r&&ae(a,nt)&&s.length===2){let g=s[0];if(!(g in i))i[g]=y===null?gs(a.table):!1;else if(typeof i[g]==="string"&&i[g]!==gs(a.table))i[g]=!1}}return o},{});if(r&&Object.keys(i).length>0){for(let[o,s]of Object.entries(i))if(typeof s==="string"&&!r[s])n[o]=null}return n}function kn(e,t){return Object.entries(e).reduce((r,[i,n])=>{if(typeof i!=="string")return r;let o=t?[...t,i]:[i];if(ae(n,nt)||ae(n,Te)||ae(n,Te.Aliased)||ae(n,vt))r.push({path:o,field:n});else if(ae(n,we))r.push(...kn(n[we.Symbol.Columns],o));else r.push(...kn(n,o));return r},[])}function sp(e,t){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let[n,o]of r.entries())if(o!==i[n])return!1;return!0}function Nb(e,t){let r=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,n])=>{if(ae(n,Te)||ae(n,nt))return[i,n];else return[i,new an(n,e[we.Symbol.Columns][i])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function aH(e,t){for(let r of t)for(let i of Object.getOwnPropertyNames(r.prototype)){if(i==="constructor")continue;Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(r.prototype,i)||Object.create(null))}}function Db(e){return e[we.Symbol.Columns]}function ap(e){return ae(e,vt)?e._.alias:ae(e,_n)?e[_t].name:ae(e,Te)?void 0:e[we.Symbol.IsAlias]?e[we.Symbol.Name]:e[we.Symbol.BaseName]}function Si(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function cH(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 uC;var Dr=S(()=>{Zn();ze();ur();Mn();vr();to();uC=typeof TextDecoder>"u"?null:new TextDecoder});var lH,dC,fC;var Lb=S(()=>{ze();lH=class lH{static[J]="ConsoleLogWriter";write(e){console.log(e)}};dC=class dC{static[J]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new lH}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),i=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${i}`)}};fC=class fC{static[J]="NoopLogger";logQuery(){}}});var uH,dH,pC;var fH=S(()=>{ze();vr();uH=Symbol.for("drizzle:PgInlineForeignKeys"),dH=Symbol.for("drizzle:EnableRLS");pC=class pC extends we{static[J]="PgTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:uH,EnableRLS:dH});[uH]=[];[dH]=!1;[we.Symbol.ExtraConfigBuilder]=void 0;[we.Symbol.ExtraConfigColumns]={}}});var mC,pH;var mH=S(()=>{ze();fH();mC=class mC{static[J]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new pH(e,this.columns,this.name)}};pH=class pH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[pC.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Hr(e,t){if(iH(t)&&!cC(e)&&!ae(e,an)&&!ae(e,ys)&&!ae(e,nt)&&!ae(e,we)&&!ae(e,_n))return new an(e,t);return e}function It(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" and ")),new Ft(")")])}function xi(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" or ")),new Ft(")")])}function gH(e){return U`not ${e}`}function bs(e,t){if(Array.isArray(t)){if(t.length===0)return U`false`;return U`${e} in ${t.map((r)=>Hr(r,e))}`}return U`${e} in ${Hr(t,e)}`}function Bb(e,t){if(Array.isArray(t)){if(t.length===0)return U`true`;return U`${e} not in ${t.map((r)=>Hr(r,e))}`}return U`${e} not in ${Hr(t,e)}`}function En(e){return U`${e} is null`}function SH(e){return U`${e} is not null`}function jb(e){return U`exists ${e}`}function lp(e){return U`not exists ${e}`}function xH(e,t,r){return U`${e} between ${Hr(t,e)} and ${Hr(r,e)}`}function wH(e,t,r){return U`${e} not between ${Hr(t,e)} and ${Hr(r,e)}`}function vH(e,t){return U`${e} like ${t}`}function _H(e,t){return U`${e} not like ${t}`}function kH(e,t){return U`${e} ilike ${t}`}function EH(e,t){return U`${e} not ilike ${t}`}var Qe=(e,t)=>U`${e} = ${Hr(t,e)}`,hH=(e,t)=>U`${e} <> ${Hr(t,e)}`,cp=(e,t)=>U`${e} > ${Hr(t,e)}`,yH=(e,t)=>U`${e} >= ${Hr(t,e)}`,bH=(e,t)=>U`${e} < ${Hr(t,e)}`,tu=(e,t)=>U`${e} <= ${Hr(t,e)}`;var IH=S(()=>{Zn();ze();vr();ur()});function ro(e){return U`${e} asc`}function za(e){return U`${e} desc`}var TH=S(()=>{ur()});var hC=S(()=>{IH();TH()});function $H(){return{and:It,between:xH,eq:Qe,exists:jb,gt:cp,gte:yH,ilike:kH,inArray:bs,isNull:En,isNotNull:SH,like:vH,lt:bH,lte:tu,ne:hH,not:gH,notBetween:wH,notExists:lp,notLike:_H,notIlike:EH,notInArray:Bb,or:xi,sql:U}}function CH(){return{sql:U,asc:ro,desc:za}}function RH(e,t){if(Object.keys(e).length===1&&"default"in e&&!ae(e.default,we))e=e.default;let r={},i={},n={};for(let[o,s]of Object.entries(e))if(ae(s,we)){let a=Pa(s),c=i[a];r[a]=o,n[o]={tsName:o,dbName:s[we.Symbol.Name],schema:s[we.Symbol.Schema],columns:s[we.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let u of Object.values(s[we.Symbol.Columns]))if(u.primary)n[o].primaryKey.push(u);let l=s[we.Symbol.ExtraConfigBuilder]?.(s[we.Symbol.ExtraConfigColumns]);if(l){for(let u of Object.values(l))if(ae(u,mC))n[o].primaryKey.push(...u.columns)}}else if(ae(s,AH)){let a=Pa(s.table),c=r[a],l=s.config(t(s.table)),u;for(let[f,p]of Object.entries(l))if(c){let m=n[c];if(m.relations[f]=p,u)m.primaryKey.push(...u)}else{if(!(a in i))i[a]={relations:{},primaryKey:u};i[a].relations[f]=p}}return{tables:n,tableNamesMap:r}}function Mbe(e){return function(r,i){return new Ss(e,r,i,i?.fields.reduce((n,o)=>n&&o.notNull,!0)??!1)}}function Fbe(e){return function(r,i){return new up(e,r,i)}}function OH(e,t,r){if(ae(r,Ss)&&r.config)return{fields:r.config.fields,references:r.config.references};let i=t[Pa(r.referencedTable)];if(!i)throw Error(`Table "${r.referencedTable[we.Symbol.Name]}" not found in schema`);let n=e[i];if(!n)throw Error(`Table "${i}" not found in schema`);let o=r.sourceTable,s=t[Pa(o)];if(!s)throw Error(`Table "${o[we.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(n.relations))if(r.relationName&&r!==c&&c.relationName===r.relationName||!r.relationName&&c.referencedTable===r.sourceTable)a.push(c);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${i}"`):Error(`There are multiple relations between "${i}" and "${r.sourceTable[we.Symbol.Name]}". Please specify relation name`);if(a[0]&&ae(a[0],Ss)&&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 PH(e){return{one:Mbe(e),many:Fbe(e)}}function Ub(e,t,r,i,n=(o)=>o){let o={};for(let[s,a]of i.entries())if(a.isJson){let c=t.relations[a.tsKey],l=r[s],u=typeof l==="string"?JSON.parse(l):l;o[a.tsKey]=ae(c,Ss)?u&&Ub(e,e[a.relationTableTsKey],u,a.selection,n):u.map((f)=>Ub(e,e[a.relationTableTsKey],f,a.selection,n))}else{let c=n(r[s]),l=a.field,u;if(ae(l,nt))u=l;else if(ae(l,Te))u=l.decoder;else u=l.sql.decoder;o[a.tsKey]=c===null?null:u.mapFromDriverValue(c)}return o}var gC,AH,Ss,up;var dp=S(()=>{vr();Zn();ze();mH();hC();ur();gC=class gC{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[we.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName};AH=class AH{constructor(e,t){this.table=e,this.config=t}static[J]="Relations"};Ss=class Ss extends gC{constructor(e,t,r,i){super(e,t,r?.relationName);this.config=r,this.isNullable=i}static[J]="One";withFieldName(e){let t=new Ss(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};up=class up extends gC{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[J]="Many";withFieldName(e){let t=new up(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function fp(e,t){return new Proxy(e,new Na(t,!1))}function wi(e,t){return new Proxy(e,new ru(new Proxy(e.table,new Na(t,!1))))}function yC(e,t){return new Te.Aliased(pp(e.sql,t),e.fieldAlias)}function pp(e,t){return U.join(e.queryChunks.map((r)=>{if(ae(r,nt))return wi(r,t);if(ae(r,Te))return pp(r,t);if(ae(r,Te.Aliased))return yC(r,t);return r}))}var ru,Na,Hbe;var mp=S(()=>{Zn();ze();ur();vr();to();ru=class ru{constructor(e){this.table=e}static[J]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Na=class Na{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[J]="TableAliasProxyHandler";get(e,t){if(t===we.Symbol.IsAlias)return!0;if(t===we.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===we.Symbol.OriginalName)return this.alias;if(t===_t)return{...e[_t],name:this.alias,isAlias:!0};if(t===we.Symbol.Columns){let i=e[we.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map((o)=>{n[o]=new Proxy(i[o],new ru(new Proxy(e,this)))}),n}let r=e[t];if(ae(r,nt))return new Proxy(r,new ru(new Proxy(e,this)));return r}};Hbe=class Hbe{constructor(e){this.alias=e}static[J]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return fp(e.sourceTable,this.alias);return e[t]}}});var bt;var Da=S(()=>{mp();Zn();ze();ur();Mn();to();bt=class bt{static[J]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===_t)return{...e[_t],selectedFields:new Proxy(e[_t].selectedFields,this)};if(typeof t==="symbol")return e[t];let i=(ae(e,vt)?e._.selectedFields:ae(e,_n)?e[_t].selectedFields:e)[t];if(ae(i,Te.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;let n=i.clone();return n.isSelectionField=!0,n}if(ae(i,Te)){if(this.config.sqlBehavior==="sql")return i;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(ae(i,nt)){if(this.config.alias)return new Proxy(i,new ru(new Proxy(i.table,new Na(this.config.alias,this.config.replaceOriginalName??!1))));return i}if(typeof i!=="object"||i===null)return i;return new Proxy(i,new bt(this.config))}}});var Lr;var no=S(()=>{ze();Lr=class Lr{static[J]="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 bC,zH;var SC=S(()=>{ze();Xl();bC=class bC{static[J]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 zH(e,this)}};zH=class zH{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function xC(e,t){return`${e[wr]}_${t.join("_")}_unique`}var NH,Kbe,DH;var wC=S(()=>{ze();Xl();NH=class NH{constructor(e,t){this.name=t,this.columns=e}static[J]="SQLiteUniqueConstraintBuilder";columns;build(e){return new DH(e,this.columns,this.name)}};Kbe=class Kbe{static[J]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new NH(e,this.name)}};DH=class DH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??xC(this.table,this.columns.map((i)=>i.name))}static[J]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Qt,Tt;var xs=S(()=>{Cb();Zn();ze();SC();wC();Qt=class Qt extends tp{static[J]="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:i})=>((n,o)=>{let s=new bC(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)})(r,i))}};Tt=class Tt extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=xC(e,[t.name]);super(e,t);this.table=e}static[J]="SQLiteColumn"}});function MH(e,t){let{name:r,config:i}=Si(e,t);if(i?.mode==="json")return new jH(r);if(i?.mode==="bigint")return new LH(r);return new qH(r)}var LH,BH,jH,UH,qH,ZH;var vC=S(()=>{ze();Dr();xs();LH=class LH extends Qt{static[J]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new BH(e,this.config)}};BH=class BH extends Tt{static[J]="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(uC.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};jH=class jH extends Qt{static[J]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new UH(e,this.config)}};UH=class UH extends Tt{static[J]="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(uC.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};qH=class qH extends Qt{static[J]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new ZH(e,this.config)}};ZH=class ZH extends Tt{static[J]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function KH(e){return(t,r)=>{let{name:i,config:n}=Si(t,r);return new FH(i,n,e)}}var FH,HH;var _C=S(()=>{ze();Dr();xs();FH=class FH extends Qt{static[J]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new HH(e,this.config)}};HH=class HH extends Tt{static[J]="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 _r(e,t){let{name:r,config:i}=Si(e,t);if(i?.mode==="timestamp"||i?.mode==="timestamp_ms")return new WH(r,i.mode);if(i?.mode==="boolean")return new QH(r,i.mode);return new JH(r)}var qb,Zb,JH,VH,WH,GH,QH,YH;var kC=S(()=>{ze();ur();Dr();xs();qb=class qb extends Qt{static[J]="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()}};Zb=class Zb extends Tt{static[J]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};JH=class JH extends qb{static[J]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new VH(e,this.config)}};VH=class VH extends Zb{static[J]="SQLiteInteger"};WH=class WH extends qb{static[J]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(U`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new GH(e,this.config)}};GH=class GH extends Zb{static[J]="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}};QH=class QH extends qb{static[J]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new YH(e,this.config)}};YH=class YH extends Zb{static[J]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function oK(e,t){let{name:r,config:i}=Si(e,t),n=i?.mode;return n==="number"?new tK(r):n==="bigint"?new nK(r):new XH(r)}var XH,eK,tK,rK,nK,iK;var EC=S(()=>{ze();Dr();xs();XH=class XH extends Qt{static[J]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new eK(e,this.config)}};eK=class eK extends Tt{static[J]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};tK=class tK extends Qt{static[J]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new rK(e,this.config)}};rK=class rK extends Tt{static[J]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};nK=class nK extends Qt{static[J]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new iK(e,this.config)}};iK=class iK extends Tt{static[J]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function cK(e){return new sK(e??"")}var sK,aK;var IC=S(()=>{ze();xs();sK=class sK extends Qt{static[J]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new aK(e,this.config)}};aK=class aK extends Tt{static[J]="SQLiteReal";getSQLType(){return"real"}}});function dr(e,t={}){let{name:r,config:i}=Si(e,t);if(i.mode==="json")return new dK(r);return new lK(r,i)}var lK,uK,dK,fK;var TC=S(()=>{ze();Dr();xs();lK=class lK extends Qt{static[J]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new uK(e,this.config)}};uK=class uK extends Tt{static[J]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};dK=class dK extends Qt{static[J]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new fK(e,this.config)}};fK=class fK extends Tt{static[J]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function pK(){return{blob:MH,customType:KH,integer:_r,numeric:oK,real:cK,text:dr}}var mK=S(()=>{vC();_C();kC();EC();IC();TC()});function Jbe(e,t,r,i,n=e){let o=new Bt(e,i,n),s=typeof t==="function"?t(pK()):t,a=Object.fromEntries(Object.entries(s).map(([l,u])=>{let f=u;f.setName(l);let p=f.build(o);return o[AC].push(...f.buildForeignKeys(p,o)),[l,p]})),c=Object.assign(o,a);if(c[we.Symbol.Columns]=a,c[we.Symbol.ExtraConfigColumns]=a,r)c[Bt.Symbol.ExtraConfigBuilder]=r;return c}var AC,Bt,hp=(e,t,r)=>Jbe(e,t,r);var io=S(()=>{ze();vr();mK();AC=Symbol.for("drizzle:SQLiteInlineForeignKeys");Bt=class Bt extends we{static[J]="SQLiteTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:AC});[we.Symbol.Columns];[AC]=[];[we.Symbol.ExtraConfigBuilder]=void 0}});var Vbe,hK;var gK=S(()=>{ze();Vbe=class Vbe{constructor(e,t){this.name=e,this.value=t}static[J]="SQLiteCheckBuilder";brand;build(e){return new hK(e,this)}};hK=class hK{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[J]="SQLiteCheck";name;value}});function La(e){return new yK(e,!1)}var yK,bK,SK;var xK=S(()=>{ze();yK=class yK{constructor(e,t){this.name=e,this.unique=t}static[J]="SQLiteIndexBuilderOn";on(...e){return new bK(this.name,e,this.unique)}};bK=class bK{static[J]="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 SK(this.config,e)}};SK=class SK{static[J]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var Wbe,wK;var vK=S(()=>{ze();io();Wbe=class Wbe{static[J]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new wK(e,this.columns,this.name)}};wK=class wK{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[Bt.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Fn(e){if(ae(e,Bt))return[`${e[we.Symbol.BaseName]}`];if(ae(e,vt))return e._.usedTables??[];if(ae(e,Te))return e.usedTables??[];return[]}var nu=S(()=>{ze();ur();Mn();vr();io()});var Mb;var _K=S(()=>{ze();no();Da();io();vr();Dr();nu();Mb=class Mb extends Lr{constructor(e,t,r,i){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:i}}static[J]="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[we.Symbol.Columns],new bt({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[Bt.Symbol.Columns]){return this.config.returning=kn(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:Fn(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 Gbe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function Qbe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,i,n)=>{let o=n===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return r+o},"")}function Ybe(e){return e}var $C;var kK=S(()=>{ze();vr();$C=class $C{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Gbe:e==="camelCase"?Qbe:Ybe}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[we.Symbol.Schema]??"public",r=e.table[we.Symbol.OriginalName],i=`${t}.${r}.${e.name}`;if(!this.cache[i])this.cacheTable(e.table);return this.cache[i]}cacheTable(e){let t=e[we.Symbol.Schema]??"public",r=e[we.Symbol.OriginalName],i=`${t}.${r}`;if(!this.cachedTables[i]){for(let n of Object.values(e[we.Symbol.Columns])){let o=`${i}.${n.name}`;this.cache[o]=this.convert(n.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var iu,oo,CC;var Fb=S(()=>{ze();iu=class iu extends Error{static[J]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};oo=class oo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
409
|
+
`)}catch{}}}formatJsonEntry(e,t,r){let i={ts:new Date().toISOString(),level:e,msg:t};if(this.context)i.ctx=this.context;if(r.length>0)i.data=r;return JSON.stringify(i)}silly(e,...t){if(this.level<=_a.SILLY)this.write(console.debug.bind(console),"silly",e,t)}verbose(e,...t){if(this.level<=_a.VERBOSE)this.write(console.debug.bind(console),"verbose",e,t)}debug(e,...t){if(this.level<=_a.DEBUG)this.write(console.debug.bind(console),"debug",e,t)}info(e,...t){if(this.level<=_a.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<=_a.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=_a.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new on({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var _a,uZe;var p$=S(()=>{_a={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};uZe=on.getInstance()});var m$,Vhe,Cl,mZe;var Of=S(()=>{ti();Ae();m$=d.enum(["file_operations","content_operations","data_processing","batch_processing"]),Vhe=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:m$,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:Ac.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:_o.optional()}),Cl=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:m$,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:Ac.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:_o.optional(),rootJobId:d.string()}),mZe=d.enum(["none","skip","replace","coalesce"])});var Whe,os=15000;var Pf=S(()=>{Of();Ae();Whe=d.object({id:d.string(),type:d.string(),data:d.string(),status:d.enum(["pending","processing","completed","failed"]),source:d.string().nullable(),priority:d.number(),retryCount:d.number(),maxRetries:d.number(),lastError:d.string().nullable(),createdAt:d.number(),scheduledFor:d.number(),startedAt:d.number().nullable(),completedAt:d.number().nullable(),attemptId:d.string().nullable(),workerSlotId:d.string().nullable(),workerSessionId:d.string().nullable(),leaseExpiresAt:d.number().nullable(),attemptHeartbeatAt:d.number().nullable(),runtimeUpdatedAt:d.number().nullable(),metadata:Cl,progress:d.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:d.unknown().nullable().optional()})});var h$,v3,Ze,Ghe,Qhe,_3,Yhe;var ss=S(()=>{Ae();Of();h$=d.enum(["pending","processing","completed","failed"]),v3=d.enum(["completed","failed"]),Ze={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Ghe=d.object({id:d.string(),type:d.string(),status:h$,data:d.unknown(),result:d.unknown().optional(),lastError:d.string().optional().nullable(),attempts:d.number(),maxRetries:d.number(),priority:d.number(),createdAt:d.date(),updatedAt:d.date(),processedAt:d.date().optional().nullable(),completedAt:d.date().optional().nullable(),failedAt:d.date().optional().nullable()}),Qhe=d.object({jobId:d.string(),type:d.string(),status:v3,result:d.unknown().optional(),error:d.string().optional()}),_3=d.object({success:d.literal(!1),error:d.string().optional()}),Yhe=d.object({id:d.string(),type:d.enum(["job","batch"]),status:h$,message:d.string().optional(),progress:d.object({current:d.number(),total:d.number(),percentage:d.number()}).optional(),aggregationKey:d.string().optional(),batchDetails:d.object({totalOperations:d.number(),completedOperations:d.number(),failedOperations:d.number(),currentOperation:d.string().optional(),errors:d.array(d.string()).optional()}).optional(),jobDetails:d.object({jobType:d.string(),priority:d.number(),retryCount:d.number()}).optional(),metadata:Cl})});var Be,cr;var jn=S(()=>{Be=class Be extends Error{code;extendedCode;rawCode;constructor(e,t,r,i,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=i,this.name="LibsqlError"}};cr=class cr extends Be{statementIndex;constructor(e,t,r,i,n,o){super(e,r,i,n,o);this.statementIndex=t,this.name="LibsqlBatchError"}}});function k3(e){let t=Xhe.exec(e);if(t===null)throw new Be(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,i=r.scheme,n=r.authority!==void 0?ege(r.authority):void 0,o=ka(r.path),s=r.query!==void 0?rge(r.query):void 0,a=r.fragment!==void 0?ka(r.fragment):void 0;return{scheme:i,authority:n,path:o,query:s,fragment:a}}function ege(e){let t=tge.exec(e);if(t===null)throw new Be("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,i=ka(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,o=r.username!==void 0?{username:ka(r.username),password:r.password!==void 0?ka(r.password):void 0}:void 0;return{host:i,port:n,userinfo:o}}function rge(e){let t=e.split("&"),r=[];for(let i of t){if(i==="")continue;let n,o,s=i.indexOf("=");if(s<0)n=i,o="";else n=i.substring(0,s),o=i.substring(s+1);r.push({key:ka(n.replaceAll("+"," ")),value:ka(o.replaceAll("+"," "))})}return{pairs:r}}function ka(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Be(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function zf(e,t,r){if(t===void 0)throw new Be(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let i=`${e}:`,n=nge(t.host),o=ige(t.port),a=`//${oge(t.userinfo)}${n}${o}`,c=r.split("/").map(encodeURIComponent).join("/");if(c!==""&&!c.startsWith("/"))c="/"+c;return new URL(`${i}${a}${c}`)}function nge(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function ige(e){return e!==void 0?`:${e}`:""}function oge(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var Xhe,tge;var ob=S(()=>{jn();Xhe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();tge=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var Ol,E3,I3,Nf,sb,sge,lr,T3,C3=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),R3=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),O3=(e)=>{let t,r,i,n,o="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(i=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|i<<8|n,o+=Nf[t>>18&63]+Nf[t>>12&63]+Nf[t>>6&63]+Nf[t&63]}return s?o.slice(0,s-3)+"===".substring(s):o},b$,g$,ab=(e,t=!1)=>t?C3(g$(e)):g$(e),age=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?lr(192|t>>>6)+lr(128|t&63):lr(224|t>>>12&15)+lr(128|t>>>6&63)+lr(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return lr(240|t>>>18&7)+lr(128|t>>>12&63)+lr(128|t>>>6&63)+lr(128|t&63)}},cge,P3=(e)=>e.replace(cge,age),A3,Rl=(e,t=!1)=>t?C3(A3(e)):A3(e),$3=(e)=>Rl(e,!0),lge,uge=(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 lr((r>>>10)+55296)+lr((r&1023)+56320);case 3:return lr((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return lr((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},z3=(e)=>e.replace(lge,uge),N3=(e)=>{if(e=e.replace(/\s+/g,""),!sge.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,i,n=[];for(let o=0;o<e.length;)if(t=sb[e.charAt(o++)]<<18|sb[e.charAt(o++)]<<12|(r=sb[e.charAt(o++)])<<6|(i=sb[e.charAt(o++)]),r===64)n.push(lr(t>>16&255));else if(i===64)n.push(lr(t>>16&255,t>>8&255));else n.push(lr(t>>16&255,t>>8&255,t&255));return n.join("")},S$,D3,L3=(e)=>D3(B3(e)),dge,B3=(e)=>R3(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),y$=(e)=>dge(B3(e)),fge=(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)},j3=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),U3=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,j3(r));e("fromBase64",function(){return y$(this)}),e("toBase64",function(t){return Rl(this,t)}),e("toBase64URI",function(){return Rl(this,!0)}),e("toBase64URL",function(){return Rl(this,!0)}),e("toUint8Array",function(){return L3(this)})},q3=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,j3(r));e("toBase64",function(t){return ab(this,t)}),e("toBase64URI",function(){return ab(this,!0)}),e("toBase64URL",function(){return ab(this,!0)})},pge=()=>{U3(),q3()},Pl;var cb=S(()=>{Ol=typeof Buffer==="function",E3=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,I3=typeof TextEncoder==="function"?new TextEncoder:void 0,Nf=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),sb=((e)=>{let t={};return e.forEach((r,i)=>t[r]=i),t})(Nf),sge=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,lr=String.fromCharCode.bind(String),T3=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),b$=typeof btoa==="function"?(e)=>btoa(e):Ol?(e)=>Buffer.from(e,"binary").toString("base64"):O3,g$=Ol?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let i=0,n=e.length;i<n;i+=4096)r.push(lr.apply(null,e.subarray(i,i+4096)));return b$(r.join(""))},cge=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,A3=Ol?(e)=>Buffer.from(e,"utf8").toString("base64"):I3?(e)=>g$(I3.encode(e)):(e)=>b$(P3(e)),lge=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,S$=typeof atob==="function"?(e)=>atob(R3(e)):Ol?(e)=>Buffer.from(e,"base64").toString("binary"):N3,D3=Ol?(e)=>T3(Buffer.from(e,"base64")):(e)=>T3(S$(e).split("").map((t)=>t.charCodeAt(0))),dge=Ol?(e)=>Buffer.from(e,"base64").toString("utf8"):E3?(e)=>E3.decode(D3(e)):(e)=>z3(S$(e)),Pl={version:"3.8.0",VERSION:"3.8.0",atob:S$,atobPolyfill:N3,btoa:b$,btoaPolyfill:O3,fromBase64:y$,toBase64:Rl,encode:Rl,encodeURI:$3,encodeURL:$3,utob:P3,btou:z3,decode:y$,isValid:fge,fromUint8Array:ab,toUint8Array:L3,extendString:U3,extendUint8Array:q3,extendBuiltins:pge}});function as(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 zl{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,i,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=i,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(mge),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function mge(e){return Array.prototype.map.call(e,hge)}function hge(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return Pl.fromUint8Array(new Uint8Array(e));else return e}var hi="https://github.com/libsql/libsql-client-ts#supported-urls";var Nl=S(()=>{cb()});function M3(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function Df(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:i,tls:n,intMode:o,concurrency:s}=e;s=Math.max(0,s||20),o??="number";let a=[];if(r===Z3)r="file::memory:";let c=k3(r),l=c.scheme.toLowerCase(),u=l==="file"&&c.path===Z3&&c.authority===void 0,f;if(u)f={cache:{values:["shared","private"],update:(g,b)=>a.push(`${g}=${b}`)}};else f={tls:{values:["0","1"],update:(g,b)=>n=b==="1"},authToken:{update:(g,b)=>i=b}};for(let{key:g,value:b}of c.query?.pairs??[]){if(!Object.hasOwn(f,g))throw new Be(`Unsupported URL query parameter ${JSON.stringify(g)}`,"URL_PARAM_NOT_SUPPORTED");let _=f[g];if(_.values!==void 0&&!_.values.includes(b))throw new Be(`Unknown value for the "${g}" query argument: ${JSON.stringify(b)}. Supported values are: [${_.values.map((T)=>'"'+T+'"').join(", ")}]`,"URL_INVALID");if(_.update!==void 0)_?.update(g,b)}let p=a.length===0?"":`?${a.join("&")}`,m=c.path+p,y;if(l==="libsql")if(n===!1){if(c.authority?.port===void 0)throw new Be('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");y=t?"http":"ws"}else y=t?"https":"wss";else y=l;if(y==="http"||y==="ws")n??=!1;else n??=!0;if(y!=="http"&&y!=="ws"&&y!=="https"&&y!=="wss"&&y!=="file")throw new Be(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(c.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(o!=="number"&&o!=="bigint"&&o!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(o)}`);if(c.fragment!==void 0)throw new Be(`URL fragments are not supported: ${JSON.stringify("#"+c.fragment)}`,"URL_INVALID");if(u)return{scheme:"file",tls:!1,path:m,intMode:o,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:y,tls:n,authority:c.authority,path:m,authToken:i,intMode:o,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 Z3=":memory:";var Lf=S(()=>{jn();ob();Nl()});var H3=Se(function(xn){var gge=xn&&xn.__createBinding||(Object.create?function(e,t,r,i){if(i===void 0)i=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,i,n)}:function(e,t,r,i){if(i===void 0)i=r;e[i]=t[r]}),yge=xn&&xn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),F3=xn&&xn.__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))gge(t,e,r)}return yge(t,e),t};Object.defineProperty(xn,"__esModule",{value:!0});xn.load=xn.currentTarget=void 0;var bge=F3(pr("path")),Sge=F3(pr("fs"));function xge(){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 wge()?`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}`)}xn.currentTarget=xge;function wge(){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 vge(e){let t=bge.join(e,"index.node");return Sge.existsSync(t)?pr(t):null}xn.load=vge});var V3=Se(function(zZe,J3){var K3=()=>process.platform==="linux",x$=null,_ge=()=>{if(!x$)x$=K3()&&process.report?process.report.getReport():{};return x$};J3.exports={isLinux:K3,getReport:_ge}});var Q3=Se(function(NZe,G3){var W3=pr("fs"),kge=(e)=>W3.readFileSync(e,"utf-8"),Ege=(e)=>new Promise((t,r)=>{W3.readFile(e,"utf-8",(i,n)=>{if(i)r(i);else t(n)})});G3.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:kge,readFile:Ege}});var m5=Se(function(DZe,p5){var X3=pr("child_process"),{isLinux:Dl,getReport:e5}=V3(),{LDD_PATH:lb,readFile:t5,readFileSync:r5}=Q3(),gi,yi,cs="",n5=()=>{if(!cs)return new Promise((e)=>{X3.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{cs=t?" ":r,e(cs)})});return cs},i5=()=>{if(!cs)try{cs=X3.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){cs=" "}return cs},Qi="glibc",o5=/GLIBC\s(\d+\.\d+)/,Ea="musl",Ige=Qi.toUpperCase(),Tge=Ea.toLowerCase(),Age=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),s5=()=>{let e=e5();if(e.header&&e.header.glibcVersionRuntime)return Qi;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Age))return Ea}return null},a5=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Qi))return Qi;if(r&&r.includes(Ea))return Ea;return null},c5=(e)=>{if(e.includes(Tge))return Ea;if(e.includes(Ige))return Qi;return null},$ge=async()=>{if(gi!==void 0)return gi;gi=null;try{let e=await t5(lb);gi=c5(e)}catch(e){}return gi},Cge=()=>{if(gi!==void 0)return gi;gi=null;try{let e=r5(lb);gi=c5(e)}catch(e){}return gi},l5=async()=>{let e=null;if(Dl()){if(e=await $ge(),!e)e=s5();if(!e){let t=await n5();e=a5(t)}}return e},u5=()=>{let e=null;if(Dl()){if(e=Cge(),!e)e=s5();if(!e){let t=i5();e=a5(t)}}return e},Rge=async()=>Dl()&&await l5()!==Qi,Oge=()=>Dl()&&u5()!==Qi,Pge=async()=>{if(yi!==void 0)return yi;yi=null;try{let t=(await t5(lb)).match(o5);if(t)yi=t[1]}catch(e){}return yi},zge=()=>{if(yi!==void 0)return yi;yi=null;try{let t=r5(lb).match(o5);if(t)yi=t[1]}catch(e){}return yi},d5=()=>{let e=e5();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},Y3=(e)=>e.trim().split(/\s+/)[1],f5=(e)=>{let[t,r,i]=e.split(/[\r\n]+/);if(t&&t.includes(Qi))return Y3(t);if(r&&i&&r.includes(Ea))return Y3(i);return null},Nge=async()=>{let e=null;if(Dl()){if(e=await Pge(),!e)e=d5();if(!e){let t=await n5();e=f5(t)}}return e},Dge=()=>{let e=null;if(Dl()){if(e=zge(),!e)e=d5();if(!e){let t=i5();e=f5(t)}}return e};p5.exports={GLIBC:Qi,MUSL:Ea,family:l5,familySync:u5,isNonGlibcLinux:Rge,isNonGlibcLinuxSync:Oge,version:Nge,versionSync:Dge}});var g5=Se(function(LZe,h5){var Lge={ALLOW:0,DENY:1};h5.exports=Lge});var b5=Se(function(BZe,y5){var w$={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function Ia(e,t,r){if(new.target!==Ia)return new Ia(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),w$.value=""+e,Object.defineProperty(this,"message",w$),Error.captureStackTrace(this,Ia),this.code=t,this.rawCode=r}Object.setPrototypeOf(Ia,Error);Object.setPrototypeOf(Ia.prototype,Error.prototype);Object.defineProperty(Ia.prototype,"name",w$);y5.exports=Ia});var I5=Se(function(jZe,ub){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Bge,currentTarget:jge}=H3(),{familySync:S5,GLIBC:Uge,MUSL:qge}=m5();function Zge(){if(process.env.LIBSQL_JS_DEV)return Bge(__dirname);let e=jge();if(S5()==Uge)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"&&S5()==qge)e="linux-arm-musleabihf";return pr(`@libsql/${e}`)}var{databaseOpen:Mge,databaseOpenWithSync:Fge,databaseInTransaction:Hge,databaseInterrupt:Kge,databaseClose:Jge,databaseSyncSync:Vge,databaseSyncUntilSync:Wge,databaseExecSync:Gge,databasePrepareSync:Qge,databaseDefaultSafeIntegers:Yge,databaseAuthorizer:Xge,databaseLoadExtension:eye,databaseMaxWriteReplicationIndex:tye,statementRaw:rye,statementIsReader:nye,statementGet:x5,statementRun:w5,statementInterrupt:iye,statementRowsSync:v5,statementColumns:oye,statementSafeIntegers:sye,rowsNext:aye}=Zge(),cye=g5(),_5=b5();function Ll(e){if(e.libsqlError)return new _5(e.message,e.code,e.rawCode);return e}class k5{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var i="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),i=t.syncAuth;else if(t.authToken)i=t.authToken;let o=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,c=t?.offline??!1,l=t?.remoteEncryptionKey??"";this.db=Fge(e,t.syncUrl,i,r,o,s,a,c,l)}else{let o=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,c=t?.remoteEncryptionKey??"";this.db=Mge(e,o,r,s,a,c)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return Hge(n)}}})}sync(){return Vge.call(this.db)}syncUntil(e){return Wge.call(this.db,e)}prepare(e){try{let t=Qge.call(this.db,e);return new E5(t)}catch(t){throw Ll(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...o)=>{t.exec("BEGIN "+n);try{let s=e(...o);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},i={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(i.default.value,i),Object.defineProperties(i.deferred.value,i),Object.defineProperties(i.immediate.value,i),Object.defineProperties(i.exclusive.value,i),i.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,i=this.prepare(`PRAGMA ${e}`,this,!0);return r?i.pluck().get():i.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){Xge.call(this.db,e)}loadExtension(...e){eye.call(this.db,...e)}maxWriteReplicationIndex(){return tye.call(this.db)}exec(e){try{Gge.call(this.db,e)}catch(t){throw Ll(t)}}interrupt(){Kge.call(this.db)}close(){Jge.call(this.db),this.open=!1}defaultSafeIntegers(e){return Yge.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class E5{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return rye.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return nye.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return w5.call(this.stmt,e[0]);else return w5.call(this.stmt,e.flat())}catch(t){throw Ll(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return x5.call(this.stmt,e[0]);else return x5.call(this.stmt,e.flat())}catch(t){throw Ll(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=v5.call(this.stmt,e[0]);else t=v5.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)aye.call(t,this.nextRows),this.nextRowIndex=0;let i=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!i)return{done:!0};return this.nextRowIndex++,{value:i,done:!1}}catch(i){throw Ll(i)}},[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 Ll(t)}}interrupt(){iye.call(this.stmt)}columns(){return oye.call(this.stmt)}safeIntegers(e){return sye.call(this.stmt,e??!0),this}}ub.exports=k5;ub.exports.Authorization=cye;ub.exports.SqliteError=_5});import{Buffer as A5}from"buffer";function $5(e){if(e.scheme!=="file")throw new Be(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Be(`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 ${hi}`,"URL_INVALID");if(t.port!==void 0)throw new Be("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Be("File URL cannot have username and password","URL_INVALID")}let r=M3(e);if(r&&e.syncUrl)throw new Be(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let i=e.path;if(r)i=`${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},o=new Bf.default(i,n);return Mt(o,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new C5(i,n,o,e.intMode)}class C5{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,i){this.#e=e,this.#t=t,this.#r=r,this.#n=i,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.#i(),Mt(this.#o(),r,this.#n)}async batch(e,t="deferred"){this.#i();let r=this.#o();try{Mt(r,as(t),this.#n);let i=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new cr("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let o=e[n],s=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;i.push(Mt(r,s,this.#n))}catch(o){if(o instanceof cr)throw o;if(o instanceof Be)throw new cr(o.message,n,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return Mt(r,"COMMIT",this.#n),i}finally{if(r.inTransaction)Mt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#i();let t=this.#o();try{Mt(t,"PRAGMA foreign_keys=off",this.#n),Mt(t,as("deferred"),this.#n);let r=[];for(let i=0;i<e.length;i++)try{if(!t.inTransaction)throw new cr("The transaction has been rolled back",i,"TRANSACTION_CLOSED");r.push(Mt(t,e[i],this.#n))}catch(n){if(n instanceof cr)throw n;if(n instanceof Be)throw new cr(n.message,i,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Mt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n);Mt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#o();return Mt(t,as(e),this.#n),this.#r=null,new R5(t,this.#n)}async executeMultiple(e){this.#i();let t=this.#o();try{return O5(t,e)}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n)}}async sync(){this.#i();let e=await this.#o().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 Bf.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#i(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED")}#o(){if(this.#r===null)this.#r=new Bf.default(this.#e,this.#t);return this.#r}}class R5{#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(),Mt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let i=e[r],n=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;t.push(Mt(this.#e,n,this.#t))}catch(i){if(i instanceof cr)throw i;if(i instanceof Be)throw new cr(i.message,r,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return t}async executeMultiple(e){return this.#r(),O5(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Mt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Mt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Mt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Be("The transaction is closed","TRANSACTION_CLOSED")}}function Mt(e,t,r){let i,n;if(typeof t==="string")i=t,n=[];else if(i=t.sql,Array.isArray(t.args))n=t.args.map((o)=>T5(o,r));else{n={};for(let o in t.args){let s=o[0]==="@"||o[0]==="$"||o[0]===":"?o.substring(1):o;n[s]=T5(t.args[o],r)}}try{let o=e.prepare(i);o.safeIntegers(!0);let s=!0;try{o.raw(!0)}catch{s=!1}if(s){let a=Array.from(o.columns().map((p)=>p.name)),c=Array.from(o.columns().map((p)=>p.type??"")),l=o.all(n).map((p)=>lye(p,a,r)),u=0,f=void 0;return new zl(a,c,l,0,void 0)}else{let a=o.run(n),c=a.changes,l=BigInt(a.lastInsertRowid);return new zl([],[],[],c,l)}}catch(o){throw P5(o)}}function lye(e,t,r){let i={};Object.defineProperty(i,"length",{value:e.length});for(let n=0;n<e.length;++n){let o=uye(e[n],r);Object.defineProperty(i,n,{value:o});let s=t[n];if(!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function uye(e,t){if(typeof e==="bigint")if(t==="number"){if(e<dye||e>fye)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 A5)return e.buffer;return e}function T5(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<pye||e>mye)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 A5.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 O5(e,t){try{e.exec(t)}catch(r){throw P5(r)}}function P5(e){if(e instanceof Bf.default.SqliteError){let t=e.code,r=hye(e.rawCode);return new Be(e.message,r,t,e.rawCode,e)}return e}function hye(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return gye[t]??`SQLITE_UNKNOWN_${t.toString()}`}var Bf,dye,fye=9007199254740991n,pye,mye=9223372036854775807n,gye;var z5=S(()=>{jn();Lf();Nl();Bf=hu(I5(),1);jn();dye=-9007199254740991n;pye=-9223372036854775808n;gye={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 ls;var v$=S(()=>{if(typeof WebSocket<"u")ls=WebSocket;else if(typeof global<"u")ls=global.WebSocket;else if(typeof window<"u")ls=window.WebSocket;else if(typeof self<"u")ls=self.WebSocket});class Bl{constructor(){this.intMode="number"}intMode}var st,je,jf,Ot,Uf,jl,Ta,Un,xr,bi;var Pt=S(()=>{st=class st extends Error{constructor(e){super(e);this.name="ClientError"}};je=class je extends st{constructor(e){super(e);this.name="ProtoError"}};jf=class jf extends st{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};Ot=class Ot extends st{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Uf=class Uf extends st{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};jl=class jl extends st{constructor(e){super(e);this.name="WebSocketError"}};Ta=class Ta extends st{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};Un=class Un extends st{constructor(e){super(e);this.name="ProtocolVersionError"}};xr=class xr extends st{constructor(e){super(e);this.name="InternalError"}};bi=class bi extends st{constructor(e){super(e);this.name="MisuseError"}}});function Fr(e){if(typeof e==="string")return e;throw Ul(e,"string")}function sn(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw Ul(e,"string or null")}function Yi(e){if(typeof e==="number")return e;throw Ul(e,"number")}function us(e){if(typeof e==="boolean")return e;throw Ul(e,"boolean")}function qf(e){if(Array.isArray(e))return e;throw Ul(e,"array")}function Lt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw Ul(e,"object")}function qn(e,t){return qf(e).map((r)=>t(Lt(r)))}function Ul(e,t){if(e===void 0)return new je(`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 je(`Expected ${t}, received ${r}`)}function Aa(e,t){return t(Lt(e))}var ql=S(()=>{Pt()});class N5{#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 i=0;i<t.length;++i){if(i!==0)this.#e.push(",");this.begin(),r(this,t[i]),this.end()}this.#e.push("]")}}function Zf(e,t){let r=[],i=new N5(r);return i.begin(),t(i,e),i.end(),r.join("")}var $a=0,Mf=1,Ff=2,D5=5;class L5{#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 B5{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new je(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(Ff);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return ds(this.bytes(),e)}int32(){return this.#r($a),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r($a),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(Mf),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===$a)this.#e.skipVarint();else if(this.#t===Mf)this.#e.skip(8);else if(this.#t===Ff){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===D5)this.#e.skip(4);else throw new je(`Unexpected wire type ${this.#t}`);this.#t=-1}}function ds(e,t){let r=new L5(e),i=new B5(r),n=t.default();while(!r.eof()){let o=r.varint(),s=o>>3,a=o&7;i.setup(a);let c=t[s];if(c!==void 0){let l=c(i,n);if(l!==void 0)n=l}i.maybeSkip()}return n}var _$=S(()=>{Pt()});class k${#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}#i(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),i=new Uint8Array(r),n=new DataView(r);i.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=i,this.#r=n}#o(e){this.#i(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.#i(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.#o(e<<3|t)}bytes(e,t){this.#s(e,Ff),this.#o(t.byteLength),this.#i(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 i=new k$;r(i,t),this.bytes(e,i.data())}int32(e,t){this.#s(e,$a),this.#o(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,$a),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,Mf),this.#i(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Hf(e,t){let r=new k$;return t(r,e),r.data()}var j5=()=>{};var E$=S(()=>{ql();_$();j5()});class fs{#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 xr("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var I$=S(()=>{Pt()});function rt(e,t){throw new xr(t)}var wn=S(()=>{Pt()});function Zl(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<bye||e>Sye)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 T$(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 bi("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new je("Received unrecognized type of Value");else throw rt(e,"Impossible type of Value")}var bye,Sye=9223372036854775807n;var A$=S(()=>{Pt();wn();bye=-9223372036854775808n});function Ca(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function fb(e,t){let r=Ca(e),i=e.rows.map((n)=>U5(r.columnNames,n,t));return{...r,rows:i}}function pb(e,t){let r=Ca(e),i;if(e.rows.length>0)i=U5(r.columnNames,e.rows[0],t);return{...r,row:i}}function mb(e,t){let r=Ca(e),i;if(e.rows.length>0&&r.columnNames.length>0)i=T$(e.rows[0][0],t);return{...r,value:i}}function U5(e,t,r){let i={};Object.defineProperty(i,"length",{value:t.length});for(let n=0;n<t.length;++n){let o=T$(t[n],r);Object.defineProperty(i,n,{value:o});let s=e[n];if(s!==void 0&&!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function Xi(e){return new jf(e.message,e)}var Kf=S(()=>{Pt();A$()});class Ra{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new bi("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new Ot("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new st("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 Jf(e,t){if(t instanceof Ra)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var Ml=S(()=>{Pt()});class ps{#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 Vf{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(Zl(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]=Zl(t),this}bindName(e,t){return this._namedArgs.set(e,Zl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function hb(e,t,r){let i,n=[],o=[];if(t instanceof Vf){i=t.sql,n=t._args;for(let[c,l]of t._namedArgs.entries())o.push({name:c,value:l})}else if(Array.isArray(t))if(i=t[0],Array.isArray(t[1]))n=t[1].map((c)=>Zl(c));else o=Object.entries(t[1]).map(([c,l])=>({name:c,value:Zl(l)}));else i=t;let{sql:s,sqlId:a}=Jf(e,i);return{sql:s,sqlId:a,args:n,namedArgs:o,wantRows:r}}var gb=S(()=>{Ml();A$()});class yb{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new $$(this)}execute(){if(this.#t)throw new bi("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return wye(this._stream,this._steps,e);else return xye(this._stream,this._steps,e)}}function xye(e,t,r){return e._batch(r).then((i)=>{for(let n=0;n<t.length;++n){let o=i.stepResults.get(n),s=i.stepErrors.get(n);t[n].callback(o,s)}})}async function wye(e,t,r){let i=await e._openCursor(r);try{let n=0,o=void 0,s=[];for(;;){let a=await i.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new je("Server produced StepBeginEntry for unexpected step");else if(o!==void 0)throw new je("Server produced StepBeginEntry before terminating previous step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0);n=a.step+1,o=a,s=[]}else if(a.type==="step_end"){if(o===void 0)throw new je("Server produced StepEndEntry but no step is active");let c={cols:o.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[o.step].callback(c,void 0),o=void 0,s=[]}else if(a.type==="step_error"){if(o===void 0){if(a.step>=t.length)throw new je("Server produced StepErrorEntry for unexpected step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0)}else{if(a.step!==o.step)throw new je("Server produced StepErrorEntry for unexpected step");o=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(o===void 0)throw new je("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Xi(a.error);else if(a.type==="none")throw new je("Server produced unrecognized CursorEntry");else throw rt(a,"Impossible CursorEntry")}if(o!==void 0)throw new je("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{i.close()}}class $${_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,fb)}queryRow(e){return this.#t(e,!0,pb)}queryValue(e){return this.#t(e,!0,mb)}run(e){return this.#t(e,!1,Ca)}#t(e,t,r){if(this._index!==void 0)throw new bi("This BatchStep has already been added to the batch");let i=hb(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 o={stmt:i,condition:n};return new Promise((s,a)=>{let c=(l,u)=>{if(l!==void 0&&u!==void 0)a(new je("Server returned both result and error"));else if(u!==void 0)a(Xi(u));else if(l!==void 0)s(r(l,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:o,callback:c})})}}class wt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new wt(e._batch,{type:"ok",step:q5(e)})}static error(e){return new wt(e._batch,{type:"error",step:q5(e)})}static not(e){return new wt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)Z5(e,r);return new wt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)Z5(e,r);return new wt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new wt(e,{type:"is_autocommit"})}}function q5(e){if(e._index===void 0)throw new bi("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function Z5(e,t){if(t._batch!==e)throw new bi("Cannot mix BatchCond objects for different Batch objects")}var C$=S(()=>{Pt();Kf();gb();wn()});function M5(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class Fl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,fb)}queryRow(e){return this.#e(e,!0,pb)}queryValue(e){return this.#e(e,!0,mb)}run(e){return this.#e(e,!1,Ca)}#e(e,t,r){let i=hb(this._sqlOwner(),e,t);return this._execute(i).then((n)=>r(n,this.intMode))}batch(e=!1){return new yb(this,e)}describe(e){let t=Jf(this._sqlOwner(),e);return this._describe(t).then(M5)}sequence(e){let t=Jf(this._sqlOwner(),e);return this._sequence(t)}intMode}var bb=S(()=>{C$();Kf();Ml();gb()});class Wf{}var vye=1000,_ye=10,R$;var F5=S(()=>{Pt();R$=class R$ extends Wf{#e;#t;#r;#n;#i;#o;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new ps,this.#i=new ps,this.#o=void 0,this.#a=!1}async next(){for(;;){if(this.#o!==void 0)throw new Ot("Cursor is closed",this.#o);while(!this.#a&&this.#i.length<_ye)this.#i.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#i.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:vye}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#o!==void 0)return;this.#o=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new st("Cursor was manually closed"))}get closed(){return this.#o!==void 0}}});var Gf;var O$=S(()=>{Pt();bb();F5();Gf=class Gf extends Fl{#e;#t;#r;#n;#i;#o;static open(e){let t=e._streamIdAlloc.alloc(),r=new Gf(e,t),i=()=>{return},n=(s)=>r.#l(s),o={type:"open_stream",streamId:t};return e._sendRequest(o,{responseCallback:i,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new ps,this.#n=void 0,this.#i=!1,this.#o=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 xr("Cursor not associated with the stream attempted to execute a request");return new Promise((r,i)=>{if(this.#o!==void 0)i(new Ot("Stream is closed",this.#o));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})})}_cursorClosed(e){if(e!==this.#n)throw new xr("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#o!==void 0)e.errorCallback(new Ot("Stream is closed",this.#o));else if(this.#i)e.errorCallback(new Ot("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.#i){this.#l(new st("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:i}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let i=this.#e._cursorIdAlloc.alloc(),n=new R$(this.#e,this,i),o={type:"open_cursor",streamId:this.#t,cursorId:i,batch:t},s=()=>{return},a=(c)=>n._setClosed(c);this.#e._sendRequest(o,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#o!==void 0)return;if(this.#o=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),i=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}close(){this.#l(new st("Stream was manually closed"))}closeGracefully(){this.#i=!0,this.#c()}get closed(){return this.#o!==void 0||this.#i}}});function Qf(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,H5),e.arrayObjects("named_args",t.namedArgs,kye),e.boolean("want_rows",t.wantRows)}function kye(e,t){e.string("name",t.name),e.object("value",t.value,H5)}function Hl(e,t){e.arrayObjects("steps",t.steps,Eye)}function Eye(e,t){if(t.condition!==void 0)e.object("condition",t.condition,P$);e.object("stmt",t.stmt,Qf)}function P$(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,P$);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,P$);else if(t.type==="is_autocommit");else throw rt(t,"Impossible type of BatchCond")}function H5(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",Pl.fromUint8Array(t));else if(t===void 0);else throw rt(t,"Impossible type of Value")}var z$=S(()=>{cb();wn()});function K5(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,Iye);else throw rt(t,"Impossible type of ClientMsg")}function Iye(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,Qf);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,Hl);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,Hl);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 rt(t,"Impossible type of Request")}var J5=S(()=>{z$();wn()});function Yf(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,W5);for(let r of t.namedArgs)e.message(4,r,Tye);e.bool(5,t.wantRows)}function Tye(e,t){e.string(1,t.name),e.message(2,t.value,W5)}function Kl(e,t){for(let r of t.steps)e.message(1,r,Aye)}function Aye(e,t){if(t.condition!==void 0)e.message(1,t.condition,N$);e.message(2,t.stmt,Yf)}function N$(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,N$);else if(t.type==="and")e.message(4,t.conds,V5);else if(t.type==="or")e.message(5,t.conds,V5);else if(t.type==="is_autocommit")e.message(6,void 0,G5);else throw rt(t,"Impossible type of BatchCond")}function V5(e,t){for(let r of t)e.message(1,r,N$)}function W5(e,t){if(t===null)e.message(1,void 0,G5);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 rt(t,"Impossible type of Value")}function G5(e,t){}var D$=S(()=>{wn()});function Q5(e,t){if(t.type==="hello")e.message(1,t,$ye);else if(t.type==="request")e.message(2,t,Cye);else throw rt(t,"Impossible type of ClientMsg")}function $ye(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Cye(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Rye);else if(r.type==="close_stream")e.message(3,r,Oye);else if(r.type==="execute")e.message(4,r,Pye);else if(r.type==="batch")e.message(5,r,zye);else if(r.type==="open_cursor")e.message(6,r,Nye);else if(r.type==="close_cursor")e.message(7,r,Dye);else if(r.type==="fetch_cursor")e.message(8,r,Lye);else if(r.type==="sequence")e.message(9,r,Bye);else if(r.type==="describe")e.message(10,r,jye);else if(r.type==="store_sql")e.message(11,r,Uye);else if(r.type==="close_sql")e.message(12,r,qye);else if(r.type==="get_autocommit")e.message(13,r,Zye);else throw rt(r,"Impossible type of Request")}function Rye(e,t){e.int32(1,t.streamId)}function Oye(e,t){e.int32(1,t.streamId)}function Pye(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Yf)}function zye(e,t){e.int32(1,t.streamId),e.message(2,t.batch,Kl)}function Nye(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,Kl)}function Dye(e,t){e.int32(1,t.cursorId)}function Lye(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Bye(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 jye(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 Uye(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function qye(e,t){e.int32(1,t.sqlId)}function Zye(e,t){e.int32(1,t.streamId)}var Y5=S(()=>{D$();wn()});function ms(e){let t=Fr(e.message),r=sn(e.code);return{message:t,code:r}}function Xf(e){let t=qn(e.cols,X5),r=qf(e.rows).map((s)=>qn(s,e8)),i=Yi(e.affected_row_count),n=sn(e.last_insert_rowid),o=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:i,lastInsertRowid:o}}function X5(e){let t=sn(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function Sb(e){let t=new Map;qf(e.step_results).forEach((i,n)=>{if(i!==null)t.set(n,Xf(Lt(i)))});let r=new Map;return qf(e.step_errors).forEach((i,n)=>{if(i!==null)r.set(n,ms(Lt(i)))}),{stepResults:t,stepErrors:r}}function xb(e){let t=Fr(e.type);if(t==="step_begin"){let r=Yi(e.step),i=qn(e.cols,X5);return{type:"step_begin",step:r,cols:i}}else if(t==="step_end"){let r=Yi(e.affected_row_count),i=sn(e.last_insert_rowid),n=i!==void 0?BigInt(i):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Yi(e.step),i=ms(Lt(e.error));return{type:"step_error",step:r,error:i}}else if(t==="row")return{type:"row",row:qn(e.row,e8)};else if(t==="error")return{type:"error",error:ms(Lt(e.error))};else throw new je("Unexpected type of CursorEntry")}function wb(e){let t=qn(e.params,Mye),r=qn(e.cols,Fye),i=us(e.is_explain),n=us(e.is_readonly);return{params:t,cols:r,isExplain:i,isReadonly:n}}function Mye(e){return{name:sn(e.name)}}function Fye(e){let t=Fr(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function e8(e){let t=Fr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Fr(e.value);return BigInt(r)}else if(t==="float")return Yi(e.value);else if(t==="text")return Fr(e.value);else if(t==="blob")return Pl.toUint8Array(Fr(e.base64));else throw new je("Unexpected type of Value")}var vb=S(()=>{cb();Pt();ql()});function t8(e){let t=Fr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:ms(Lt(e.error))};else if(t==="response_ok"){let r=Yi(e.request_id),i=Hye(Lt(e.response));return{type:"response_ok",requestId:r,response:i}}else if(t==="response_error"){let r=Yi(e.request_id),i=ms(Lt(e.error));return{type:"response_error",requestId:r,error:i}}else throw new je("Unexpected type of ServerMsg")}function Hye(e){let t=Fr(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:Xf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:Sb(Lt(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=qn(e.entries,xb),i=us(e.done);return{type:"fetch_cursor",entries:r,done:i}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:wb(Lt(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:us(e.is_autocommit)};else throw new je("Unexpected type of Response")}var r8=S(()=>{Pt();ql();vb()});var vn,hs,n8,i8,Jl,Kye,Jye,_b,Vye,Wye,Gye,Vl,Qye,Yye,Xye;var kb=S(()=>{vn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},hs={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(n8))},2(e,t){t.rows.push(e.message(i8))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},n8={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},i8={default(){return[]},1(e,t){t.push(e.message(Xye))}},Jl={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,i]=e.message(Kye);t.stepResults.set(r,i)},2(e,t){let[r,i]=e.message(Jye);t.stepErrors.set(r,i)}},Kye={default(){return[0,hs.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(hs)}},Jye={default(){return[0,vn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(vn)}},_b={default(){return{type:"none"}},1(e){return e.message(Vye)},2(e){return e.message(Wye)},3(e){return e.message(Gye)},4(e){return{type:"row",row:e.message(i8)}},5(e){return{type:"error",error:e.message(vn)}}},Vye={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(n8))}},Wye={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Gye={default(){return{type:"step_error",step:0,error:vn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(vn)}},Vl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Qye))},2(e,t){t.cols.push(e.message(Yye))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Qye={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Yye={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},Xye={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 o8,ebe,tbe,rbe,nbe,ibe,obe,sbe,abe;var s8=S(()=>{kb();o8={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(ebe)},3(e){return e.message(rbe)},4(e){return e.message(tbe)}},ebe={default(){return{type:"hello_error",error:vn.default()}},1(e,t){t.error=e.message(vn)}},tbe={default(){return{type:"response_error",requestId:0,error:vn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(vn)}},rbe={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(nbe)},5(e,t){t.response=e.message(ibe)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(obe)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(sbe)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(abe)}},nbe={default(){return{type:"execute",result:hs.default()}},1(e,t){t.result=e.message(hs)}},ibe={default(){return{type:"batch",result:Jl.default()}},1(e,t){t.result=e.message(Jl)}},obe={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(_b))},2(e,t){t.done=e.bool()}},sbe={default(){return{type:"describe",result:Vl.default()}},1(e,t){t.result=e.message(Vl)}},abe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var a8,L$,Eb;var Ib=S(()=>{E$();Pt();I$();Kf();Ml();wn();O$();J5();Y5();r8();s8();a8=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),L$=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Eb=class Eb extends Bl{#e;#t;#r;#n;#i;#o;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#i=!1,this.#o=void 0,this.#a=!1,this.#s=new Map,this.#c=new fs,this._streamIdAlloc=new fs,this._cursorIdAlloc=new fs,this.#l=new fs,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#f()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#p(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new xr("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})}}#f(){let e=this.#e.protocol;if(e===void 0){this.#u(new st("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.#o={version:1,encoding:"json"};else if(this.#o=L$.get(e),this.#o===void 0){this.#u(new je(`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.#o.encoding;if(t==="json"){let r=Zf(e,K5);this.#e.send(r)}else if(t==="protobuf"){let r=Hf(e,Q5);this.#e.send(r)}else throw rt(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.#o.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#o.version)})}_ensureVersion(e,t){if(this.#o===void 0||!this.#a)throw new Un(`${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.#o.version<e)throw new Un(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#o.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new Ot("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})}#p(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new jl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new jl(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.#o.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new je("Received non-text message from server with JSON encoding"));return}t=Aa(JSON.parse(e.data),t8)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new je("Received non-binary message from server with Protobuf encoding"));return}t=ds(new Uint8Array(e.data),o8)}else throw rt(r,"Impossible encoding");this.#h(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#h(e){if(e.type==="none")throw new je("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#i)throw new je("Received a duplicated hello response");if(this.#i=!0,e.type==="hello_error")throw Xi(e.error);return}else if(!this.#i)throw new je("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 je("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new je("Received unexpected type of response");r.responseCallback(e.response)}catch(i){throw r.errorCallback(i),i}}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 je("Received unexpected error response");this.#c.free(t),r.errorCallback(Xi(e.error))}else throw rt(e,"Impossible ServerMsg type")}openStream(){return Gf.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new Ra(this,t),i=()=>{return},n=(s)=>r._setClosed(s),o={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(o,{responseCallback:i,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),i={type:"close_sql",sqlId:e};this._sendRequest(i,{responseCallback:t,errorCallback:r})}close(){this.#u(new st("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var Oa;var c8=S(()=>{if(typeof queueMicrotask<"u")Oa=queueMicrotask;else{let e=Promise.resolve();Oa=(t)=>{e.then(t)}}});class B${#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 i=new Uint8Array(new ArrayBuffer(r));i.set(this.#e.slice(this.#t,this.#r),0),this.#e=i}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function l8(e){let t=sn(e.baton),r=sn(e.base_url),i=qn(e.results,cbe);return{baton:t,baseUrl:r,results:i}}function cbe(e){let t=Fr(e.type);if(t==="ok")return{type:"ok",response:lbe(Lt(e.response))};else if(t==="error")return{type:"error",error:ms(Lt(e.error))};else throw new je("Unexpected type of StreamResult")}function lbe(e){let t=Fr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Xf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:Sb(Lt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:wb(Lt(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:us(e.is_autocommit)};else throw new je("Unexpected type of StreamResponse")}function u8(e){let t=sn(e.baton),r=sn(e.base_url);return{baton:t,baseUrl:r}}var j$=S(()=>{Pt();ql();vb()});var d8,ube,dbe,fbe,pbe,mbe,hbe,f8;var U$=S(()=>{kb();d8={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(ube))}},ube={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(dbe)}},2(e){return{type:"error",error:e.message(vn)}}},dbe={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(fbe)},3(e){return e.message(pbe)},4(e){return{type:"sequence"}},5(e){return e.message(mbe)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(hbe)}},fbe={default(){return{type:"execute",result:hs.default()}},1(e,t){t.result=e.message(hs)}},pbe={default(){return{type:"batch",result:Jl.default()}},1(e,t){t.result=e.message(Jl)}},mbe={default(){return{type:"describe",result:Vl.default()}},1(e,t){t.result=e.message(Vl)}},hbe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},f8={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var q$;var p8=S(()=>{ql();_$();Pt();wn();j$();U$();vb();kb();q$=class q$ extends Wf{#e;#t;#r;#n;#i;#o;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new B$(16384),this.#i=void 0,this.#o=!1}async open(e){if(e.body===null)throw new je("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(u8,f8);if(t===void 0)throw new je("Empty response to cursor request");return t}next(){return this.#a(xb,_b)}close(){this._setClosed(new st("Cursor was manually closed"))}_setClosed(e){if(this.#i!==void 0)return;if(this.#i=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#i!==void 0}async#a(e,t){for(;;){if(this.#o)return;else if(this.#i!==void 0)throw new Ot("Cursor is closed",this.#i);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let o=new TextDecoder().decode(n),s=JSON.parse(o);return Aa(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return ds(n,t)}else throw rt(this.#t,"Impossible encoding");if(this.#r===void 0)throw new xr("Attempted to read from HTTP cursor before it was opened");let{value:r,done:i}=await this.#r.next();if(i&&this.#n.length===0)this.#o=!0;else if(i)throw new je("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 i=e.slice(0,r);return this.#n.shift(r+1),i}#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 i=e.slice(r,r+t);return this.#n.shift(r+t),i}}});function m8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,gbe)}function gbe(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Qf);else if(t.type==="batch")e.object("batch",t.batch,Hl);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 rt(t,"Impossible type of StreamRequest")}function h8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,Hl)}var Z$=S(()=>{z$();wn()});function g8(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,ybe)}function ybe(e,t){if(t.type==="close")e.message(1,t,bbe);else if(t.type==="execute")e.message(2,t,Sbe);else if(t.type==="batch")e.message(3,t,xbe);else if(t.type==="sequence")e.message(4,t,wbe);else if(t.type==="describe")e.message(5,t,vbe);else if(t.type==="store_sql")e.message(6,t,_be);else if(t.type==="close_sql")e.message(7,t,kbe);else if(t.type==="get_autocommit")e.message(8,t,Ebe);else throw rt(t,"Impossible type of StreamRequest")}function bbe(e,t){}function Sbe(e,t){e.message(1,t.stmt,Yf)}function xbe(e,t){e.message(1,t.batch,Kl)}function wbe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function vbe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function _be(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function kbe(e,t){e.int32(1,t.sqlId)}function Ebe(e,t){}function y8(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,Kl)}var M$=S(()=>{D$();wn()});function Ibe(e,t){if(t.results.length!==e.length)throw new je("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let i=t.results[r],n=e[r];if(i.type==="ok"){if(i.response.type!==n.request.type)throw new je("Received unexpected type of response");n.responseCallback(i.response)}else if(i.type==="error")n.errorCallback(Xi(i.error));else if(i.type==="none")throw new je("Received unrecognized type of StreamResult");else throw rt(i,"Received impossible type of StreamResult")}}async function Tbe(e,t){if(t==="json"){let r=await e.json();return Aa(r,l8)}if(t==="protobuf"){let r=await e.arrayBuffer();return ds(new Uint8Array(r),d8)}throw await e.body?.cancel(),rt(t,"Impossible encoding")}async function Abe(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let i=await e.json();if("message"in i)return Xi(i);return new Ta(r,e.status)}if(t==="text/plain"){let i=(await e.text()).trim();if(i!=="")r+=`: ${i}`;return new Ta(r,e.status)}return await e.body?.cancel(),new Ta(r,e.status)}var Tb;var F$=S(()=>{Pt();E$();I$();c8();Kf();Ml();bb();wn();p8();Z$();M$();Z$();M$();j$();U$();Tb=class Tb extends Fl{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;#f;#m;constructor(e,t,r,i,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=i,this.#i=n,this.#o=void 0,this.#a=new ps,this.#s=!1,this.#l=!1,this.#d=!1,this.#f=void 0,this.#m=new fs}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#p({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new Ra(this,t)}_closeSql(e){if(this.#f!==void 0)return;this.#p({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#p({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#p({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#p({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#p({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#p({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#p(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 xr("Cursor was closed, but it was not associated with the stream");this.#c=void 0,Oa(()=>this.#u())}close(){this._setClosed(new st("Stream was manually closed"))}closeGracefully(){this.#l=!0,Oa(()=>this.#u())}get closed(){return this.#f!==void 0||this.#l}_setClosed(e){if(this.#f!==void 0)return;if(this.#f=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.#o!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,Oa(()=>this.#u())}#g(e){if(this.#f!==void 0)throw new Ot("Stream is closed",this.#f);else if(this.#l)throw new Ot("Stream is closing",void 0);else this.#a.push(e),Oa(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new st("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 i=this.#a.first();if(i!==void 0&&i.type==="pipeline")r.push(i),this.#a.shift();else if(i===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.#h(e,t);else throw rt(t,"Impossible type of QueueEntry")}#y(e,t){this.#b(()=>this.#S(t,e),(r)=>Tbe(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Ibe(t,r),(r)=>t.forEach((i)=>i.errorCallback(r)))}#h(e,t){let r=new q$(this,e.encoding);this.#c=r,this.#b(()=>this.#w(t,e),(i)=>r.open(i),(i)=>i.baton,(i)=>i.baseUrl,(i)=>t.cursorCallback(r),(i)=>t.errorCallback(i))}#b(e,t,r,i,n,o){let s;try{let a=e(),c=this.#n;s=c(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Abe(a).then((c)=>{throw c});return t(a)}).then((a)=>{this.#o=r(a),this.#t=i(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),o(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#x(new URL(t.pipelinePath,this.#t),{baton:this.#o,requests:e.map((r)=>r.request)},t.encoding,m8,g8)}#w(e,t){if(t.cursorPath===void 0)throw new Un(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#x(new URL(t.cursorPath,this.#t),{baton:this.#o,batch:e.batch},t.encoding,h8,y8)}#x(e,t,r,i,n){let o,s;if(r==="json")o=Zf(t,i),s="application/json";else if(r==="protobuf")o=Hf(t,n),s="application/x-protobuf";else throw rt(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.#i!==void 0)a.set("x-turso-encryption-key",this.#i);return new Request(e.toString(),{method:"POST",headers:a,body:o})}}});async function Cbe(e,t){let r=e;for(let i of $be){let n=new URL(i.versionPath,t),o=new Request(n.toString(),{method:"GET"}),s=await r(o);if(await s.arrayBuffer(),s.ok)return i}return H$}var $be,H$,Ab;var K$=S(()=>{Pt();F$();$be=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],H$={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};Ab=class Ab extends Bl{#e;#t;#r;#n;#i;#o;_endpointPromise;_endpoint;constructor(e,t,r,i,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=i,this.#i=void 0,this.#o=new Set,n==3)this._endpointPromise=Cbe(this.#r,this.#e),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o));else this._endpointPromise=Promise.resolve(H$),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=H$.version)return;else if(this._endpoint===void 0)throw new Un(`${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 Un(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#i!==void 0)throw new Ot("Client is closed",this.#i);let e=new Tb(this,this.#e,this.#t,this.#r,this.#n);return this.#o.add(e),e}_streamClosed(e){this.#o.delete(e)}close(){this.#a(new st("Client was manually closed"))}get closed(){return this.#i!==void 0}#a(e){if(this.#i!==void 0)return;this.#i=e;for(let t of Array.from(this.#o))t._setClosed(new Ot("Client was closed",e))}}});var b8=S(()=>{Pt()});function J$(e,t,r=2){if(typeof ls>"u")throw new Uf("WebSockets are not supported in this environment");var i=void 0;if(r==3)i=Array.from(L$.keys());else i=Array.from(a8.keys());let n=new ls(e,i);return new Eb(n,t)}function V$(e,t,r,i,n=2){return new Ab(e instanceof URL?e:new URL(e),t,r,i,n)}var $b=S(()=>{v$();Ib();Pt();K$();Ib();v$();C$();b8();Ml();gb();bb();K$();F$();Ib();O$();Pt()});class ep{#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 Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(eo),i;if(this.#r===void 0){this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=o.step(),a=s.run(as(this.#e)),c=s;i=r.map((l)=>{let u=o.step().condition(wt.ok(c));if(this.#t>=3)u.condition(wt.not(wt.isAutocommit(o)));let f=u.query(l);return f.catch(()=>{return}),c=u,f}),this.#r=o.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(l){throw this.close(),l}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=void 0;i=r.map((a)=>{let c=o.step();if(s!==void 0)c.condition(wt.ok(s));if(this.#t>=3)c.condition(wt.not(wt.isAutocommit(o)));let l=c.query(a);return l.catch(()=>{return}),s=c,l}),await o.execute()}let n=[];for(let o=0;o<i.length;o++)try{let s=await i[o];if(s===void 0)throw new cr("Statement in a transaction was not executed, probably because the transaction has been rolled back",o,"TRANSACTION_CLOSED");n.push(Gl(s))}catch(s){if(s instanceof cr)throw s;let a=yt(s);if(a instanceof Be)throw new cr(a.message,o,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw yt(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(as(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 yt(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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Be("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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}}async function Wl(e,t,r,i,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let o=r.step(),s=o.run(as(e)),a=o,c=i.map((m)=>{let y=r.step().condition(wt.ok(a));if(t>=3)y.condition(wt.not(wt.isAutocommit(r)));let g=y.query(m);return a=y,g}),l=r.step().condition(wt.ok(a));if(t>=3)l.condition(wt.not(wt.isAutocommit(r)));let u=l.run("COMMIT");if(r.step().condition(wt.not(wt.ok(l))).run("ROLLBACK").catch((m)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let p=[];await s;for(let m=0;m<c.length;m++)try{let y=await c[m];if(y===void 0)throw new cr("Statement in a batch was not executed, probably because the transaction has been rolled back",m,"TRANSACTION_CLOSED");p.push(Gl(y))}catch(y){if(y instanceof cr)throw y;let g=yt(y);if(g instanceof Be)throw new cr(g.message,m,g.code,g.extendedCode,g.rawCode,g.cause instanceof Error?g.cause:void 0);throw g}return await u,p}function eo(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 i=new Vf(t);if(r)if(Array.isArray(r))i.bindIndexes(r);else for(let[n,o]of Object.entries(r))i.bindName(n,o);return i}function Gl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),i=e.rows,n=e.affectedRowCount,o=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new zl(t,r,i,n,o)}function yt(e){if(e instanceof st){let t=S8(e);return new Be(e.message,t,void 0,void 0,e)}return e}function S8(e){if(e instanceof jf&&e.code!==void 0)return e.code;else if(e instanceof je)return"HRANA_PROTO_ERROR";else if(e instanceof Ot)return e.cause instanceof st?S8(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof jl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof Ta)return"SERVER_ERROR";else if(e instanceof Un)return"PROTOCOL_VERSION_ERROR";else if(e instanceof xr)return"INTERNAL_ERROR";else return"UNKNOWN"}var G$=S(()=>{$b();jn();Nl()});class Ql{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new x8,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 i=r.sql;if(i.length>=5000)continue;let n=this.#t.get(i);if(n===void 0){while(this.#t.size+1>this.capacity){let[o,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(o)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(i),this.#t.set(i,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class x8{#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 Q$=Se(function(j3e,v8){function Rbe(e){var t=0,r=[];function i(){if(t--,t<e)n()}function n(){var c=r.shift();if(a.queue=r.length,c)s(c.fn).then(c.resolve).catch(c.reject)}function o(c){return new Promise(function(l,u){r.push({fn:c,resolve:l,reject:u}),a.queue=r.length})}function s(c){t++;try{return Promise.resolve(c()).then(function(l){return i(),l},function(l){throw i(),l})}catch(l){return i(),Promise.reject(l)}}var a=function(c){if(t>=e)return o(c);else return s(c)};return a}function Obe(e,t){var r=!1,i=this;return Promise.all(e.map(function(){var n=arguments;return i(function(){if(!r)return t.apply(void 0,n).catch(function(o){throw r=!0,o})})}))}function w8(e){return e.queue=0,e.map=Obe,e}v8.exports=function(e){if(e)return w8(Rbe(e));else return w8(function(t){return t()})}});function E8(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Be(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Be('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Be('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=zf(e.scheme,e.authority,e.path),r;try{r=J$(t,e.authToken)}catch(i){if(i instanceof Uf){let n=e.scheme==="wss"?"https":"http",o=zf(n,e.authority,e.path);throw new Be(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(o)}). For more information, please read ${hi}`,"WEBSOCKETS_NOT_SUPPORTED")}throw yt(i)}return new I8(r,t,e.authToken,e.intMode,e.concurrency)}class I8{#e;#t;#r;#n;#i;closed;protocol;#o;#a;constructor(e,t,r,i,n){this.#e=t,this.#t=r,this.#r=i,this.#n=this.#c(e),this.#i=void 0,this.closed=!1,this.protocol="ws",this.#a=k8.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 i=await this.#s();try{let n=eo(r);i.conn.sqlCache.apply([n]);let o=i.stream.query(n);i.stream.closeGracefully();let s=await o;return Gl(s)}catch(n){throw yt(n)}finally{this._closeStream(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(eo),o=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(o>=3);return await Wl(t,o,s,n)}catch(i){throw yt(i)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(eo),i=await t.conn.client.getVersion(),n=t.stream.batch(i>=3);return await Wl("deferred",i,n,r,!0)}catch(r){throw yt(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 T8(this,t,e,r)}catch(r){throw this._closeStream(t),yt(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 yt(r)}finally{this._closeStream(t)}})}sync(){throw new Be("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Pbe&&this.#i===void 0){let i=this.#c();this.#i=i,i.client.getVersion().then((n)=>{if(this.#n!==i){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=i,this.#i=void 0},(n)=>{this.#i=void 0})}if(this.#n.client.closed)try{if(this.#i!==void 0)this.#n=this.#i;else this.#n=this.#c()}catch(i){throw yt(i)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=_8}let i=r.client.openStream();i.intMode=this.#r;let n={conn:r,stream:i};return r.streamStates.add(n),n}catch(i){throw yt(i)}}#c(e){try{return e??=J$(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Ql(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw yt(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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=_8;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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}this.closed=!0}}var k8,Pbe=60000,_8=100,T8;var A8=S(()=>{$b();jn();Lf();G$();ob();Nl();k8=hu(Q$(),1);jn();T8=class T8 extends ep{#e;#t;constructor(e,t,r,i){super(r,i);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 C8(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Be(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Be('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Be('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=zf(e.scheme,e.authority,e.path);return new O8(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class O8{#e;protocol;#t;#r;#n;#i;#o;#a;#s;constructor(e,t,r,i,n,o){this.#t=e,this.#o=t,this.#r=r,this.#n=i,this.#i=n,this.#a=o,this.#e=V$(this.#t,this.#o,this.#n,o),this.#e.intMode=this.#r,this.protocol="http",this.#s=$8.default(this.#i)}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 i=eo(r),n,o=this.#e.openStream();try{n=o.query(i)}finally{o.closeGracefully()}let s=await n;return Gl(s)}catch(i){throw yt(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let i=e.map((c)=>{if(Array.isArray(c))return{sql:c[0],args:c[1]||[]};return c}).map(eo),n=await this.#e.getVersion(),o,s=this.#e.openStream();try{new Ql(s,R8).apply(i);let l=s.batch(!1);o=Wl(t,n,l,i)}finally{s.closeGracefully()}return await o}catch(r){throw yt(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(eo),r=await this.#e.getVersion(),i,n=this.#e.openStream();try{let s=n.batch(!1);i=Wl("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await i}catch(t){throw yt(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new P8(this.#e.openStream(),e,t)}catch(t){throw yt(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 yt(t)}})}sync(){throw new Be("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=V$(this.#t,this.#o,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var $8,R8=30,P8;var z8=S(()=>{$b();jn();Lf();G$();ob();Nl();$8=hu(Q$(),1);jn();P8=class P8 extends ep{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Ql(e,R8)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Yl(e){return zbe(Df(e,!0))}function zbe(e){if(e.scheme==="wss"||e.scheme==="ws")return E8(e);else if(e.scheme==="https"||e.scheme==="http")return C8(e);else return $5(e)}var Y$=S(()=>{Lf();z5();A8();z8();jn()});function ae(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,J))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(J in r&&r[J]===t[J])return!0;r=Object.getPrototypeOf(r)}return!1}var J;var ze=S(()=>{J=Symbol.for("drizzle:entityKind")});var nt;var Zn=S(()=>{ze();nt=class nt{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[J]="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 tp;var Cb=S(()=>{ze();tp=class tp{static[J]="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 wr;var Xl=S(()=>{wr=Symbol.for("drizzle:Name")});var X$,N8;var D8=S(()=>{ze();Xl();X$=class X${static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 N8(e,this)}};N8=class N8{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function Rb(e,...t){return e(...t)}var eC=()=>{};function tC(e,t){return`${e[wr]}_${t.join("_")}_unique`}var L8,Nbe,B8;var j8=S(()=>{ze();Xl();L8=class L8{constructor(e,t){this.name=t,this.columns=e}static[J]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new B8(e,this.columns,this.nullsNotDistinctConfig,this.name)}};Nbe=class Nbe{static[J]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new L8(e,this.name)}};B8=class B8{constructor(e,t,r,i){this.table=e,this.columns=t,this.name=i??tC(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[J]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function U8(e,t,r){for(let i=t;i<e.length;i++){let n=e[i];if(n==="\\"){i++;continue}if(n==='"')return[e.slice(t,i).replace(/\\/g,""),i+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,i).replace(/\\/g,""),i]}return[e.slice(t).replace(/\\/g,""),e.length]}function q8(e,t=0){let r=[],i=t,n=!1;while(i<e.length){let o=e[i];if(o===","){if(n||i===t)r.push("");n=!0,i++;continue}if(n=!1,o==="\\"){i+=2;continue}if(o==='"'){let[c,l]=U8(e,i+1,!0);r.push(c),i=l;continue}if(o==="}")return[r,i+1];if(o==="{"){let[c,l]=q8(e,i+1);r.push(c),i=l;continue}let[s,a]=U8(e,i,!1);r.push(s),i=a}return[r,i]}function Z8(e){let[t]=q8(e,1);return t}function rC(e){return`{${e.map((t)=>{if(Array.isArray(t))return rC(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var M8=()=>{};var rp,eu,F8,Dbe,H8,nC;var K8=S(()=>{Cb();Zn();ze();D8();eC();j8();M8();rp=class rp extends tp{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(e){return new H8(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:i})=>Rb((n,o)=>{let s=new X$(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)},r,i))}buildExtraConfigColumn(e){return new F8(e,this.config)}};eu=class eu extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=tC(e,[t.name]);super(e,t);this.table=e}static[J]="PgColumn"};F8=class F8 extends eu{static[J]="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}};Dbe=class Dbe{static[J]="IndexedColumn";constructor(e,t,r,i){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=i}name;keyAsName;type;indexConfig};H8=class H8 extends rp{static[J]="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 nC(e,this.config,t)}};nC=class nC extends eu{constructor(e,t,r,i){super(e,t);this.baseColumn=r,this.range=i,this.size=t.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=Z8(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((i)=>i===null?null:ae(this.baseColumn,nC)?this.baseColumn.mapToDriverValue(i,!0):this.baseColumn.mapToDriverValue(i));if(t)return r;return rC(r)}}});function W8(e){return!!e&&typeof e==="function"&&J8 in e&&e[J8]===!0}var Lbe,V8,J8,Bbe,G8;var Q8=S(()=>{ze();K8();Lbe=class Lbe extends rp{static[J]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new V8(e,this.config)}};V8=class V8 extends eu{static[J]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};J8=Symbol.for("drizzle:isPgEnum");Bbe=class Bbe extends rp{static[J]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new G8(e,this.config)}};G8=class G8 extends eu{static[J]="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 vt,np;var Mn=S(()=>{ze();vt=class vt{static[J]="Subquery";constructor(e,t,r,i=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:i,usedTables:n}}};np=class np extends vt{static[J]="WithSubquery"}});var Y8="0.45.2";var X8=()=>{};var iC,oC,eH;var tH=S(()=>{eC();X8();eH={startActiveSpan(e,t){if(!iC)return t();if(!oC)oC=iC.trace.getTracer("drizzle-orm",Y8);return Rb((r,i)=>i.startActiveSpan(e,(n)=>{try{return t(n)}catch(o){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{n.end()}}),iC,oC)}}});var _t;var to=S(()=>{_t=Symbol.for("drizzle:ViewBaseConfig")});function gs(e){return e[wr]}function Pa(e){return`${e[Ob]??"public"}.${e[wr]}`}var Ob,Pb,rH,sC,aC,ip,nH,jbe,we;var vr=S(()=>{ze();Xl();Ob=Symbol.for("drizzle:Schema"),Pb=Symbol.for("drizzle:Columns"),rH=Symbol.for("drizzle:ExtraConfigColumns"),sC=Symbol.for("drizzle:OriginalName"),aC=Symbol.for("drizzle:BaseName"),ip=Symbol.for("drizzle:IsAlias"),nH=Symbol.for("drizzle:ExtraConfigBuilder"),jbe=Symbol.for("drizzle:IsDrizzleTable");we=class we{static[J]="Table";static Symbol={Name:wr,Schema:Ob,OriginalName:sC,Columns:Pb,ExtraConfigColumns:rH,BaseName:aC,IsAlias:ip,ExtraConfigBuilder:nH};[wr];[sC];[Ob];[Pb];[rH];[aC];[ip]=!1;[jbe]=!0;[nH]=void 0;constructor(e,t,r){this[wr]=this[sC]=e,this[Ob]=t,this[aC]=r}}});function cC(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function qbe(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 iH(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function U(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Ft(e[0]));for(let[i,n]of t.entries())r.push(n,new Ft(e[i+1]));return new Te(r)}function op(e,t){return e.map((r)=>{if(ae(r,ys)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(ae(r,an)&&ae(r.value,ys)){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 Ube,Ft,Te,zb,oH,sH,G5e,an,ys,Zbe,_n;var ur=S(()=>{ze();Q8();Mn();tH();to();Zn();vr();Ube=class Ube{static[J]="FakePrimitiveParam"};Ft=class Ft{static[J]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Te([this])}};Te=class Te{constructor(e){this.queryChunks=e;for(let t of e)if(ae(t,we)){let r=t[we.Symbol.Schema];this.usedTables.push(r===void 0?t[we.Symbol.Name]:r+"."+t[we.Symbol.Name])}}static[J]="SQL";decoder=oH;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return eH.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:i,escapeName:n,escapeParam:o,prepareTyping:s,inlineParams:a,paramStartIndex:c}=r;return qbe(e.map((l)=>{if(ae(l,Ft))return{sql:l.value.join(""),params:[]};if(ae(l,zb))return{sql:n(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){let u=[new Ft("(")];for(let[f,p]of l.entries())if(u.push(p),f<l.length-1)u.push(new Ft(", "));return u.push(new Ft(")")),this.buildQueryFromSourceParams(u,r)}if(ae(l,Te))return this.buildQueryFromSourceParams(l.queryChunks,{...r,inlineParams:a||l.shouldInlineParams});if(ae(l,we)){let u=l[we.Symbol.Schema],f=l[we.Symbol.Name];return{sql:u===void 0||l[ip]?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,nt)){let u=i.getColumnCasing(l);if(t.invokeSource==="indexes")return{sql:n(u),params:[]};let f=l.table[we.Symbol.Schema];return{sql:l.table[ip]||f===void 0?n(l.table[we.Symbol.Name])+"."+n(u):n(f)+"."+n(l.table[we.Symbol.Name])+"."+n(u),params:[]}}if(ae(l,_n)){let u=l[_t].schema,f=l[_t].name;return{sql:u===void 0||l[_t].isAlias?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,an)){if(ae(l.value,ys))return{sql:o(c.value++,l),params:[l],typings:["none"]};let u=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(ae(u,Te))return this.buildQueryFromSourceParams([u],r);if(a)return{sql:this.mapInlineParam(u,r),params:[]};let f=["none"];if(s)f=[s(l.encoder)];return{sql:o(c.value++,u),params:[u],typings:f}}if(ae(l,ys))return{sql:o(c.value++,l),params:[l],typings:["none"]};if(ae(l,Te.Aliased)&&l.fieldAlias!==void 0)return{sql:n(l.fieldAlias),params:[]};if(ae(l,vt)){if(l._.isWith)return{sql:n(l._.alias),params:[]};return this.buildQueryFromSourceParams([new Ft("("),l._.sql,new Ft(") "),new zb(l._.alias)],r)}if(W8(l)){if(l.schema)return{sql:n(l.schema)+"."+n(l.enumName),params:[]};return{sql:n(l.enumName),params:[]}}if(cC(l)){if(l.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([l.getSQL()],r);return this.buildQueryFromSourceParams([new Ft("("),l.getSQL(),new Ft(")")],r)}if(a)return{sql:this.mapInlineParam(l,r),params:[]};return{sql:o(c.value++,l),params:[l],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 Te.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}};zb=class zb{constructor(e){this.value=e}static[J]="Name";brand;getSQL(){return new Te([this])}};oH={mapFromDriverValue:(e)=>e},sH={mapToDriverValue:(e)=>e},G5e={...oH,...sH};an=class an{constructor(e,t=sH){this.value=e,this.encoder=t}static[J]="Param";brand;getSQL(){return new Te([this])}};((e)=>{function t(){return new Te([])}e.empty=t;function r(c){return new Te(c)}e.fromList=r;function i(c){return new Te([new Ft(c)])}e.raw=i;function n(c,l){let u=[];for(let[f,p]of c.entries()){if(f>0&&l!==void 0)u.push(l);u.push(p)}return new Te(u)}e.join=n;function o(c){return new zb(c)}e.identifier=o;function s(c){return new ys(c)}e.placeholder=s;function a(c,l){return new an(c,l)}e.param=a})(U||(U={}));((e)=>{class t{constructor(r,i){this.sql=r,this.fieldAlias=i}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Te||(Te={}));ys=class ys{constructor(e){this.name=e}static[J]="Placeholder";getSQL(){return new Te([this])}};Zbe=Symbol.for("drizzle:IsDrizzleView");_n=class _n{static[J]="View";[_t];[Zbe]=!0;constructor({name:e,schema:t,selectedFields:r,query:i}){this[_t]={name:e,originalName:e,schema:t,selectedFields:r,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new Te([this])}};nt.prototype.getSQL=function(){return new Te([this])};we.prototype.getSQL=function(){return new Te([this])};vt.prototype.getSQL=function(){return new Te([this])}});function lC(e,t,r){let i={},n=e.reduce((o,{path:s,field:a},c)=>{let l;if(ae(a,nt))l=a;else if(ae(a,Te))l=a.decoder;else if(ae(a,vt))l=a._.sql.decoder;else l=a.sql.decoder;let u=o;for(let[f,p]of s.entries())if(f<s.length-1){if(!(p in u))u[p]={};u=u[p]}else{let m=t[c],y=u[p]=m===null?null:l.mapFromDriverValue(m);if(r&&ae(a,nt)&&s.length===2){let g=s[0];if(!(g in i))i[g]=y===null?gs(a.table):!1;else if(typeof i[g]==="string"&&i[g]!==gs(a.table))i[g]=!1}}return o},{});if(r&&Object.keys(i).length>0){for(let[o,s]of Object.entries(i))if(typeof s==="string"&&!r[s])n[o]=null}return n}function kn(e,t){return Object.entries(e).reduce((r,[i,n])=>{if(typeof i!=="string")return r;let o=t?[...t,i]:[i];if(ae(n,nt)||ae(n,Te)||ae(n,Te.Aliased)||ae(n,vt))r.push({path:o,field:n});else if(ae(n,we))r.push(...kn(n[we.Symbol.Columns],o));else r.push(...kn(n,o));return r},[])}function sp(e,t){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let[n,o]of r.entries())if(o!==i[n])return!1;return!0}function Nb(e,t){let r=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,n])=>{if(ae(n,Te)||ae(n,nt))return[i,n];else return[i,new an(n,e[we.Symbol.Columns][i])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function aH(e,t){for(let r of t)for(let i of Object.getOwnPropertyNames(r.prototype)){if(i==="constructor")continue;Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(r.prototype,i)||Object.create(null))}}function Db(e){return e[we.Symbol.Columns]}function ap(e){return ae(e,vt)?e._.alias:ae(e,_n)?e[_t].name:ae(e,Te)?void 0:e[we.Symbol.IsAlias]?e[we.Symbol.Name]:e[we.Symbol.BaseName]}function Si(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function cH(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 uC;var Dr=S(()=>{Zn();ze();ur();Mn();vr();to();uC=typeof TextDecoder>"u"?null:new TextDecoder});var lH,dC,fC;var Lb=S(()=>{ze();lH=class lH{static[J]="ConsoleLogWriter";write(e){console.log(e)}};dC=class dC{static[J]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new lH}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),i=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${i}`)}};fC=class fC{static[J]="NoopLogger";logQuery(){}}});var uH,dH,pC;var fH=S(()=>{ze();vr();uH=Symbol.for("drizzle:PgInlineForeignKeys"),dH=Symbol.for("drizzle:EnableRLS");pC=class pC extends we{static[J]="PgTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:uH,EnableRLS:dH});[uH]=[];[dH]=!1;[we.Symbol.ExtraConfigBuilder]=void 0;[we.Symbol.ExtraConfigColumns]={}}});var mC,pH;var mH=S(()=>{ze();fH();mC=class mC{static[J]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new pH(e,this.columns,this.name)}};pH=class pH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[pC.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Hr(e,t){if(iH(t)&&!cC(e)&&!ae(e,an)&&!ae(e,ys)&&!ae(e,nt)&&!ae(e,we)&&!ae(e,_n))return new an(e,t);return e}function It(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" and ")),new Ft(")")])}function xi(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" or ")),new Ft(")")])}function gH(e){return U`not ${e}`}function bs(e,t){if(Array.isArray(t)){if(t.length===0)return U`false`;return U`${e} in ${t.map((r)=>Hr(r,e))}`}return U`${e} in ${Hr(t,e)}`}function Bb(e,t){if(Array.isArray(t)){if(t.length===0)return U`true`;return U`${e} not in ${t.map((r)=>Hr(r,e))}`}return U`${e} not in ${Hr(t,e)}`}function En(e){return U`${e} is null`}function SH(e){return U`${e} is not null`}function jb(e){return U`exists ${e}`}function lp(e){return U`not exists ${e}`}function xH(e,t,r){return U`${e} between ${Hr(t,e)} and ${Hr(r,e)}`}function wH(e,t,r){return U`${e} not between ${Hr(t,e)} and ${Hr(r,e)}`}function vH(e,t){return U`${e} like ${t}`}function _H(e,t){return U`${e} not like ${t}`}function kH(e,t){return U`${e} ilike ${t}`}function EH(e,t){return U`${e} not ilike ${t}`}var Qe=(e,t)=>U`${e} = ${Hr(t,e)}`,hH=(e,t)=>U`${e} <> ${Hr(t,e)}`,cp=(e,t)=>U`${e} > ${Hr(t,e)}`,yH=(e,t)=>U`${e} >= ${Hr(t,e)}`,bH=(e,t)=>U`${e} < ${Hr(t,e)}`,tu=(e,t)=>U`${e} <= ${Hr(t,e)}`;var IH=S(()=>{Zn();ze();vr();ur()});function ro(e){return U`${e} asc`}function za(e){return U`${e} desc`}var TH=S(()=>{ur()});var hC=S(()=>{IH();TH()});function $H(){return{and:It,between:xH,eq:Qe,exists:jb,gt:cp,gte:yH,ilike:kH,inArray:bs,isNull:En,isNotNull:SH,like:vH,lt:bH,lte:tu,ne:hH,not:gH,notBetween:wH,notExists:lp,notLike:_H,notIlike:EH,notInArray:Bb,or:xi,sql:U}}function CH(){return{sql:U,asc:ro,desc:za}}function RH(e,t){if(Object.keys(e).length===1&&"default"in e&&!ae(e.default,we))e=e.default;let r={},i={},n={};for(let[o,s]of Object.entries(e))if(ae(s,we)){let a=Pa(s),c=i[a];r[a]=o,n[o]={tsName:o,dbName:s[we.Symbol.Name],schema:s[we.Symbol.Schema],columns:s[we.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let u of Object.values(s[we.Symbol.Columns]))if(u.primary)n[o].primaryKey.push(u);let l=s[we.Symbol.ExtraConfigBuilder]?.(s[we.Symbol.ExtraConfigColumns]);if(l){for(let u of Object.values(l))if(ae(u,mC))n[o].primaryKey.push(...u.columns)}}else if(ae(s,AH)){let a=Pa(s.table),c=r[a],l=s.config(t(s.table)),u;for(let[f,p]of Object.entries(l))if(c){let m=n[c];if(m.relations[f]=p,u)m.primaryKey.push(...u)}else{if(!(a in i))i[a]={relations:{},primaryKey:u};i[a].relations[f]=p}}return{tables:n,tableNamesMap:r}}function Mbe(e){return function(r,i){return new Ss(e,r,i,i?.fields.reduce((n,o)=>n&&o.notNull,!0)??!1)}}function Fbe(e){return function(r,i){return new up(e,r,i)}}function OH(e,t,r){if(ae(r,Ss)&&r.config)return{fields:r.config.fields,references:r.config.references};let i=t[Pa(r.referencedTable)];if(!i)throw Error(`Table "${r.referencedTable[we.Symbol.Name]}" not found in schema`);let n=e[i];if(!n)throw Error(`Table "${i}" not found in schema`);let o=r.sourceTable,s=t[Pa(o)];if(!s)throw Error(`Table "${o[we.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(n.relations))if(r.relationName&&r!==c&&c.relationName===r.relationName||!r.relationName&&c.referencedTable===r.sourceTable)a.push(c);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${i}"`):Error(`There are multiple relations between "${i}" and "${r.sourceTable[we.Symbol.Name]}". Please specify relation name`);if(a[0]&&ae(a[0],Ss)&&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 PH(e){return{one:Mbe(e),many:Fbe(e)}}function Ub(e,t,r,i,n=(o)=>o){let o={};for(let[s,a]of i.entries())if(a.isJson){let c=t.relations[a.tsKey],l=r[s],u=typeof l==="string"?JSON.parse(l):l;o[a.tsKey]=ae(c,Ss)?u&&Ub(e,e[a.relationTableTsKey],u,a.selection,n):u.map((f)=>Ub(e,e[a.relationTableTsKey],f,a.selection,n))}else{let c=n(r[s]),l=a.field,u;if(ae(l,nt))u=l;else if(ae(l,Te))u=l.decoder;else u=l.sql.decoder;o[a.tsKey]=c===null?null:u.mapFromDriverValue(c)}return o}var gC,AH,Ss,up;var dp=S(()=>{vr();Zn();ze();mH();hC();ur();gC=class gC{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[we.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName};AH=class AH{constructor(e,t){this.table=e,this.config=t}static[J]="Relations"};Ss=class Ss extends gC{constructor(e,t,r,i){super(e,t,r?.relationName);this.config=r,this.isNullable=i}static[J]="One";withFieldName(e){let t=new Ss(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};up=class up extends gC{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[J]="Many";withFieldName(e){let t=new up(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function fp(e,t){return new Proxy(e,new Na(t,!1))}function wi(e,t){return new Proxy(e,new ru(new Proxy(e.table,new Na(t,!1))))}function yC(e,t){return new Te.Aliased(pp(e.sql,t),e.fieldAlias)}function pp(e,t){return U.join(e.queryChunks.map((r)=>{if(ae(r,nt))return wi(r,t);if(ae(r,Te))return pp(r,t);if(ae(r,Te.Aliased))return yC(r,t);return r}))}var ru,Na,Hbe;var mp=S(()=>{Zn();ze();ur();vr();to();ru=class ru{constructor(e){this.table=e}static[J]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Na=class Na{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[J]="TableAliasProxyHandler";get(e,t){if(t===we.Symbol.IsAlias)return!0;if(t===we.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===we.Symbol.OriginalName)return this.alias;if(t===_t)return{...e[_t],name:this.alias,isAlias:!0};if(t===we.Symbol.Columns){let i=e[we.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map((o)=>{n[o]=new Proxy(i[o],new ru(new Proxy(e,this)))}),n}let r=e[t];if(ae(r,nt))return new Proxy(r,new ru(new Proxy(e,this)));return r}};Hbe=class Hbe{constructor(e){this.alias=e}static[J]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return fp(e.sourceTable,this.alias);return e[t]}}});var bt;var Da=S(()=>{mp();Zn();ze();ur();Mn();to();bt=class bt{static[J]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===_t)return{...e[_t],selectedFields:new Proxy(e[_t].selectedFields,this)};if(typeof t==="symbol")return e[t];let i=(ae(e,vt)?e._.selectedFields:ae(e,_n)?e[_t].selectedFields:e)[t];if(ae(i,Te.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;let n=i.clone();return n.isSelectionField=!0,n}if(ae(i,Te)){if(this.config.sqlBehavior==="sql")return i;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(ae(i,nt)){if(this.config.alias)return new Proxy(i,new ru(new Proxy(i.table,new Na(this.config.alias,this.config.replaceOriginalName??!1))));return i}if(typeof i!=="object"||i===null)return i;return new Proxy(i,new bt(this.config))}}});var Lr;var no=S(()=>{ze();Lr=class Lr{static[J]="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 bC,zH;var SC=S(()=>{ze();Xl();bC=class bC{static[J]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 zH(e,this)}};zH=class zH{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function xC(e,t){return`${e[wr]}_${t.join("_")}_unique`}var NH,Kbe,DH;var wC=S(()=>{ze();Xl();NH=class NH{constructor(e,t){this.name=t,this.columns=e}static[J]="SQLiteUniqueConstraintBuilder";columns;build(e){return new DH(e,this.columns,this.name)}};Kbe=class Kbe{static[J]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new NH(e,this.name)}};DH=class DH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??xC(this.table,this.columns.map((i)=>i.name))}static[J]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Qt,Tt;var xs=S(()=>{Cb();Zn();ze();SC();wC();Qt=class Qt extends tp{static[J]="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:i})=>((n,o)=>{let s=new bC(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)})(r,i))}};Tt=class Tt extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=xC(e,[t.name]);super(e,t);this.table=e}static[J]="SQLiteColumn"}});function MH(e,t){let{name:r,config:i}=Si(e,t);if(i?.mode==="json")return new jH(r);if(i?.mode==="bigint")return new LH(r);return new qH(r)}var LH,BH,jH,UH,qH,ZH;var vC=S(()=>{ze();Dr();xs();LH=class LH extends Qt{static[J]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new BH(e,this.config)}};BH=class BH extends Tt{static[J]="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(uC.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};jH=class jH extends Qt{static[J]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new UH(e,this.config)}};UH=class UH extends Tt{static[J]="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(uC.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};qH=class qH extends Qt{static[J]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new ZH(e,this.config)}};ZH=class ZH extends Tt{static[J]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function KH(e){return(t,r)=>{let{name:i,config:n}=Si(t,r);return new FH(i,n,e)}}var FH,HH;var _C=S(()=>{ze();Dr();xs();FH=class FH extends Qt{static[J]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new HH(e,this.config)}};HH=class HH extends Tt{static[J]="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 _r(e,t){let{name:r,config:i}=Si(e,t);if(i?.mode==="timestamp"||i?.mode==="timestamp_ms")return new WH(r,i.mode);if(i?.mode==="boolean")return new QH(r,i.mode);return new JH(r)}var qb,Zb,JH,VH,WH,GH,QH,YH;var kC=S(()=>{ze();ur();Dr();xs();qb=class qb extends Qt{static[J]="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()}};Zb=class Zb extends Tt{static[J]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};JH=class JH extends qb{static[J]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new VH(e,this.config)}};VH=class VH extends Zb{static[J]="SQLiteInteger"};WH=class WH extends qb{static[J]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(U`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new GH(e,this.config)}};GH=class GH extends Zb{static[J]="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}};QH=class QH extends qb{static[J]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new YH(e,this.config)}};YH=class YH extends Zb{static[J]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function oK(e,t){let{name:r,config:i}=Si(e,t),n=i?.mode;return n==="number"?new tK(r):n==="bigint"?new nK(r):new XH(r)}var XH,eK,tK,rK,nK,iK;var EC=S(()=>{ze();Dr();xs();XH=class XH extends Qt{static[J]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new eK(e,this.config)}};eK=class eK extends Tt{static[J]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};tK=class tK extends Qt{static[J]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new rK(e,this.config)}};rK=class rK extends Tt{static[J]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};nK=class nK extends Qt{static[J]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new iK(e,this.config)}};iK=class iK extends Tt{static[J]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function cK(e){return new sK(e??"")}var sK,aK;var IC=S(()=>{ze();xs();sK=class sK extends Qt{static[J]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new aK(e,this.config)}};aK=class aK extends Tt{static[J]="SQLiteReal";getSQLType(){return"real"}}});function dr(e,t={}){let{name:r,config:i}=Si(e,t);if(i.mode==="json")return new dK(r);return new lK(r,i)}var lK,uK,dK,fK;var TC=S(()=>{ze();Dr();xs();lK=class lK extends Qt{static[J]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new uK(e,this.config)}};uK=class uK extends Tt{static[J]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};dK=class dK extends Qt{static[J]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new fK(e,this.config)}};fK=class fK extends Tt{static[J]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function pK(){return{blob:MH,customType:KH,integer:_r,numeric:oK,real:cK,text:dr}}var mK=S(()=>{vC();_C();kC();EC();IC();TC()});function Jbe(e,t,r,i,n=e){let o=new Bt(e,i,n),s=typeof t==="function"?t(pK()):t,a=Object.fromEntries(Object.entries(s).map(([l,u])=>{let f=u;f.setName(l);let p=f.build(o);return o[AC].push(...f.buildForeignKeys(p,o)),[l,p]})),c=Object.assign(o,a);if(c[we.Symbol.Columns]=a,c[we.Symbol.ExtraConfigColumns]=a,r)c[Bt.Symbol.ExtraConfigBuilder]=r;return c}var AC,Bt,hp=(e,t,r)=>Jbe(e,t,r);var io=S(()=>{ze();vr();mK();AC=Symbol.for("drizzle:SQLiteInlineForeignKeys");Bt=class Bt extends we{static[J]="SQLiteTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:AC});[we.Symbol.Columns];[AC]=[];[we.Symbol.ExtraConfigBuilder]=void 0}});var Vbe,hK;var gK=S(()=>{ze();Vbe=class Vbe{constructor(e,t){this.name=e,this.value=t}static[J]="SQLiteCheckBuilder";brand;build(e){return new hK(e,this)}};hK=class hK{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[J]="SQLiteCheck";name;value}});function La(e){return new yK(e,!1)}var yK,bK,SK;var xK=S(()=>{ze();yK=class yK{constructor(e,t){this.name=e,this.unique=t}static[J]="SQLiteIndexBuilderOn";on(...e){return new bK(this.name,e,this.unique)}};bK=class bK{static[J]="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 SK(this.config,e)}};SK=class SK{static[J]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var Wbe,wK;var vK=S(()=>{ze();io();Wbe=class Wbe{static[J]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new wK(e,this.columns,this.name)}};wK=class wK{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[Bt.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Fn(e){if(ae(e,Bt))return[`${e[we.Symbol.BaseName]}`];if(ae(e,vt))return e._.usedTables??[];if(ae(e,Te))return e.usedTables??[];return[]}var nu=S(()=>{ze();ur();Mn();vr();io()});var Mb;var _K=S(()=>{ze();no();Da();io();vr();Dr();nu();Mb=class Mb extends Lr{constructor(e,t,r,i){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:i}}static[J]="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[we.Symbol.Columns],new bt({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[Bt.Symbol.Columns]){return this.config.returning=kn(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:Fn(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 Gbe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function Qbe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,i,n)=>{let o=n===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return r+o},"")}function Ybe(e){return e}var $C;var kK=S(()=>{ze();vr();$C=class $C{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Gbe:e==="camelCase"?Qbe:Ybe}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[we.Symbol.Schema]??"public",r=e.table[we.Symbol.OriginalName],i=`${t}.${r}.${e.name}`;if(!this.cache[i])this.cacheTable(e.table);return this.cache[i]}cacheTable(e){let t=e[we.Symbol.Schema]??"public",r=e[we.Symbol.OriginalName],i=`${t}.${r}`;if(!this.cachedTables[i]){for(let n of Object.values(e[we.Symbol.Columns])){let o=`${i}.${n.name}`;this.cache[o]=this.convert(n.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var iu,oo,CC;var Fb=S(()=>{ze();iu=class iu extends Error{static[J]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};oo=class oo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
410
410
|
params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,oo),r)this.cause=r}};CC=class CC extends iu{static[J]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var EK=()=>{};var IK=()=>{};var TK=S(()=>{EK();IK()});var RC=S(()=>{hC();TK();ur()});var OC=S(()=>{vC();xs();_C();kC();EC();IC();TC()});var so;var gp=S(()=>{ze();ur();so=class so extends _n{static[J]="SQLiteViewBase"}});var ou,PC,zC;var Hb=S(()=>{mp();kK();Zn();ze();Fb();dp();RC();ur();OC();io();Mn();vr();Dr();to();gp();ou=class ou{static[J]="SQLiteDialect";casing;constructor(e){this.casing=new $C(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=[U`with `];for(let[r,i]of e.entries())if(t.push(U`${U.identifier(i._.alias)} as (${i._.sql})`),r<e.length-1)t.push(U`, `);return t.push(U` `),U.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:i,limit:n,orderBy:o}){let s=this.buildWithCTE(i),a=r?U` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,c=t?U` where ${t}`:void 0,l=this.buildOrderBy(o),u=this.buildLimit(n);return U`${s}delete from ${e}${c}${a}${l}${u}`}buildUpdateSet(e,t){let r=e[we.Symbol.Columns],i=Object.keys(r).filter((o)=>t[o]!==void 0||r[o]?.onUpdateFn!==void 0),n=i.length;return U.join(i.flatMap((o,s)=>{let a=r[o],c=a.onUpdateFn?.(),l=t[o]??(ae(c,Te)?c:U.param(c,a)),u=U`${U.identifier(this.casing.getColumnCasing(a))} = ${l}`;if(s<n-1)return[u,U.raw(", ")];return[u]}))}buildUpdateQuery({table:e,set:t,where:r,returning:i,withList:n,joins:o,from:s,limit:a,orderBy:c}){let l=this.buildWithCTE(n),u=this.buildUpdateSet(e,t),f=s&&U.join([U.raw(" from "),this.buildFromTable(s)]),p=this.buildJoins(o),m=i?U` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,y=r?U` where ${r}`:void 0,g=this.buildOrderBy(c),b=this.buildLimit(a);return U`${l}update ${e} set ${u}${f}${p}${y}${m}${g}${b}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,i=e.flatMap(({field:n},o)=>{let s=[];if(ae(n,Te.Aliased)&&n.isSelectionField)s.push(U.identifier(n.fieldAlias));else if(ae(n,Te.Aliased)||ae(n,Te)){let a=ae(n,Te.Aliased)?n.sql:n;if(t)s.push(new Te(a.queryChunks.map((c)=>{if(ae(c,nt))return U.identifier(this.casing.getColumnCasing(c));return c})));else s.push(a);if(ae(n,Te.Aliased))s.push(U` as ${U.identifier(n.fieldAlias)}`)}else if(ae(n,nt)){let a=n.table[we.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(U`cast(${U.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(U`cast(${U.identifier(a)}.${U.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(U.identifier(this.casing.getColumnCasing(n)));else s.push(U`${U.identifier(a)}.${U.identifier(this.casing.getColumnCasing(n))}`)}else if(ae(n,vt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let c=a[0][1],l=ae(c,Te)?c.decoder:ae(c,nt)?{mapFromDriverValue:(u)=>c.mapFromDriverValue(u)}:c.sql.decoder;if(l)n._.sql.decoder=l}s.push(n)}if(o<r-1)s.push(U`, `);return s});return U.join(i)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,i]of e.entries()){if(r===0)t.push(U` `);let n=i.table,o=i.on?U` on ${i.on}`:void 0;if(ae(n,Bt)){let s=n[Bt.Symbol.Name],a=n[Bt.Symbol.Schema],c=n[Bt.Symbol.OriginalName],l=s===c?void 0:i.alias;t.push(U`${U.raw(i.joinType)} join ${a?U`${U.identifier(a)}.`:void 0}${U.identifier(c)}${l&&U` ${U.identifier(l)}`}${o}`)}else t.push(U`${U.raw(i.joinType)} join ${n}${o}`);if(r<e.length-1)t.push(U` `)}return U.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?U` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,i]of e.entries())if(t.push(i),r<e.length-1)t.push(U`, `)}return t.length>0?U` order by ${U.join(t)}`:void 0}buildFromTable(e){if(ae(e,we)&&e[we.Symbol.IsAlias])return U`${U`${U.identifier(e[we.Symbol.Schema]??"")}.`.if(e[we.Symbol.Schema])}${U.identifier(e[we.Symbol.OriginalName])} ${U.identifier(e[we.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:i,having:n,table:o,joins:s,orderBy:a,groupBy:c,limit:l,offset:u,distinct:f,setOperators:p}){let m=r??kn(t);for(let P of m)if(ae(P.field,nt)&&gs(P.field.table)!==(ae(o,vt)?o._.alias:ae(o,so)?o[_t].name:ae(o,Te)?void 0:gs(o))&&!((N)=>s?.some(({alias:I})=>I===(N[we.Symbol.IsAlias]?gs(N):N[we.Symbol.BaseName])))(P.field.table)){let N=gs(P.field.table);throw Error(`Your "${P.path.join("->")}" field references a column "${N}"."${P.field.name}", but the table "${N}" is not part of the query! Did you forget to join it?`)}let y=!s||s.length===0,g=this.buildWithCTE(e),b=f?U` distinct`:void 0,_=this.buildSelection(m,{isSingleTable:y}),T=this.buildFromTable(o),A=this.buildJoins(s),z=i?U` where ${i}`:void 0,j=n?U` having ${n}`:void 0,E=[];if(c){for(let[P,N]of c.entries())if(E.push(N),P<c.length-1)E.push(U`, `)}let F=E.length>0?U` group by ${U.join(E)}`:void 0,D=this.buildOrderBy(a),H=this.buildLimit(l),X=u?U` offset ${u}`:void 0,Z=U`${g}select${b} ${_} from ${T}${A}${z}${F}${j}${D}${H}${X}`;if(p.length>0)return this.buildSetOperations(Z,p);return Z}buildSetOperations(e,t){let[r,...i]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(i.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),i)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:i,limit:n,orderBy:o,offset:s}}){let a=U`${e.getSQL()} `,c=U`${i.getSQL()}`,l;if(o&&o.length>0){let m=[];for(let y of o)if(ae(y,Tt))m.push(U.identifier(y.name));else if(ae(y,Te)){for(let g=0;g<y.queryChunks.length;g++){let b=y.queryChunks[g];if(ae(b,Tt))y.queryChunks[g]=U.identifier(this.casing.getColumnCasing(b))}m.push(U`${y}`)}else m.push(U`${y}`);l=U` order by ${U.join(m,U`, `)}`}let u=typeof n==="object"||typeof n==="number"&&n>=0?U` limit ${n}`:void 0,f=U.raw(`${t} ${r?"all ":""}`),p=s?U` offset ${s}`:void 0;return U`${a}${f}${c}${l}${u}${p}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:i,withList:n,select:o}){let s=[],a=e[we.Symbol.Columns],c=Object.entries(a).filter(([y,g])=>!g.shouldDisableInsert()),l=c.map(([,y])=>U.identifier(this.casing.getColumnCasing(y)));if(o){let y=t;if(ae(y,Te))s.push(y);else s.push(y.getSQL())}else{let y=t;s.push(U.raw("values "));for(let[g,b]of y.entries()){let _=[];for(let[T,A]of c){let z=b[T];if(z===void 0||ae(z,an)&&z.value===void 0){let j;if(A.default!==null&&A.default!==void 0)j=ae(A.default,Te)?A.default:U.param(A.default,A);else if(A.defaultFn!==void 0){let E=A.defaultFn();j=ae(E,Te)?E:U.param(E,A)}else if(!A.default&&A.onUpdateFn!==void 0){let E=A.onUpdateFn();j=ae(E,Te)?E:U.param(E,A)}else j=U`null`;_.push(j)}else _.push(z)}if(s.push(_),g<y.length-1)s.push(U`, `)}}let u=this.buildWithCTE(n),f=U.join(s),p=i?U` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,m=r?.length?U.join(r):void 0;return U`${u}insert into ${e} ${l} ${f}${m}${p}`}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:i,tableConfig:n,queryConfig:o,tableAlias:s,nestedQueryRelation:a,joinOn:c}){let l=[],u,f,p=[],m,y=[];if(o===!0)l=Object.entries(n.columns).map(([_,T])=>({dbKey:T.name,tsKey:_,field:wi(T,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let b=Object.fromEntries(Object.entries(n.columns).map(([E,F])=>[E,wi(F,s)]));if(o.where){let E=typeof o.where==="function"?o.where(b,$H()):o.where;m=E&&pp(E,s)}let _=[],T=[];if(o.columns){let E=!1;for(let[F,D]of Object.entries(o.columns)){if(D===void 0)continue;if(F in n.columns){if(!E&&D===!0)E=!0;T.push(F)}}if(T.length>0)T=E?T.filter((F)=>o.columns?.[F]===!0):Object.keys(n.columns).filter((F)=>!T.includes(F))}else T=Object.keys(n.columns);for(let E of T){let F=n.columns[E];_.push({tsKey:E,value:F})}let A=[];if(o.with)A=Object.entries(o.with).filter((E)=>!!E[1]).map(([E,F])=>({tsKey:E,queryConfig:F,relation:n.relations[E]}));let z;if(o.extras){z=typeof o.extras==="function"?o.extras(b,{sql:U}):o.extras;for(let[E,F]of Object.entries(z))_.push({tsKey:E,value:yC(F,s)})}for(let{tsKey:E,value:F}of _)l.push({dbKey:ae(F,Te.Aliased)?F.fieldAlias:n.columns[E].name,tsKey:E,field:ae(F,nt)?wi(F,s):F,relationTableTsKey:void 0,isJson:!1,selection:[]});let j=typeof o.orderBy==="function"?o.orderBy(b,CH()):o.orderBy??[];if(!Array.isArray(j))j=[j];p=j.map((E)=>{if(ae(E,nt))return wi(E,s);return pp(E,s)}),u=o.limit,f=o.offset;for(let{tsKey:E,queryConfig:F,relation:D}of A){let H=OH(t,r,D),X=Pa(D.referencedTable),Z=r[X],P=`${s}_${E}`,N=It(...H.fields.map((R,M)=>Qe(wi(H.references[M],P),wi(R,s)))),I=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[Z],tableConfig:t[Z],queryConfig:ae(D,Ss)?F===!0?{limit:1}:{...F,limit:1}:F,tableAlias:P,joinOn:N,nestedQueryRelation:D}),O=U`(${I.sql})`.as(E);l.push({dbKey:E,tsKey:E,field:O,relationTableTsKey:Z,isJson:!0,selection:I.selection})}}if(l.length===0)throw new iu({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 g;if(m=It(c,m),a){let b=U`json_array(${U.join(l.map(({field:A})=>ae(A,Tt)?U.identifier(this.casing.getColumnCasing(A)):ae(A,Te.Aliased)?A.sql:A),U`, `)})`;if(ae(a,up))b=U`coalesce(json_group_array(${b}), json_array())`;let _=[{dbKey:"data",tsKey:"data",field:b.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:l}];if(u!==void 0||f!==void 0||p.length>0)g=this.buildSelectQuery({table:fp(i,s),fields:{},fieldsFlat:[{path:[],field:U.raw("*")}],where:m,limit:u,offset:f,orderBy:p,setOperators:[]}),m=void 0,u=void 0,f=void 0,p=void 0;else g=fp(i,s);g=this.buildSelectQuery({table:ae(g,Bt)?g:new vt(g,{},s),fields:{},fieldsFlat:_.map(({field:A})=>({path:[],field:ae(A,nt)?wi(A,s):A})),joins:y,where:m,limit:u,offset:f,orderBy:p,setOperators:[]})}else g=this.buildSelectQuery({table:fp(i,s),fields:{},fieldsFlat:l.map(({field:b})=>({path:[],field:ae(b,nt)?wi(b,s):b})),joins:y,where:m,limit:u,offset:f,orderBy:p,setOperators:[]});return{tableTsKey:n.tsName,sql:g,selection:l}}};PC=class PC extends ou{static[J]="SQLiteSyncDialect";migrate(e,t,r){let i=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=U`
|
|
411
411
|
CREATE TABLE IF NOT EXISTS ${U.identifier(i)} (
|
|
412
412
|
id SERIAL PRIMARY KEY,
|
|
@@ -419,7 +419,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrac
|
|
|
419
419
|
hash text NOT NULL,
|
|
420
420
|
created_at numeric
|
|
421
421
|
)
|
|
422
|
-
`;await t.run(n);let s=(await t.values(U`SELECT id, hash, created_at FROM ${U.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let l of c.sql)await a.run(U.raw(l));await a.run(U`INSERT INTO ${U.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var NC;var AK=S(()=>{ze();NC=class NC{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Kb(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!sp(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(o)}}var Hn,$K,DC,Xbe=()=>({union:eSe,unionAll:tSe,intersect:rSe,except:nSe}),eSe,tSe,rSe,nSe;var LC=S(()=>{ze();AK();no();Da();ur();Mn();vr();Dr();to();nu();gp();Hn=class Hn{static[J]="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(ae(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ae(e,so))r=e[_t].selectedFields;else if(ae(e,Te))r={};else r=Db(e);return new DC({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};$K=class $K extends NC{static[J]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:i,dialect:n,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=i,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=ap(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Fn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=ap(t);for(let o of Fn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ae(t,Te)){let o=ae(t,vt)?t._.selectedFields:ae(t,_n)?t[_t].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new bt({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(([o])=>[o,!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(([o])=>[o,!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 i=typeof r==="function"?r(Xbe()):r;if(!sp(this.getSelectedFields(),i.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:i}),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 bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({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 bt({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 bt({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(...Fn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Fn(r.table));return new Proxy(new vt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};DC=class DC extends $K{static[J]="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=kn(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()}};aH(DC,[Lr]);eSe=Kb("union",!1),tSe=Kb("union",!0),rSe=Kb("intersect",!1),nSe=Kb("except",!1)});var Ba;var Jb=S(()=>{ze();Da();Hb();Mn();LC();Ba=class Ba{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ae(e,ou)?e:void 0,this.dialectConfig=ae(e,ou)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new np(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new PC(this.dialectConfig);return this.dialect}}});var Vb,BC;var CK=S(()=>{ze();no();ur();io();vr();Dr();nu();Jb();Vb=class Vb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="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 i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ae(s,Te)?s:new an(s,n[o])}return i});return new BC(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ba):e;if(!ae(t,Te)&&!sp(this.table[Pb],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 BC(this.table,t,this.session,this.dialect,this.withList,!0)}};BC=class BC extends Lr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[J]="SQLiteInsert";config;returning(e=this.config.table[Bt.Symbol.Columns]){return this.config.returning=kn(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(U` on conflict do nothing`);else{let t=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,r=e.where?U` where ${e.where}`:U``;this.config.onConflict.push(U` 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?U` where ${e.where}`:void 0,r=e.targetWhere?U` where ${e.targetWhere}`:void 0,i=e.setWhere?U` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,Nb(this.config.table,e.set));return this.config.onConflict.push(U` on conflict ${n}${r} do update set ${o}${t}${i}`),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:Fn(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 Wb,RK;var OK=S(()=>{ze();no();Da();io();Mn();vr();Dr();to();nu();gp();Wb=class Wb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new RK(this.table,Nb(this.table,e),this.session,this.dialect,this.withList)}};RK=class RK extends Lr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[J]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=ap(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ae(t,Bt)?t[we.Symbol.Columns]:ae(t,vt)?t._.selectedFields:ae(t,so)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:i}),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[we.Symbol.Columns],new bt({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[Bt.Symbol.Columns]){return this.config.returning=kn(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:Fn(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 jC=S(()=>{_K();CK();Jb();LC();OK()});var yp;var PK=S(()=>{ze();ur();yp=class yp extends Te{constructor(e){super(yp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=yp.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return U`(select count(*) from ${e}${U.raw(" where ").if(t)}${t})`}static buildCount(e,t){return U`select count(*) from ${e}${U.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 qC,Gb,UC;var zK=S(()=>{ze();no();dp();qC=class qC{constructor(e,t,r,i,n,o,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=i,this.table=n,this.tableConfig=o,this.dialect=s,this.session=a}static[J]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new UC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new Gb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new UC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Gb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};Gb=class Gb extends Lr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[J]="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,(i,n)=>{let o=i.map((s)=>Ub(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}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()}};UC=class UC extends Gb{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var su;var NK=S(()=>{ze();no();su=class su extends Lr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[J]="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 bp;var Qb=S(()=>{ze();Da();ur();jC();Mn();PK();zK();NK();bp=class bp{constructor(e,t,r,i){this.resultKind=e,this.dialect=t,this.session=r,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))n[o]=new qC(e,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[o],s,t,r);this.$cache={invalidate:async(o)=>{}}}static[J]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new Ba(r.dialect));return new Proxy(new np(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new yp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Wb(a,t.session,t.dialect,e)}function o(a){return new Vb(a,t.session,t.dialect,e)}function s(a){return new Mb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Wb(e,this.session,this.dialect)}$cache;insert(e){return new Vb(e,this.session,this.dialect)}delete(e){return new Mb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(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 ZC(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(o)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var DK,Sp;var MC=S(()=>{ze();DK=class DK{static[J]="Cache"};Sp=class Sp extends DK{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var LK=S(()=>{MC()});function BK(e,t){return new Proxy(e,new Na(t,!1))}var jK=S(()=>{mp()});var UK,FC,HC,KC;var JC=S(()=>{MC();ze();Fb();no();Qb();UK=class UK extends Lr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};FC=class FC{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[J]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ae(this.cache,Sp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new oo(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new oo(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new oo(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new oo(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await ZC(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new oo(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await ZC(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new oo(e,t,i)}}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 UK(()=>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)}}};HC=class HC{constructor(e){this.dialect=e}static[J]="SQLiteSession";prepareOneTimeQuery(e,t,r,i,n,o,s){return this.prepareQuery(e,t,r,i,n,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new iu({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")}};KC=class KC extends bp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new CC}}});var VC,iSe,oSe,Yb;var qK=S(()=>{ze();Da();Dr();Jb();io();gp();VC=class VC{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};iSe=class iSe extends VC{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ba);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Yb({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};oSe=class oSe extends VC{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=Db(hp(e,t))}existing(){return new Proxy(new Yb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Yb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Yb=class Yb extends so{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var Xb=S(()=>{jK();gK();OC();Qb();Hb();SC();xK();vK();jC();JC();io();wC();nu();qK()});function ZK(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function eS(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 tS,WC,MK;var GC=S(()=>{LK();ze();Lb();ur();Xb();JC();Dr();tS=class tS extends HC{constructor(e,t,r,i,n){super(t);this.client=e,this.schema=r,this.options=i,this.tx=n,this.logger=i.logger??new fC,this.cache=i.cache??new Sp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new MK(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new tS(this.client,this.dialect,this.schema,this.options,r),n=new WC("async",this.dialect,i,this.schema);try{let o=await e(n);return await r.commit(),o}catch(o){throw await r.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};WC=class WC extends KC{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new WC("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(U.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(U.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(U.raw(`rollback to savepoint ${t}`)),i}}};MK=class MK extends FC{constructor(e,t,r,i,n,o,s,a,c,l,u){super("async",c,t,i,n,o);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=l,this.customResultMapper=u,this.customResultMapper=u,this.fields=s}static[J]="LibSQLPreparedQuery";async run(e){let t=op(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:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=op(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapAllResult(u))})}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)=>ZK(r));if(this.customResultMapper)return this.customResultMapper(e,eS);return e.map((r)=>lC(this.fields,Array.prototype.slice.call(r).map((i)=>eS(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=op(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapGetResult(u))})}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 ZK(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,eS);return lC(this.fields,Array.prototype.slice.call(r).map((i)=>eS(i)),this.joinsNotNullableMap)}async values(e){let t=op(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:i})=>i)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function au(e,t={}){let r=new zC({casing:t.casing}),i;if(t.logger===!0)i=new dC;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=RH(t.schema,PH);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new tS(e,r,n,{logger:i,cache:t.cache},void 0),s=new FK("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var FK;var HK=S(()=>{ze();Lb();dp();Qb();Hb();GC();FK=class FK extends bp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function rS(...e){if(typeof e[0]==="string"){let t=Yl({url:e[0]});return au(t,e[1])}if(cH(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return au(r,i);let n=typeof t==="string"?Yl({url:t}):Yl(t);return au(n,i)}return au(e[0],e[1])}var KK=S(()=>{Y$();Dr();HK();((e)=>{function t(r){return au({},r)}e.mock=t})(rS||(rS={}))});var JK=S(()=>{KK();GC()});function VK(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function lSe(e){return e instanceof Be&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function nS(e,t){let r=Date.now()+(t.budgetMs??sSe),i=async(n)=>{if(t.isClosed())throw new Be("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!lSe(o))throw o;await t.afterRefusal?.();let s=Math.min(aSe*2**(n-1),cSe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw o;if(await new Promise((c)=>setTimeout(c,a)),t.isClosed()||Date.now()>=r)throw o;return i(n+1)}};return i(1)}function QC(e,t={}){let r=Yl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let u=function(f,p){return nS(()=>typeof f==="string"?s(f,p):s(f),l)},i=r.transaction.bind(r),n=()=>r.closed,o=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),l={isClosed:n,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};r.execute=u,r.batch=(f,p)=>nS(()=>a(f,p),l),r.migrate=(f)=>nS(()=>c(f),l),r.transaction=(f)=>nS(()=>i(f),l)}return r}function iS(e){let{url:t,schema:r}=e,i=VK(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?QC({url:t,authToken:i},n):QC({url:t},n);return{db:rS(o,{schema:r}),client:o,url:t}}async function oS(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var sSe=5000,aSe=5,cSe=40;var YC=S(()=>{Y$();JK()});var WK=S(()=>{p$();YC()});var XC=S(()=>{YC();WK()});var ne,pt;var eR=S(()=>{Xb();Rf();ne=hp("job_queue",{id:dr("id").primaryKey().$defaultFn(()=>Gi()),type:dr("type").notNull(),data:dr("data").notNull(),result:dr("result",{mode:"json"}),progress:dr("progress",{mode:"json"}).$type(),source:dr("source"),metadata:dr("metadata",{mode:"json"}).$type().notNull(),status:dr("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:_r("priority").notNull().default(0),retryCount:_r("retryCount").notNull().default(0),maxRetries:_r("maxRetries").notNull().default(3),lastError:dr("lastError"),createdAt:_r("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:_r("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:_r("startedAt"),completedAt:_r("completedAt"),attemptId:dr("attemptId"),workerSlotId:dr("workerSlotId"),workerSessionId:dr("workerSessionId"),leaseExpiresAt:_r("leaseExpiresAt"),attemptHeartbeatAt:_r("attemptHeartbeatAt"),runtimeUpdatedAt:_r("runtimeUpdatedAt")},(e)=>({queueReadyIdx:La("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:La("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:La("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:La("idx_job_queue_source").on(e.source)})),pt=hp("job_worker_sessions",{slotId:dr("slotId").primaryKey(),sessionId:dr("sessionId").notNull().unique(),startedAt:_r("startedAt").notNull(),heartbeatAt:_r("heartbeatAt").notNull(),expiresAt:_r("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:La("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:La("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function GK(e){return iS({url:e.url,schema:{jobQueue:ne,jobWorkerSessions:pt},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var QK=S(()=>{XC();eR()});class tR{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)}}var YK=S(()=>{mp();Cb();Zn();ze();Fb();Lb();no();dp();RC();Mn();vr();Dr();to()});class rR{tails=new Map;async run(e,t){let r=this.tails.get(e),i=()=>{},n=new Promise((o)=>{i=o});this.tails.set(e,n),await r;try{return await t()}finally{if(i(),this.tails.get(e)===n)this.tails.delete(e)}}}class nR{findDuplicate(e,t,r){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,r).sort((o,s)=>s.createdAt-o.createdAt||s.id.localeCompare(o.id)),n=i.find((o)=>o.status===Me.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let i=uSe.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var uSe;var XK=S(()=>{Ae();ss();uSe=d.looseObject({deduplicationKey:d.string().optional()})});class iR{db;transactionClient;databaseUrl;logger;deduplicator=new nR;writeRetryBudgetMs;constructor(e,t,r,i,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??dSe}async insert(e){await this.write("insert",async()=>this.db.insert(ne).values(e))}async enqueueAtomic(e){return hSe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let i=await this.runEnqueueTransaction(e,t,r);if(i.retry)return this.attemptEnqueue(e,t,r+1);return i.decision}async runEnqueueTransaction(e,t,r){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type),f=this.deduplicator.findDuplicate(u,a,o);if(!f)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:f.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),f.id,f.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${f.id}`);return{kind:"coalesced",jobId:f.id}}await c();let p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Me.FAILED,"Replaced by newer job",p,p,f.id,Me.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${f.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:f.id}}async getActiveDeduplicationCandidates(e,t){return(await e.execute({sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Me.PENDING,Me.PROCESSING]})).rows.map((i)=>this.parseDeduplicationCandidate(i))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==Me.PENDING&&r!==Me.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let o=JSON.parse(n);return{id:t,status:r,createdAt:Number(i),metadata: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`\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]})).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,i,n){let o=Math.min(fSe*2**(i-1),pSe),s=o/2+Math.random()*(o/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,i,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,i,n=Date.now()+this.writeRetryBudgetMs,o=1){try{return await r()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,n,o,s),this.retryOnConflict(e,t,r,i,n,o+1)}}transactionConflictError(e,t,r,i){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:i});let n=t.strategy??"none",o=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: ${o})`,{cause:i})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let i=new Set;for(let n=r;n!==void 0&&!i.has(n);){if(i.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):"",i=at(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),i=os){let n=r+i;await this.write("start worker session",async()=>this.db.insert(pt).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:pt.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}}))}async heartbeatWorkerSession(e,t,r=Date.now(),i=os){return(await this.write("heartbeat worker session",async()=>this.db.update(pt).set({heartbeatAt:r,expiresAt:r+i}).where(It(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(pt).where(It(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.write("complete",async()=>this.db.update(ne).set({status:Me.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(ne).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(ne).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(ne).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:ne.retryCount,maxRetries:ne.maxRetries,type:ne.type,scheduledFor:ne.scheduledFor,startedAt:ne.startedAt,runtimeUpdatedAt:ne.runtimeUpdatedAt}).from(ne).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.write("fail",async()=>this.db.update(ne).set({status:s?Me.PENDING:Me.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(It(this.attemptWriteGuard(e,r),Qe(ne.retryCount,o.retryCount))).returning({id:ne.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.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 i=(await this.write("retire unowned job",async()=>this.db.update(ne).set({status:Me.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(It(Qe(ne.id,e.jobId),Qe(ne.type,e.expectedType),xi(Qe(ne.status,Me.PENDING),Qe(ne.status,Me.PROCESSING)),En(ne.attemptId),En(ne.workerSlotId),En(ne.workerSessionId),En(ne.leaseExpiresAt),En(ne.attemptHeartbeatAt),En(ne.progress),En(ne.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(ne).where(Qe(ne.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(ne).where(U`json_extract(${ne.metadata}, '$.rootJobId') = ${e}`).orderBy(ro(ne.createdAt),ro(ne.id))}async getStatusByEntityId(e){return(await this.db.select().from(ne).where(U`json_extract(${ne.data}, '$.id') = ${e}`).orderBy(za(ne.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:ne.type,status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.type,ne.status),this.db.select({oldestPendingAt:U`min(case when ${ne.status} = ${Me.PENDING} then ${ne.createdAt} end)`,duePending:U`coalesce(sum(case when ${ne.status} = ${Me.PENDING} and ${ne.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:U`min(case when ${ne.status} = ${Me.PENDING} and ${ne.scheduledFor} <= ${e} then ${ne.scheduledFor} end)`,latestClaimAt:U`max(${ne.startedAt})`,oldestProcessingAt:U`min(case when ${ne.status} = ${Me.PROCESSING} then ${ne.startedAt} end)`,staleLeaseCount:U`coalesce(sum(case when ${ne.status} = ${Me.PROCESSING} and ${ne.leaseExpiresAt} is not null and ${ne.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(ne),this.db.select({total:U`count(*)`,active:U`coalesce(sum(case when ${pt.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:U`coalesce(sum(case when ${pt.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:U`max(${pt.heartbeatAt})`}).from(pt)]),n={pending:0,processing:0,completed:0,failed:0},o=t.map((l)=>{let u=Number(l.count);return n[l.status]+=u,{type:l.type,status:l.status,count:u}}),s=r[0],a=i[0],c=(l)=>l===null||l===void 0?null:Math.max(0,e-Number(l));return{totals:n,byType:o,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:c(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=mSe.parse(t);if(r===0)return[];return(await this.db.select().from(ne).where(U`(${ne.runtimeUpdatedAt}, ${ne.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(ro(ne.runtimeUpdatedAt),ro(ne.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(ne).where(It(xi(Qe(ne.status,Me.COMPLETED),Qe(ne.status,Me.FAILED)),tu(ne.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=xi(Qe(ne.status,Me.PENDING),Qe(ne.status,Me.PROCESSING)),r=e&&e.length>0?It(t,bs(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(za(ne.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?bs(ne.type,e):void 0;return this.db.select().from(ne).where(r).orderBy(za(ne.createdAt)).limit(t)}async getFailedJobs(e){let t=Qe(ne.status,Me.FAILED),r=e&&e.length>0?It(t,bs(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(za(ne.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s,exclusiveTypes:a=[]}=e,c=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,i),Qe(pt.sessionId,n),cp(pt.expiresAt,t))),l=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,ne.workerSlotId),Qe(pt.sessionId,ne.workerSessionId))),u=It(Qe(ne.status,Me.PROCESSING),xi(En(ne.attemptId),lp(l),tu(ne.leaseExpiresAt,t))),f=BK(ne,"running"),p=this.db.select({id:f.id}).from(f).where(It(Qe(f.type,ne.type),Qe(f.status,Me.PROCESSING),cp(f.leaseExpiresAt,t),U`${f.id} <> ${ne.id}`)),m=a.length===0?void 0:xi(Bb(ne.type,[...a]),lp(p)),y=U`${ne.status} = ${Me.PROCESSING} AND ${ne.retryCount} + 1 > ${ne.maxRetries}`,g=this.db.select({id:ne.id}).from(ne).where(It(bs(ne.type,s),m,xi(It(Qe(ne.status,Me.PENDING),tu(ne.scheduledFor,t)),u))).orderBy(ro(ne.priority),ro(ne.createdAt)).limit(1),_=(await this.write("claim",async()=>this.db.update(ne).set({status:U`CASE WHEN ${y} THEN ${Me.FAILED} ELSE ${Me.PROCESSING} END`,retryCount:U`CASE WHEN ${ne.status} = ${Me.PROCESSING} THEN ${ne.retryCount} + 1 ELSE ${ne.retryCount} END`,lastError:U`CASE WHEN ${ne.status} = ${Me.PROCESSING} THEN 'Attempt lease expired' ELSE ${ne.lastError} END`,startedAt:U`CASE WHEN ${y} THEN ${ne.startedAt} ELSE ${t} END`,completedAt:U`CASE WHEN ${y} THEN ${t} ELSE NULL END`,attemptId:U`CASE WHEN ${y} THEN ${ne.attemptId} ELSE ${r} END`,workerSlotId:U`CASE WHEN ${y} THEN ${ne.workerSlotId} ELSE ${i} END`,workerSessionId:U`CASE WHEN ${y} THEN ${ne.workerSessionId} ELSE ${n} END`,leaseExpiresAt:U`CASE WHEN ${y} THEN ${ne.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:U`CASE WHEN ${y} THEN ${ne.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:U`CASE WHEN ${y} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${ne.runtimeUpdatedAt} END`}).where(It(bs(ne.id,g),jb(c))).returning()))[0];if(_?.status!==Me.PROCESSING)return null;return this.logger.debug("Job claimed",{jobId:_.id,attemptId:_.attemptId,workerSlotId:i,workerSessionId:n}),_}nextRuntimeUpdatedAt(e){return U`max(${e}, coalesce((select max(${ne.runtimeUpdatedAt}) from ${ne}), 0) + 1)`}attemptWriteGuard(e,t){return t?It(Qe(ne.id,e),Qe(ne.status,Me.PROCESSING),Qe(ne.attemptId,t)):It(Qe(ne.id,e),En(ne.attemptId),xi(Qe(ne.status,Me.PENDING),Qe(ne.status,Me.PROCESSING)))}}var dSe=2000,fSe=5,pSe=40,mSe,hSe;var eJ=S(()=>{YK();Xb();eR();Ae();ss();Pf();XK();mSe=d.number().int().min(0).max(1000),hSe=new rR});import{AsyncLocalStorage as gSe}from"async_hooks";class xp{storage=new gSe;static createFresh(){return new xp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=_o.parse(e),n=ySe(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function ySe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var oR=S(()=>{ti()});class wp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Gi()}`;directWorkerSessionId=Gi();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new wp(e,t??on.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=GK(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??xp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new tR(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new iR(i,n,o,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 oS(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:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Gi(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:f,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:Me.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...p,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:l},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},y,g=()=>{y?.rollback(),y=void 0};try{let b=await this.repository.enqueueAtomic({jobData:m,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{y=await this.projectionAdmission?.reserveJobAdmission(l)},onInsertRollback:g});if(y?.commit(),y=void 0,b.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:b.jobId});else if(b.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:b.jobId});else{if(b.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:b.replacedJobId});this.logger.debug("Job enqueued",{id:b.jobId,type:t,priority:m.priority,rootJobId:m.metadata.rootJobId})}return b.jobId}catch(b){throw g(),this.logger.error("Failed to enqueue job",{type:t,error:at(b)}),b}}createJobProvenance(e,t,r){let i=this.operationContext.current(),n=r?.metadata.provenance??i?.provenance,o=n?.rootJobId===t?n:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,a=r?.projection,c=a?[...o?.projectionLineage??[],a.id]:[...o?.projectionLineage??[]],l=a?.id??o?.projectionId;return _o.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let r=e??await this.getDirectClaimOptions(),i=Date.now(),n=await this.repository.claimNextReady({...r,now:i,attemptId:Gi(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!n)return null;return this.logger.debug("Job dequeued",{id:n.id,type:n.type,priority:n.priority,retryCount:n.retryCount,attemptId:n.attemptId,workerSlotId:n.workerSlotId,workerSessionId:n.workerSessionId}),n}async startWorkerSession(e,t,r=os){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=os){return this.repository.heartbeatWorkerSession(e,t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(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)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),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,i=Date.now()+(e.timeoutMs??30000),n=async(o)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?o??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(c)};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 tJ=S(()=>{Rf();p$();Pf();ss();XC();QK();eJ();ti();oR()});var sR=()=>{};var rJ=S(()=>{Rf();ss();Pf();ss();sR();oR()});var nJ=S(()=>{ss();sR()});var q7e;var iJ=S(()=>{ti();Ae();Of();q7e=d.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},d.record(d.string(),d.unknown()))});var F7e;var oJ=S(()=>{Ae();F7e=d.record(d.string(),d.unknown())});var sJ=S(()=>{ti();Rf()});var aJ=S(()=>{tJ();rJ();nJ();iJ();oJ();Pf();ss();Of();sJ()});var aR={};Ht(aR,{LEGACY_PROJECTION_JOB_TYPES:()=>lJ,LEGACY_PROJECTION_RETIREMENT_REASON:()=>dJ,legacyProjectionJobTypeSchema:()=>uJ,retireLegacyProjectionJob:()=>TSe});import{existsSync as kSe}from"fs";import{resolve as ESe}from"path";function cJ(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 ISe(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 TSe(e){let t=ESe(e.databasePath);if(!kSe(t))throw Error(`Job database does not exist: ${t}`);let r=uJ.parse(e.jobType),i=wp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(ISe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:cJ(n),retired:!1}}let o=`retire:${n.id}`;if(e.confirmation!==o)throw Error(`Refusing to retire ${n.id}; expected --confirm ${o}`);let s=await i.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:dJ,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:cJ(s),retired:!0}}finally{i.close()}}var lJ,uJ,dJ="Retired legacy projection job superseded by scheduler-owned projections";var cR=S(()=>{aJ();Ae();lJ=["conversation-memory:project","skill:project","swot:derive","topic:project"],uJ=d.enum(lJ)});function Yt(e,t,r,i,n){return pJ.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function uR(e){return _p.parse(structuredClone(RSe[e]))}function kp(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 aS(e,t={}){let r=t.fetchImpl??fetch,i=t.now??(()=>new Date),n=t.timeoutMs??20000,o=i(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),lR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:c.ok})}catch(c){return lR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:OSe(c)})}finally{clearTimeout(a)}}async function dR(e,t){let r=_p.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${sS(c)}`}if(!n)for(let c of r.phases)try{let l=mJ.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=sS(l);i.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:u}),n=`${c.id}: ${u}`;break}}finally{try{if(s=hJ.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=sS(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=gJ.parse(await t.stopMonitoring())}catch(c){let l=sS(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=bJ(a,r.maximumExternalAiCalls??0),yJ.parse({profile:r.profile,success:n===void 0&&i.length===r.phases.length&&s.success,baseline:o,phases:i,cleanup:s,metrics:a,...n?{failure:n}:{}})}function bJ(e,t=0){let r=e.health.find((o)=>!o.ok);if(r)return`health: ${r.endpoint} unavailable`;let i=e.externalAiCalls??0;if(i>t)return t===0?`external AI: observed ${i} call(s)`:`external AI: observed ${i} 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 OSe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function sS(e){return at(e)}var vp,fJ,pJ,_p,ASe,lR,$Se,mJ,hJ,CSe,gJ,yJ,RSe;var cS=S(()=>{Ae();vp=d.enum(["regression","load","stress"]),fJ=d.enum(["add","update","rename","delete"]),pJ=d.object({id:d.string().min(1),operation:fJ,count:d.number().int().positive().max(700),targetProbeCount:d.number().int().min(0).max(700),settleMs:d.number().int().nonnegative().max(300000)}),_p=d.object({profile:vp,maximumProbeCount:d.number().int().positive().max(700),maximumExternalAiCalls:d.number().int().nonnegative().max(1e4).optional(),phases:d.array(pJ).min(1)}),ASe=d.object({entities:d.number().int().nonnegative(),notes:d.number().int().nonnegative(),version:d.string().min(1)}),lR=d.object({timestamp:d.iso.datetime(),endpoint:d.string().startsWith("/"),status:d.number().int().nonnegative(),durationMs:d.number().nonnegative(),ok:d.boolean(),error:d.string().optional()}),$Se=d.object({timestamp:d.iso.datetime(),cpuPercent:d.number().nonnegative(),memoryPercent:d.number().nonnegative(),pids:d.number().int().nonnegative()}),mJ=d.object({id:d.string().min(1),operation:fJ,count:d.number().int().positive(),success:d.boolean(),commitLatencyMs:d.number().nonnegative().optional(),persistenceLatencyMs:d.number().nonnegative().optional(),error:d.string().optional()}),hJ=d.object({success:d.boolean(),probesRemaining:d.number().int().nonnegative(),finalEntities:d.number().int().nonnegative().optional(),finalNotes:d.number().int().nonnegative().optional(),contentTreeRestored:d.boolean().optional(),error:d.string().optional()}),CSe=d.object({status:d.string(),restartCount:d.number().int().nonnegative(),oomKilled:d.boolean()}),gJ=d.object({health:d.array(lR),runtime:d.array($Se),externalAiCalls:d.number().int().nonnegative().optional(),container:CSe.optional()}),yJ=d.object({profile:vp,success:d.boolean(),baseline:ASe,phases:d.array(mJ),cleanup:hJ,metrics:gJ,failure:d.string().optional()}),RSe={regression:{profile:"regression",maximumProbeCount:20,phases:[Yt("add20","add",20,20,0),Yt("update20","update",20,20,30000),Yt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("update350a","update",350,350,45000),Yt("rename100","rename",100,350,45000),Yt("update350b","update",350,350,45000),Yt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("add700","add",350,700,0),Yt("update700a","update",700,700,45000),Yt("rename200","rename",200,700,45000),Yt("update700b","update",700,700,45000),Yt("delete700","delete",700,0,150000)]}}});import{spawn as PSe}from"child_process";async function SJ(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw vi(t,r,n);return n}function vi(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var ao=async(e,t,r={})=>new Promise((i,n)=>{let o=PSe(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var Ep=()=>{};class cu{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,i){let n=new cu(e,r,i);return await SJ(e,"git",["-c","credential.helper=","-c",`credential.helper=${xJ}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",xJ]),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 vi("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 xJ='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var wJ=S(()=>{Ep()});function Ip(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class fR{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#i=!0;#o;#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 aS(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#i=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#o=Promise.all([this.#f(),this.#m()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#i=!0})}async stop(){this.#i=!0,await this.#o}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let i=this.#e.now().getTime();while(this.#e.now().getTime()-i<r){let n=await this.fetchHealthPayload();if(this.#d(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let i=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-i<r){let o=await this.fetchHealthPayload();if(this.#d(o,e,t)){if(n+=1,n===2)return o}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let i=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await i.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:i.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:i.ok}),!i.ok)return;return zSe.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||Ip(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await aS(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#m(){while(!this.#i){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var zSe;var vJ=S(()=>{Ae();cS();zSe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),app:d.object({version:d.string(),entities:d.number().int().nonnegative(),entityCounts:d.array(d.object({entityType:d.string(),count:d.number().int().nonnegative()})).default([])})})});var lS={};Ht(lS,{applyDirectorySyncStressPhase:()=>$J,cleanupDirectorySyncStress:()=>IJ,listProbeFiles:()=>ja,parseStressRuntimeSample:()=>CJ,removeProbeFiles:()=>SR,runDeployedDirectorySyncStress:()=>kJ,runStressCommand:()=>ao,verifyDirectorySyncStressAccess:()=>EJ});import{chmod as NSe,mkdir as mR,mkdtemp as hR,readFile as DSe,readdir as LSe,rename as BSe,rm as Ap,writeFile as Kn}from"fs/promises";import{tmpdir as gR}from"os";import{join as St,resolve as yR}from"path";async function kJ(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=xR(r),n=yR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",i));await mR(n,{recursive:!0});let{pilot:o,user:s}=await bR(e.rootDir,e.handle);kp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=vp.parse(e.profile),c=e.plan?_p.parse(e.plan):uR(a);if(c.profile!==a)throw Error(`Directory-sync stress plan profile ${c.profile} does not match requested profile ${a}`);if((c.maximumExternalAiCalls??0)===0)AJ(s);let l=jSe.parse(e.env??process.env),u=new TJ({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??ao,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),f;try{f=await dR(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:f};return await FSe(p),p}async function EJ(e){let r=(e.now??(()=>new Date))().toISOString(),i=xR(r),n=yR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`access-check-${i}`));await mR(n,{recursive:!0});let{pilot:o,user:s}=await bR(e.rootDir,e.handle);kp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),AJ(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await hR(St(gR(),"brains-ops-directory-sync-access-check-"));try{let l=await cu.clone(e.commandRunner??ao,`${o.githubOrg}/${s.contentRepo}`,St(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let f={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Kn(St(n,"access-check.json"),`${JSON.stringify(f,null,2)}
|
|
422
|
+
`;await t.run(n);let s=(await t.values(U`SELECT id, hash, created_at FROM ${U.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let l of c.sql)await a.run(U.raw(l));await a.run(U`INSERT INTO ${U.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var NC;var AK=S(()=>{ze();NC=class NC{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Kb(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!sp(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(o)}}var Hn,$K,DC,Xbe=()=>({union:eSe,unionAll:tSe,intersect:rSe,except:nSe}),eSe,tSe,rSe,nSe;var LC=S(()=>{ze();AK();no();Da();ur();Mn();vr();Dr();to();nu();gp();Hn=class Hn{static[J]="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(ae(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ae(e,so))r=e[_t].selectedFields;else if(ae(e,Te))r={};else r=Db(e);return new DC({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};$K=class $K extends NC{static[J]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:i,dialect:n,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=i,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=ap(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Fn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=ap(t);for(let o of Fn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ae(t,Te)){let o=ae(t,vt)?t._.selectedFields:ae(t,_n)?t[_t].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new bt({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(([o])=>[o,!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(([o])=>[o,!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 i=typeof r==="function"?r(Xbe()):r;if(!sp(this.getSelectedFields(),i.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:i}),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 bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({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 bt({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 bt({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(...Fn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Fn(r.table));return new Proxy(new vt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};DC=class DC extends $K{static[J]="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=kn(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()}};aH(DC,[Lr]);eSe=Kb("union",!1),tSe=Kb("union",!0),rSe=Kb("intersect",!1),nSe=Kb("except",!1)});var Ba;var Jb=S(()=>{ze();Da();Hb();Mn();LC();Ba=class Ba{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ae(e,ou)?e:void 0,this.dialectConfig=ae(e,ou)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new np(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new PC(this.dialectConfig);return this.dialect}}});var Vb,BC;var CK=S(()=>{ze();no();ur();io();vr();Dr();nu();Jb();Vb=class Vb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="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 i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ae(s,Te)?s:new an(s,n[o])}return i});return new BC(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ba):e;if(!ae(t,Te)&&!sp(this.table[Pb],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 BC(this.table,t,this.session,this.dialect,this.withList,!0)}};BC=class BC extends Lr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[J]="SQLiteInsert";config;returning(e=this.config.table[Bt.Symbol.Columns]){return this.config.returning=kn(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(U` on conflict do nothing`);else{let t=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,r=e.where?U` where ${e.where}`:U``;this.config.onConflict.push(U` 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?U` where ${e.where}`:void 0,r=e.targetWhere?U` where ${e.targetWhere}`:void 0,i=e.setWhere?U` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,Nb(this.config.table,e.set));return this.config.onConflict.push(U` on conflict ${n}${r} do update set ${o}${t}${i}`),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:Fn(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 Wb,RK;var OK=S(()=>{ze();no();Da();io();Mn();vr();Dr();to();nu();gp();Wb=class Wb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new RK(this.table,Nb(this.table,e),this.session,this.dialect,this.withList)}};RK=class RK extends Lr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[J]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=ap(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ae(t,Bt)?t[we.Symbol.Columns]:ae(t,vt)?t._.selectedFields:ae(t,so)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:i}),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[we.Symbol.Columns],new bt({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[Bt.Symbol.Columns]){return this.config.returning=kn(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:Fn(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 jC=S(()=>{_K();CK();Jb();LC();OK()});var yp;var PK=S(()=>{ze();ur();yp=class yp extends Te{constructor(e){super(yp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=yp.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return U`(select count(*) from ${e}${U.raw(" where ").if(t)}${t})`}static buildCount(e,t){return U`select count(*) from ${e}${U.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 qC,Gb,UC;var zK=S(()=>{ze();no();dp();qC=class qC{constructor(e,t,r,i,n,o,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=i,this.table=n,this.tableConfig=o,this.dialect=s,this.session=a}static[J]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new UC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new Gb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new UC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Gb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};Gb=class Gb extends Lr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[J]="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,(i,n)=>{let o=i.map((s)=>Ub(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}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()}};UC=class UC extends Gb{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var su;var NK=S(()=>{ze();no();su=class su extends Lr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[J]="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 bp;var Qb=S(()=>{ze();Da();ur();jC();Mn();PK();zK();NK();bp=class bp{constructor(e,t,r,i){this.resultKind=e,this.dialect=t,this.session=r,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))n[o]=new qC(e,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[o],s,t,r);this.$cache={invalidate:async(o)=>{}}}static[J]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new Ba(r.dialect));return new Proxy(new np(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new yp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Wb(a,t.session,t.dialect,e)}function o(a){return new Vb(a,t.session,t.dialect,e)}function s(a){return new Mb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Wb(e,this.session,this.dialect)}$cache;insert(e){return new Vb(e,this.session,this.dialect)}delete(e){return new Mb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(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 ZC(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(o)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var DK,Sp;var MC=S(()=>{ze();DK=class DK{static[J]="Cache"};Sp=class Sp extends DK{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var LK=S(()=>{MC()});function BK(e,t){return new Proxy(e,new Na(t,!1))}var jK=S(()=>{mp()});var UK,FC,HC,KC;var JC=S(()=>{MC();ze();Fb();no();Qb();UK=class UK extends Lr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};FC=class FC{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[J]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ae(this.cache,Sp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new oo(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new oo(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new oo(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new oo(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await ZC(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new oo(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await ZC(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new oo(e,t,i)}}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 UK(()=>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)}}};HC=class HC{constructor(e){this.dialect=e}static[J]="SQLiteSession";prepareOneTimeQuery(e,t,r,i,n,o,s){return this.prepareQuery(e,t,r,i,n,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new iu({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")}};KC=class KC extends bp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new CC}}});var VC,iSe,oSe,Yb;var qK=S(()=>{ze();Da();Dr();Jb();io();gp();VC=class VC{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};iSe=class iSe extends VC{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ba);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Yb({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};oSe=class oSe extends VC{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=Db(hp(e,t))}existing(){return new Proxy(new Yb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Yb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Yb=class Yb extends so{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var Xb=S(()=>{jK();gK();OC();Qb();Hb();SC();xK();vK();jC();JC();io();wC();nu();qK()});function ZK(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function eS(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 tS,WC,MK;var GC=S(()=>{LK();ze();Lb();ur();Xb();JC();Dr();tS=class tS extends HC{constructor(e,t,r,i,n){super(t);this.client=e,this.schema=r,this.options=i,this.tx=n,this.logger=i.logger??new fC,this.cache=i.cache??new Sp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new MK(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new tS(this.client,this.dialect,this.schema,this.options,r),n=new WC("async",this.dialect,i,this.schema);try{let o=await e(n);return await r.commit(),o}catch(o){throw await r.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};WC=class WC extends KC{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new WC("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(U.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(U.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(U.raw(`rollback to savepoint ${t}`)),i}}};MK=class MK extends FC{constructor(e,t,r,i,n,o,s,a,c,l,u){super("async",c,t,i,n,o);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=l,this.customResultMapper=u,this.customResultMapper=u,this.fields=s}static[J]="LibSQLPreparedQuery";async run(e){let t=op(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:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=op(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapAllResult(u))})}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)=>ZK(r));if(this.customResultMapper)return this.customResultMapper(e,eS);return e.map((r)=>lC(this.fields,Array.prototype.slice.call(r).map((i)=>eS(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=op(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapGetResult(u))})}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 ZK(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,eS);return lC(this.fields,Array.prototype.slice.call(r).map((i)=>eS(i)),this.joinsNotNullableMap)}async values(e){let t=op(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:i})=>i)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function au(e,t={}){let r=new zC({casing:t.casing}),i;if(t.logger===!0)i=new dC;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=RH(t.schema,PH);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new tS(e,r,n,{logger:i,cache:t.cache},void 0),s=new FK("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var FK;var HK=S(()=>{ze();Lb();dp();Qb();Hb();GC();FK=class FK extends bp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function rS(...e){if(typeof e[0]==="string"){let t=Yl({url:e[0]});return au(t,e[1])}if(cH(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return au(r,i);let n=typeof t==="string"?Yl({url:t}):Yl(t);return au(n,i)}return au(e[0],e[1])}var KK=S(()=>{Y$();Dr();HK();((e)=>{function t(r){return au({},r)}e.mock=t})(rS||(rS={}))});var JK=S(()=>{KK();GC()});function VK(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function lSe(e){return e instanceof Be&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function nS(e,t){let r=Date.now()+(t.budgetMs??sSe),i=async(n)=>{if(t.isClosed())throw new Be("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!lSe(o))throw o;await t.afterRefusal?.();let s=Math.min(aSe*2**(n-1),cSe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw o;if(await new Promise((c)=>setTimeout(c,a)),t.isClosed()||Date.now()>=r)throw o;return i(n+1)}};return i(1)}function QC(e,t={}){let r=Yl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let u=function(f,p){return nS(()=>typeof f==="string"?s(f,p):s(f),l)},i=r.transaction.bind(r),n=()=>r.closed,o=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),l={isClosed:n,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};r.execute=u,r.batch=(f,p)=>nS(()=>a(f,p),l),r.migrate=(f)=>nS(()=>c(f),l),r.transaction=(f)=>nS(()=>i(f),l)}return r}function iS(e){let{url:t,schema:r}=e,i=VK(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?QC({url:t,authToken:i},n):QC({url:t},n);return{db:rS(o,{schema:r}),client:o,url:t}}async function oS(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var sSe=5000,aSe=5,cSe=40;var YC=S(()=>{Y$();JK()});var WK=S(()=>{p$();YC()});var XC=S(()=>{YC();WK()});var ne,pt;var eR=S(()=>{Xb();Rf();ne=hp("job_queue",{id:dr("id").primaryKey().$defaultFn(()=>Gi()),type:dr("type").notNull(),data:dr("data").notNull(),result:dr("result",{mode:"json"}),progress:dr("progress",{mode:"json"}).$type(),source:dr("source"),metadata:dr("metadata",{mode:"json"}).$type().notNull(),status:dr("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:_r("priority").notNull().default(0),retryCount:_r("retryCount").notNull().default(0),maxRetries:_r("maxRetries").notNull().default(3),lastError:dr("lastError"),createdAt:_r("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:_r("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:_r("startedAt"),completedAt:_r("completedAt"),attemptId:dr("attemptId"),workerSlotId:dr("workerSlotId"),workerSessionId:dr("workerSessionId"),leaseExpiresAt:_r("leaseExpiresAt"),attemptHeartbeatAt:_r("attemptHeartbeatAt"),runtimeUpdatedAt:_r("runtimeUpdatedAt")},(e)=>({queueReadyIdx:La("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:La("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:La("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:La("idx_job_queue_source").on(e.source)})),pt=hp("job_worker_sessions",{slotId:dr("slotId").primaryKey(),sessionId:dr("sessionId").notNull().unique(),startedAt:_r("startedAt").notNull(),heartbeatAt:_r("heartbeatAt").notNull(),expiresAt:_r("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:La("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:La("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function GK(e){return iS({url:e.url,schema:{jobQueue:ne,jobWorkerSessions:pt},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var QK=S(()=>{XC();eR()});class tR{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)}}var YK=S(()=>{mp();Cb();Zn();ze();Fb();Lb();no();dp();RC();Mn();vr();Dr();to()});class rR{tails=new Map;async run(e,t){let r=this.tails.get(e),i=()=>{},n=new Promise((o)=>{i=o});this.tails.set(e,n),await r;try{return await t()}finally{if(i(),this.tails.get(e)===n)this.tails.delete(e)}}}class nR{findDuplicate(e,t,r){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,r).sort((o,s)=>s.createdAt-o.createdAt||s.id.localeCompare(o.id)),n=i.find((o)=>o.status===Ze.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let i=uSe.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var uSe;var XK=S(()=>{Ae();ss();uSe=d.looseObject({deduplicationKey:d.string().optional()})});class iR{db;transactionClient;databaseUrl;logger;deduplicator=new nR;writeRetryBudgetMs;constructor(e,t,r,i,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??dSe}async insert(e){await this.write("insert",async()=>this.db.insert(ne).values(e))}async enqueueAtomic(e){return hSe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let i=await this.runEnqueueTransaction(e,t,r);if(i.retry)return this.attemptEnqueue(e,t,r+1);return i.decision}async runEnqueueTransaction(e,t,r){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type),f=this.deduplicator.findDuplicate(u,a,o);if(!f)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:f.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),f.id,f.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${f.id}`);return{kind:"coalesced",jobId:f.id}}await c();let p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Ze.FAILED,"Replaced by newer job",p,p,f.id,Ze.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${f.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:f.id}}async getActiveDeduplicationCandidates(e,t){return(await e.execute({sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Ze.PENDING,Ze.PROCESSING]})).rows.map((i)=>this.parseDeduplicationCandidate(i))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==Ze.PENDING&&r!==Ze.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let o=JSON.parse(n);return{id:t,status:r,createdAt:Number(i),metadata: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`\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]})).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,i,n){let o=Math.min(fSe*2**(i-1),pSe),s=o/2+Math.random()*(o/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,i,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,i,n=Date.now()+this.writeRetryBudgetMs,o=1){try{return await r()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,n,o,s),this.retryOnConflict(e,t,r,i,n,o+1)}}transactionConflictError(e,t,r,i){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:i});let n=t.strategy??"none",o=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: ${o})`,{cause:i})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let i=new Set;for(let n=r;n!==void 0&&!i.has(n);){if(i.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):"",i=at(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),i=os){let n=r+i;await this.write("start worker session",async()=>this.db.insert(pt).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:pt.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}}))}async heartbeatWorkerSession(e,t,r=Date.now(),i=os){return(await this.write("heartbeat worker session",async()=>this.db.update(pt).set({heartbeatAt:r,expiresAt:r+i}).where(It(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(pt).where(It(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.write("complete",async()=>this.db.update(ne).set({status:Ze.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(ne).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(ne).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(ne).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:ne.retryCount,maxRetries:ne.maxRetries,type:ne.type,scheduledFor:ne.scheduledFor,startedAt:ne.startedAt,runtimeUpdatedAt:ne.runtimeUpdatedAt}).from(ne).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.write("fail",async()=>this.db.update(ne).set({status:s?Ze.PENDING:Ze.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(It(this.attemptWriteGuard(e,r),Qe(ne.retryCount,o.retryCount))).returning({id:ne.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.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 i=(await this.write("retire unowned job",async()=>this.db.update(ne).set({status:Ze.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(It(Qe(ne.id,e.jobId),Qe(ne.type,e.expectedType),xi(Qe(ne.status,Ze.PENDING),Qe(ne.status,Ze.PROCESSING)),En(ne.attemptId),En(ne.workerSlotId),En(ne.workerSessionId),En(ne.leaseExpiresAt),En(ne.attemptHeartbeatAt),En(ne.progress),En(ne.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(ne).where(Qe(ne.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(ne).where(U`json_extract(${ne.metadata}, '$.rootJobId') = ${e}`).orderBy(ro(ne.createdAt),ro(ne.id))}async getStatusByEntityId(e){return(await this.db.select().from(ne).where(U`json_extract(${ne.data}, '$.id') = ${e}`).orderBy(za(ne.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:ne.type,status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.type,ne.status),this.db.select({oldestPendingAt:U`min(case when ${ne.status} = ${Ze.PENDING} then ${ne.createdAt} end)`,duePending:U`coalesce(sum(case when ${ne.status} = ${Ze.PENDING} and ${ne.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:U`min(case when ${ne.status} = ${Ze.PENDING} and ${ne.scheduledFor} <= ${e} then ${ne.scheduledFor} end)`,latestClaimAt:U`max(${ne.startedAt})`,oldestProcessingAt:U`min(case when ${ne.status} = ${Ze.PROCESSING} then ${ne.startedAt} end)`,staleLeaseCount:U`coalesce(sum(case when ${ne.status} = ${Ze.PROCESSING} and ${ne.leaseExpiresAt} is not null and ${ne.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(ne),this.db.select({total:U`count(*)`,active:U`coalesce(sum(case when ${pt.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:U`coalesce(sum(case when ${pt.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:U`max(${pt.heartbeatAt})`}).from(pt)]),n={pending:0,processing:0,completed:0,failed:0},o=t.map((l)=>{let u=Number(l.count);return n[l.status]+=u,{type:l.type,status:l.status,count:u}}),s=r[0],a=i[0],c=(l)=>l===null||l===void 0?null:Math.max(0,e-Number(l));return{totals:n,byType:o,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:c(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=mSe.parse(t);if(r===0)return[];return(await this.db.select().from(ne).where(U`(${ne.runtimeUpdatedAt}, ${ne.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(ro(ne.runtimeUpdatedAt),ro(ne.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(ne).where(It(xi(Qe(ne.status,Ze.COMPLETED),Qe(ne.status,Ze.FAILED)),tu(ne.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=xi(Qe(ne.status,Ze.PENDING),Qe(ne.status,Ze.PROCESSING)),r=e&&e.length>0?It(t,bs(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(za(ne.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?bs(ne.type,e):void 0;return this.db.select().from(ne).where(r).orderBy(za(ne.createdAt)).limit(t)}async getFailedJobs(e){let t=Qe(ne.status,Ze.FAILED),r=e&&e.length>0?It(t,bs(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(za(ne.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s,exclusiveTypes:a=[]}=e,c=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,i),Qe(pt.sessionId,n),cp(pt.expiresAt,t))),l=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,ne.workerSlotId),Qe(pt.sessionId,ne.workerSessionId))),u=It(Qe(ne.status,Ze.PROCESSING),xi(En(ne.attemptId),lp(l),tu(ne.leaseExpiresAt,t))),f=BK(ne,"running"),p=this.db.select({id:f.id}).from(f).where(It(Qe(f.type,ne.type),Qe(f.status,Ze.PROCESSING),cp(f.leaseExpiresAt,t),U`${f.id} <> ${ne.id}`)),m=a.length===0?void 0:xi(Bb(ne.type,[...a]),lp(p)),y=U`${ne.status} = ${Ze.PROCESSING} AND ${ne.retryCount} + 1 > ${ne.maxRetries}`,g=this.db.select({id:ne.id}).from(ne).where(It(bs(ne.type,s),m,xi(It(Qe(ne.status,Ze.PENDING),tu(ne.scheduledFor,t)),u))).orderBy(ro(ne.priority),ro(ne.createdAt)).limit(1),_=(await this.write("claim",async()=>this.db.update(ne).set({status:U`CASE WHEN ${y} THEN ${Ze.FAILED} ELSE ${Ze.PROCESSING} END`,retryCount:U`CASE WHEN ${ne.status} = ${Ze.PROCESSING} THEN ${ne.retryCount} + 1 ELSE ${ne.retryCount} END`,lastError:U`CASE WHEN ${ne.status} = ${Ze.PROCESSING} THEN 'Attempt lease expired' ELSE ${ne.lastError} END`,startedAt:U`CASE WHEN ${y} THEN ${ne.startedAt} ELSE ${t} END`,completedAt:U`CASE WHEN ${y} THEN ${t} ELSE NULL END`,attemptId:U`CASE WHEN ${y} THEN ${ne.attemptId} ELSE ${r} END`,workerSlotId:U`CASE WHEN ${y} THEN ${ne.workerSlotId} ELSE ${i} END`,workerSessionId:U`CASE WHEN ${y} THEN ${ne.workerSessionId} ELSE ${n} END`,leaseExpiresAt:U`CASE WHEN ${y} THEN ${ne.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:U`CASE WHEN ${y} THEN ${ne.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:U`CASE WHEN ${y} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${ne.runtimeUpdatedAt} END`}).where(It(bs(ne.id,g),jb(c))).returning()))[0];if(!_)return null;if(_.status===Ze.FAILED)return _;return this.logger.debug("Job claimed",{jobId:_.id,attemptId:_.attemptId,workerSlotId:i,workerSessionId:n}),_}nextRuntimeUpdatedAt(e){return U`max(${e}, coalesce((select max(${ne.runtimeUpdatedAt}) from ${ne}), 0) + 1)`}attemptWriteGuard(e,t){return t?It(Qe(ne.id,e),Qe(ne.status,Ze.PROCESSING),Qe(ne.attemptId,t)):It(Qe(ne.id,e),En(ne.attemptId),xi(Qe(ne.status,Ze.PENDING),Qe(ne.status,Ze.PROCESSING)))}}var dSe=2000,fSe=5,pSe=40,mSe,hSe;var eJ=S(()=>{YK();Xb();eR();Ae();ss();Pf();XK();mSe=d.number().int().min(0).max(1000),hSe=new rR});import{AsyncLocalStorage as gSe}from"async_hooks";class xp{storage=new gSe;static createFresh(){return new xp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=_o.parse(e),n=ySe(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function ySe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var oR=S(()=>{ti()});class wp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Gi()}`;directWorkerSessionId=Gi();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new wp(e,t??on.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=GK(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??xp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new tR(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new iR(i,n,o,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 oS(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:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Gi(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:f,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:Ze.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...p,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:l},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},y,g=()=>{y?.rollback(),y=void 0};try{let b=await this.repository.enqueueAtomic({jobData:m,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{y=await this.projectionAdmission?.reserveJobAdmission(l)},onInsertRollback:g});if(y?.commit(),y=void 0,b.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:b.jobId});else if(b.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:b.jobId});else{if(b.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:b.replacedJobId});this.logger.debug("Job enqueued",{id:b.jobId,type:t,priority:m.priority,rootJobId:m.metadata.rootJobId})}return b.jobId}catch(b){throw g(),this.logger.error("Failed to enqueue job",{type:t,error:at(b)}),b}}createJobProvenance(e,t,r){let i=this.operationContext.current(),n=r?.metadata.provenance??i?.provenance,o=n?.rootJobId===t?n:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,a=r?.projection,c=a?[...o?.projectionLineage??[],a.id]:[...o?.projectionLineage??[]],l=a?.id??o?.projectionId;return _o.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...i}=e??await this.getDirectClaimOptions(),n=Date.now(),o=await this.repository.claimNextReady({...i,now:n,attemptId:Gi(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!o)return null;if(o.status===Ze.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:o.id,type:o.type,retryCount:o.retryCount}),await r?.(o),null;return this.logger.debug("Job dequeued",{id:o.id,type:o.type,priority:o.priority,retryCount:o.retryCount,attemptId:o.attemptId,workerSlotId:o.workerSlotId,workerSessionId:o.workerSessionId}),o}async startWorkerSession(e,t,r=os){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=os){return this.repository.heartbeatWorkerSession(e,t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(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)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),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,i=Date.now()+(e.timeoutMs??30000),n=async(o)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?o??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(c)};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 tJ=S(()=>{Rf();p$();Pf();ss();XC();QK();eJ();ti();oR()});var sR=()=>{};var rJ=S(()=>{Rf();ss();Pf();ss();sR();oR()});var nJ=S(()=>{ss();sR()});var q7e;var iJ=S(()=>{ti();Ae();Of();q7e=d.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},d.record(d.string(),d.unknown()))});var F7e;var oJ=S(()=>{Ae();F7e=d.record(d.string(),d.unknown())});var sJ=S(()=>{ti();Rf()});var aJ=S(()=>{tJ();rJ();nJ();iJ();oJ();Pf();ss();Of();sJ()});var aR={};Ht(aR,{LEGACY_PROJECTION_JOB_TYPES:()=>lJ,LEGACY_PROJECTION_RETIREMENT_REASON:()=>dJ,legacyProjectionJobTypeSchema:()=>uJ,retireLegacyProjectionJob:()=>TSe});import{existsSync as kSe}from"fs";import{resolve as ESe}from"path";function cJ(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 ISe(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 TSe(e){let t=ESe(e.databasePath);if(!kSe(t))throw Error(`Job database does not exist: ${t}`);let r=uJ.parse(e.jobType),i=wp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(ISe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:cJ(n),retired:!1}}let o=`retire:${n.id}`;if(e.confirmation!==o)throw Error(`Refusing to retire ${n.id}; expected --confirm ${o}`);let s=await i.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:dJ,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:cJ(s),retired:!0}}finally{i.close()}}var lJ,uJ,dJ="Retired legacy projection job superseded by scheduler-owned projections";var cR=S(()=>{aJ();Ae();lJ=["conversation-memory:project","skill:project","swot:derive","topic:project"],uJ=d.enum(lJ)});function Yt(e,t,r,i,n){return pJ.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function uR(e){return _p.parse(structuredClone(RSe[e]))}function kp(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 aS(e,t={}){let r=t.fetchImpl??fetch,i=t.now??(()=>new Date),n=t.timeoutMs??20000,o=i(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),lR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:c.ok})}catch(c){return lR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:OSe(c)})}finally{clearTimeout(a)}}async function dR(e,t){let r=_p.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${sS(c)}`}if(!n)for(let c of r.phases)try{let l=mJ.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=sS(l);i.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:u}),n=`${c.id}: ${u}`;break}}finally{try{if(s=hJ.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=sS(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=gJ.parse(await t.stopMonitoring())}catch(c){let l=sS(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=bJ(a,r.maximumExternalAiCalls??0),yJ.parse({profile:r.profile,success:n===void 0&&i.length===r.phases.length&&s.success,baseline:o,phases:i,cleanup:s,metrics:a,...n?{failure:n}:{}})}function bJ(e,t=0){let r=e.health.find((o)=>!o.ok);if(r)return`health: ${r.endpoint} unavailable`;let i=e.externalAiCalls??0;if(i>t)return t===0?`external AI: observed ${i} call(s)`:`external AI: observed ${i} 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 OSe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function sS(e){return at(e)}var vp,fJ,pJ,_p,ASe,lR,$Se,mJ,hJ,CSe,gJ,yJ,RSe;var cS=S(()=>{Ae();vp=d.enum(["regression","load","stress"]),fJ=d.enum(["add","update","rename","delete"]),pJ=d.object({id:d.string().min(1),operation:fJ,count:d.number().int().positive().max(700),targetProbeCount:d.number().int().min(0).max(700),settleMs:d.number().int().nonnegative().max(300000)}),_p=d.object({profile:vp,maximumProbeCount:d.number().int().positive().max(700),maximumExternalAiCalls:d.number().int().nonnegative().max(1e4).optional(),phases:d.array(pJ).min(1)}),ASe=d.object({entities:d.number().int().nonnegative(),notes:d.number().int().nonnegative(),version:d.string().min(1)}),lR=d.object({timestamp:d.iso.datetime(),endpoint:d.string().startsWith("/"),status:d.number().int().nonnegative(),durationMs:d.number().nonnegative(),ok:d.boolean(),error:d.string().optional()}),$Se=d.object({timestamp:d.iso.datetime(),cpuPercent:d.number().nonnegative(),memoryPercent:d.number().nonnegative(),pids:d.number().int().nonnegative()}),mJ=d.object({id:d.string().min(1),operation:fJ,count:d.number().int().positive(),success:d.boolean(),commitLatencyMs:d.number().nonnegative().optional(),persistenceLatencyMs:d.number().nonnegative().optional(),error:d.string().optional()}),hJ=d.object({success:d.boolean(),probesRemaining:d.number().int().nonnegative(),finalEntities:d.number().int().nonnegative().optional(),finalNotes:d.number().int().nonnegative().optional(),contentTreeRestored:d.boolean().optional(),error:d.string().optional()}),CSe=d.object({status:d.string(),restartCount:d.number().int().nonnegative(),oomKilled:d.boolean()}),gJ=d.object({health:d.array(lR),runtime:d.array($Se),externalAiCalls:d.number().int().nonnegative().optional(),container:CSe.optional()}),yJ=d.object({profile:vp,success:d.boolean(),baseline:ASe,phases:d.array(mJ),cleanup:hJ,metrics:gJ,failure:d.string().optional()}),RSe={regression:{profile:"regression",maximumProbeCount:20,phases:[Yt("add20","add",20,20,0),Yt("update20","update",20,20,30000),Yt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("update350a","update",350,350,45000),Yt("rename100","rename",100,350,45000),Yt("update350b","update",350,350,45000),Yt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("add700","add",350,700,0),Yt("update700a","update",700,700,45000),Yt("rename200","rename",200,700,45000),Yt("update700b","update",700,700,45000),Yt("delete700","delete",700,0,150000)]}}});import{spawn as PSe}from"child_process";async function SJ(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw vi(t,r,n);return n}function vi(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var ao=async(e,t,r={})=>new Promise((i,n)=>{let o=PSe(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var Ep=()=>{};class cu{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,i){let n=new cu(e,r,i);return await SJ(e,"git",["-c","credential.helper=","-c",`credential.helper=${xJ}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",xJ]),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 vi("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 xJ='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var wJ=S(()=>{Ep()});function Ip(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class fR{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#i=!0;#o;#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 aS(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#i=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#o=Promise.all([this.#f(),this.#m()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#i=!0})}async stop(){this.#i=!0,await this.#o}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let i=this.#e.now().getTime();while(this.#e.now().getTime()-i<r){let n=await this.fetchHealthPayload();if(this.#d(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let i=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-i<r){let o=await this.fetchHealthPayload();if(this.#d(o,e,t)){if(n+=1,n===2)return o}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let i=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await i.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:i.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:i.ok}),!i.ok)return;return zSe.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||Ip(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await aS(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#m(){while(!this.#i){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var zSe;var vJ=S(()=>{Ae();cS();zSe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),app:d.object({version:d.string(),entities:d.number().int().nonnegative(),entityCounts:d.array(d.object({entityType:d.string(),count:d.number().int().nonnegative()})).default([])})})});var lS={};Ht(lS,{applyDirectorySyncStressPhase:()=>$J,cleanupDirectorySyncStress:()=>IJ,listProbeFiles:()=>ja,parseStressRuntimeSample:()=>CJ,removeProbeFiles:()=>SR,runDeployedDirectorySyncStress:()=>kJ,runStressCommand:()=>ao,verifyDirectorySyncStressAccess:()=>EJ});import{chmod as NSe,mkdir as mR,mkdtemp as hR,readFile as DSe,readdir as LSe,rename as BSe,rm as Ap,writeFile as Kn}from"fs/promises";import{tmpdir as gR}from"os";import{join as St,resolve as yR}from"path";async function kJ(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=xR(r),n=yR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",i));await mR(n,{recursive:!0});let{pilot:o,user:s}=await bR(e.rootDir,e.handle);kp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=vp.parse(e.profile),c=e.plan?_p.parse(e.plan):uR(a);if(c.profile!==a)throw Error(`Directory-sync stress plan profile ${c.profile} does not match requested profile ${a}`);if((c.maximumExternalAiCalls??0)===0)AJ(s);let l=jSe.parse(e.env??process.env),u=new TJ({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??ao,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),f;try{f=await dR(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:f};return await FSe(p),p}async function EJ(e){let r=(e.now??(()=>new Date))().toISOString(),i=xR(r),n=yR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`access-check-${i}`));await mR(n,{recursive:!0});let{pilot:o,user:s}=await bR(e.rootDir,e.handle);kp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),AJ(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await hR(St(gR(),"brains-ops-directory-sync-access-check-"));try{let l=await cu.clone(e.commandRunner??ao,`${o.githubOrg}/${s.contentRepo}`,St(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let f={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Kn(St(n,"access-check.json"),`${JSON.stringify(f,null,2)}
|
|
423
423
|
`),f}finally{await Ap(c,{recursive:!0,force:!0})}}async function IJ(e){let t=e.now??(()=>new Date),r=yR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`cleanup-${xR(t().toISOString())}`));await mR(r,{recursive:!0});let{pilot:i,user:n}=await bR(e.rootDir,e.handle);kp({handle:n.handle,domain:n.domain,contentRepo:n.contentRepo,confirmation:e.confirmation});let o=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!o)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let s=e.commandRunner??ao,a=e.logger??console.info,c=await hR(St(gR(),"brains-ops-directory-sync-cleanup-")),l=St(c,"content");try{let u=await cu.clone(s,`${i.githubOrg}/${n.contentRepo}`,l,o),f=await SR(u.dir),p;if(f>0)await u.commitAll("test(directory-sync): clean residual stress probes"),await u.pushMainWithRebase(),p=await u.output(["rev-parse","HEAD"]),a(`Removed ${f} directory-sync stress probes`);let m=(await ja(u.dir)).length,y=m===0?await u.pruneStressBackupBranches():[],g={success:m===0,artifactsDir:r,probesRemoved:f,probesRemaining:m,backupBranchesDeleted:y,...p?{cleanupCommit:p}:{}};return await Kn(St(r,"cleanup.json"),`${JSON.stringify(g,null,2)}
|
|
424
424
|
`),g}finally{await Ap(c,{recursive:!0,force:!0})}}class TJ{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new fR({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#y()})}async prepare(e){this.#r=await hR(St(gR(),"brains-ops-directory-sync-stress-"));let t=St(this.#r,"content");this.#i=St(this.#r,"id_ed25519"),this.#o=St(this.#r,"known_hosts"),this.#a=await this.#m(),await Kn(this.#i,MSe(this.#e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await NSe(this.#i,384);let r=await this.#b("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 Kn(this.#o,r.stdout,{mode:384});let i=await this.#h(["docker","ps","--filter","label=service=rover","--filter","label=role=web","--format","{{.Names}}"]);if(this.#s=i.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 cu.clone(this.#e.commandRunner,`${this.#e.githubOrg}/${this.#e.user.contentRepo}`,t,this.#e.environment.CONTENT_REPO_ADMIN_TOKEN);if(this.#n=n,(await ja(n.dir)).length>0)throw Error("Directory-sync stress probes already exist");let o=await n.output(["rev-parse","HEAD"]);this.#l=await n.output(["rev-parse","HEAD^{tree}"]),this.#d=await this.#f();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 Kn(St(this.#e.artifactsDir,"state.json"),`${JSON.stringify({runId:this.#e.runId,profile:e.profile,originalHead:o,originalTree:this.#l,backupBranch:this.#c,baseline:{entities:s.entities,notes:Ip(s),version:s.version}},null,2)}
|
|
425
425
|
`),this.#e.logger(`Prepared ${e.profile} directory-sync stress run for ${this.#e.user.handle}`),{entities:s.entities,notes:Ip(s),version:s.version}}async startMonitoring(){this.#S(),this.#t.start()}async executePhase(e,t){this.#S();let r=this.#n;if(!r)throw Error("Directory-sync stress checkout is not prepared");await r.sync();let i=this.#t.healthSamples.length,n=this.#e.now().getTime(),o=await this.#g();if(o?.pending!==0||o.processing!==0)return lu(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"]),c=await this.#p(a,900000);if(c===void 0)return lu(e,"runtime did not pull the phase commit");let l;if(e.operation==="rename"){let m=t.notes+e.targetProbeCount;if(e.settleMs>0)await this.#e.sleep(e.settleMs);let y=await this.#t.waitForStableEntityBaseline(m,void 0,1200000);if(l=this.#e.now().getTime()-s,!y)return lu(e,`health did not stabilize at ${m} notes`,c,l)}else if(e.operation==="add"||e.operation==="delete"){let m=t.notes+e.targetProbeCount,y=this.#e.now().getTime(),g=await this.#t.waitForEntityBaseline(m,void 0,1200000);if(l=this.#e.now().getTime()-y,!g)return lu(e,`health did not reach ${m} notes`,c,l)}if(e.operation!=="rename"&&e.settleMs>0)await this.#e.sleep(e.settleMs);let u=e.operation==="delete"?0:Math.ceil(e.count/50);if(!await this.#u(o.completedImports+u,1200000))return lu(e,`health did not observe ${u} completed import job(s) with a drained queue`,c,l);let p=this.#t.healthSamples.slice(i).find((m)=>!m.ok);if(p)return lu(e,`${p.endpoint} unavailable (${p.status===0?p.error??"unknown":p.status})`,c,l);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:c,...l===void 0?{}:{persistenceLatencyMs:l}}}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 SR(t.dir)>0)await t.commitAll("test(directory-sync): remove stress probes"),await t.pushMainWithRebase();let i=(await ja(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=i===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:i,...n?{finalEntities:n.entities,finalNotes:Ip(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 ja(t.dir)).length,error:at(r)}}}async stopMonitoring(){await this.#t.stop(),await Kn(St(this.#e.artifactsDir,"health-samples.json"),`${JSON.stringify(this.#t.healthSamples,null,2)}
|
|
@@ -732,7 +732,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
|
732
732
|
`),o}async function qJ(e,t){let r=await xt(e),i=r.users.find((n)=>n.handle===t);if(!i)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:i}}async function ZJ(e){let t=await YSe(_i(XSe(),"brains-ops-watchdog-smoke-")),r=_i(t,"id_ed25519"),i=_i(t,"known_hosts");try{let n=encodeURIComponent(`brain=${e.target.pilot.contentRepoPrefix}${e.target.user.handle}`),o=await e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${n}`,{headers:{Authorization:`Bearer ${e.environment.HCLOUD_TOKEN}`}});if(!o.ok)throw Error(`Hetzner server lookup failed with ${o.status}`);let s=exe.parse(await o.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 uu(r,nxe(e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await QSe(r,384);let c=await e.commandRunner("ssh-keyscan",["-T","10","-t","ed25519",a.public_net.ipv4.ip]);if(c.exitCode!==0||!c.stdout.trim())throw Error("Unable to resolve watchdog smoke SSH host key");return await uu(i,c.stdout,{mode:384}),{temporaryRoot:t,sshKeyPath:r,knownHostsPath:i,serverIp:a.public_net.ipv4.ip,commandRunner:e.commandRunner}}catch(n){throw await _R(t,{recursive:!0,force:!0}),n}}async function vR(e,t,r){return e.commandRunner("ssh",[...MJ(e),`root@${e.serverIp}`,"bash","-s","--",t,r],{stdin:kR()})}async function txe(e,t,r){return e.commandRunner("scp",[...MJ(e),"-r",`root@${e.serverIp}:${t}/.`,r])}function MJ(e){return["-i",e.sshKeyPath,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${e.knownHostsPath}`]}async function rxe(e){try{return await GSe(e),!0}catch{return!1}}async function uS(e,t,r){await Promise.all([uu(_i(e,`${t}.stdout.log`),r.stdout),uu(_i(e,`${t}.stderr.log`),r.stderr)])}function nxe(e){return`${e.replace(/\r\n/g,`
|
|
733
733
|
`).replace(/\\n/g,`
|
|
734
734
|
`).trimEnd()}
|
|
735
|
-
`}var BJ,exe;var fS=S(async()=>{Ae();zJ();un();Ep();await PJ();BJ=d.object({HCLOUD_TOKEN:d.string().min(1),KAMAL_SSH_PRIVATE_KEY:d.string().min(1)}),exe=d.object({servers:d.array(d.object({status:d.string(),public_net:d.object({ipv4:d.object({ip:d.string().min(1)})})}))})});import{access as ZN,chmod as iE,mkdir as bh,readFile as FN,writeFile as MN}from"fs/promises";import{dirname as wG,join as Ic}from"path";import{fileURLToPath as vG}from"url";var Cp={name:"@rizom/ops",version:"0.2.0-alpha.
|
|
735
|
+
`}var BJ,exe;var fS=S(async()=>{Ae();zJ();un();Ep();await PJ();BJ=d.object({HCLOUD_TOKEN:d.string().min(1),KAMAL_SSH_PRIVATE_KEY:d.string().min(1)}),exe=d.object({servers:d.array(d.object({status:d.string(),public_net:d.object({ipv4:d.object({ip:d.string().min(1)})})}))})});import{access as ZN,chmod as iE,mkdir as bh,readFile as FN,writeFile as MN}from"fs/promises";import{dirname as wG,join as Ic}from"path";import{fileURLToPath as vG}from"url";var Cp={name:"@rizom/ops",version:"0.2.0-alpha.563",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/auth-service":"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 run build && 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"};_s();Ec();var _G=["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/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"],oE=new Set([".kamal/hooks/pre-deploy"]),kG=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),EG=vG(new URL("../templates/rover-pilot/",import.meta.url)),IG=[`service: rover
|
|
736
736
|
image: <%= ENV['IMAGE_REPOSITORY'] %>
|
|
737
737
|
|
|
738
738
|
servers:
|