oh-my-pr 4.2.1 → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs
CHANGED
|
@@ -96,7 +96,7 @@ ${R}`),g.pop(),`{${I}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";
|
|
|
96
96
|
`)&&(r=r.replace(/[^\n]+$/,"")),!1}),r&&(r=r.replace(/\S/g,"")),r}rawColon(e){let r;return e.walkDecls(n=>{if(typeof n.raws.between<"u")return r=n.raws.between.replace(/[^\s:]/g,""),!1}),r}rawEmptyBody(e){let r;return e.walk(n=>{if(n.nodes&&n.nodes.length===0&&(r=n.raws.after,typeof r<"u"))return!1}),r}rawIndent(e){if(e.raws.indent)return e.raws.indent;let r;return e.walk(n=>{let i=n.parent;if(i&&i!==e&&i.parent&&i.parent===e&&typeof n.raws.before<"u"){let s=n.raws.before.split(`
|
|
97
97
|
`);return r=s[s.length-1],r=r.replace(/\S/g,""),!1}}),r}rawSemicolon(e){let r;return e.walk(n=>{if(n.nodes&&n.nodes.length&&n.last.type==="decl"&&(r=n.raws.semicolon,typeof r<"u"))return!1}),r}rawValue(e,r){let n=e[r],i=e.raws[r];return i&&i.value===n?i.raw:n}root(e){if(this.body(e),e.raws.after){let r=e.raws.after,n=e.parent&&e.parent.type==="document";this.builder(n?r:Sn(r))}}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(Sn(e.raws.ownSemicolon),e,"end")}stringify(e,r){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,r)}};kA.exports=go;go.default=go});var ho=y((Mse,RA)=>{"use strict";var DJ=jh();function qh(t,e){new DJ(e).stringify(t)}RA.exports=qh;qh.default=qh});var wl=y((jse,Uh)=>{"use strict";Uh.exports.isClean=Symbol("isClean");Uh.exports.my=Symbol("my")});var vo=y((qse,AA)=>{"use strict";var NJ=vl(),FJ=jh(),MJ=ho(),{isClean:bo,my:jJ}=wl();function Gh(t,e){let r=new t.constructor;for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n)||n==="proxyCache")continue;let i=t[n],s=typeof i;n==="parent"&&s==="object"?e&&(r[n]=e):n==="source"?r[n]=i:Array.isArray(i)?r[n]=i.map(a=>Gh(a,r)):(s==="object"&&i!==null&&(i=Gh(i)),r[n]=i)}return r}function Xr(t,e){if(e&&typeof e.offset<"u")return e.offset;let r=1,n=1,i=0;for(let s=0;s<t.length;s++){if(n===e.line&&r===e.column){i=s;break}t[s]===`
|
|
98
98
|
`?(r=1,n+=1):r+=1}return i}var yo=class{get proxyOf(){return this}constructor(e={}){this.raws={},this[bo]=!1,this[jJ]=!0;for(let r in e)if(r==="nodes"){this.nodes=[];for(let n of e[r])typeof n.clone=="function"?this.append(n.clone()):this.append(n)}else this[r]=e[r]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let r=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${r.input.from}:${r.start.line}:${r.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let r in e)this[r]=e[r];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let r=Gh(this);for(let n in e)r[n]=e[n];return r}cloneAfter(e={}){let r=this.clone(e);return this.parent.insertAfter(this,r),r}cloneBefore(e={}){let r=this.clone(e);return this.parent.insertBefore(this,r),r}error(e,r={}){if(this.source){let{end:n,start:i}=this.rangeBy(r);return this.source.input.error(e,{column:i.column,line:i.line},{column:n.column,line:n.line},r)}return new NJ(e)}getProxyProcessor(){return{get(e,r){return r==="proxyOf"?e:r==="root"?()=>e.root().toProxy():e[r]},set(e,r,n){return e[r]===n||(e[r]=n,(r==="prop"||r==="value"||r==="name"||r==="params"||r==="important"||r==="text")&&e.markDirty()),!0}}}markClean(){this[bo]=!0}markDirty(){if(this[bo]){this[bo]=!1;let e=this;for(;e=e.parent;)e[bo]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e={}){let r=this.source.start;if(e.index)r=this.positionInside(e.index);else if(e.word){let n="document"in this.source.input?this.source.input.document:this.source.input.css,s=n.slice(Xr(n,this.source.start),Xr(n,this.source.end)).indexOf(e.word);s!==-1&&(r=this.positionInside(s))}return r}positionInside(e){let r=this.source.start.column,n=this.source.start.line,i="document"in this.source.input?this.source.input.document:this.source.input.css,s=Xr(i,this.source.start),a=s+e;for(let o=s;o<a;o++)i[o]===`
|
|
99
|
-
`?(r=1,n+=1):r+=1;return{column:r,line:n,offset:a}}prev(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e-1]}rangeBy(e={}){let r="document"in this.source.input?this.source.input.document:this.source.input.css,n={column:this.source.start.column,line:this.source.start.line,offset:Xr(r,this.source.start)},i=this.source.end?{column:this.source.end.column+1,line:this.source.end.line,offset:typeof this.source.end.offset=="number"?this.source.end.offset:Xr(r,this.source.end)+1}:{column:n.column+1,line:n.line,offset:n.offset+1};if(e.word){let a=r.slice(Xr(r,this.source.start),Xr(r,this.source.end)).indexOf(e.word);a!==-1&&(n=this.positionInside(a),i=this.positionInside(a+e.word.length))}else e.start?n={column:e.start.column,line:e.start.line,offset:Xr(r,e.start)}:e.index&&(n=this.positionInside(e.index)),e.end?i={column:e.end.column,line:e.end.line,offset:Xr(r,e.end)}:typeof e.endIndex=="number"?i=this.positionInside(e.endIndex):e.index&&(i=this.positionInside(e.index+1));return(i.line<n.line||i.line===n.line&&i.column<=n.column)&&(i={column:n.column+1,line:n.line,offset:n.offset+1}),{end:i,start:n}}raw(e,r){return new FJ().raw(this,e,r)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...e){if(this.parent){let r=this,n=!1;for(let i of e)i===this?n=!0:n?(this.parent.insertAfter(r,i),r=i):this.parent.insertBefore(r,i);n||this.remove()}return this}root(){let e=this;for(;e.parent&&e.parent.type!=="document";)e=e.parent;return e}toJSON(e,r){let n={},i=r==null;r=r||new Map;let s=0;for(let a in this){if(!Object.prototype.hasOwnProperty.call(this,a)||a==="parent"||a==="proxyCache")continue;let o=this[a];if(Array.isArray(o))n[a]=o.map(u=>typeof u=="object"&&u.toJSON?u.toJSON(null,r):u);else if(typeof o=="object"&&o.toJSON)n[a]=o.toJSON(null,r);else if(a==="source"){if(o==null)continue;let u=r.get(o.input);u==null&&(u=s,r.set(o.input,s),s++),n[a]={end:o.end,inputId:u,start:o.start}}else n[a]=o}return i&&(n.inputs=[...r.keys()].map(a=>a.toJSON())),n}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=MJ){e.stringify&&(e=e.stringify);let r="";return e(this,n=>{r+=n}),r}warn(e,r,n={}){let i={node:this};for(let s in n)i[s]=n[s];return e.warn(r,i)}};AA.exports=yo;yo.default=yo});var xo=y((Use,PA)=>{"use strict";var qJ=vo(),wo=class extends qJ{constructor(e){super(e),this.type="comment"}};PA.exports=wo;wo.default=wo});var Eo=y((Gse,CA)=>{"use strict";var UJ=vo(),_o=class extends UJ{get variable(){return this.prop.startsWith("--")||this.prop[0]==="$"}constructor(e){e&&typeof e.value<"u"&&typeof e.value!="string"&&(e={...e,value:String(e.value)}),super(e),this.type="decl"}};CA.exports=_o;_o.default=_o});var kn=y((Bse,qA)=>{"use strict";var OA=xo(),IA=Eo(),GJ=vo(),{isClean:LA,my:DA}=wl(),Bh,NA,FA,Hh;function MA(t){return t.map(e=>(e.nodes&&(e.nodes=MA(e.nodes)),delete e.source,e))}function jA(t){if(t[LA]=!1,t.proxyOf.nodes)for(let e of t.proxyOf.nodes)jA(e)}var ur=class t extends GJ{get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}append(...e){for(let r of e){let n=this.normalize(r,this.last);for(let i of n)this.proxyOf.nodes.push(i)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let r of this.nodes)r.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let r=this.getIterator(),n,i;for(;this.indexes[r]<this.proxyOf.nodes.length&&(n=this.indexes[r],i=e(this.proxyOf.nodes[n],n),i!==!1);)this.indexes[r]+=1;return delete this.indexes[r],i}every(e){return this.nodes.every(e)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let e=this.lastEach;return this.indexes[e]=0,e}getProxyProcessor(){return{get(e,r){return r==="proxyOf"?e:e[r]?r==="each"||typeof r=="string"&&r.startsWith("walk")?(...n)=>e[r](...n.map(i=>typeof i=="function"?(s,a)=>i(s.toProxy(),a):i)):r==="every"||r==="some"?n=>e[r]((i,...s)=>n(i.toProxy(),...s)):r==="root"?()=>e.root().toProxy():r==="nodes"?e.nodes.map(n=>n.toProxy()):r==="first"||r==="last"?e[r].toProxy():e[r]:e[r]},set(e,r,n){return e[r]===n||(e[r]=n,(r==="name"||r==="params"||r==="selector")&&e.markDirty()),!0}}}index(e){return typeof e=="number"?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,r){let n=this.index(e),i=this.normalize(r,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(let a of i)this.proxyOf.nodes.splice(n+1,0,a);let s;for(let a in this.indexes)s=this.indexes[a],n<s&&(this.indexes[a]=s+i.length);return this.markDirty(),this}insertBefore(e,r){let n=this.index(e),i=n===0?"prepend":!1,s=this.normalize(r,this.proxyOf.nodes[n],i).reverse();n=this.index(e);for(let o of s)this.proxyOf.nodes.splice(n,0,o);let a;for(let o in this.indexes)a=this.indexes[o],n<=a&&(this.indexes[o]=a+s.length);return this.markDirty(),this}normalize(e,r){if(typeof e=="string")e=MA(NA(e).nodes);else if(typeof e>"u")e=[];else if(Array.isArray(e)){e=e.slice(0);for(let i of e)i.parent&&i.parent.removeChild(i,"ignore")}else if(e.type==="root"&&this.type!=="document"){e=e.nodes.slice(0);for(let i of e)i.parent&&i.parent.removeChild(i,"ignore")}else if(e.type)e=[e];else if(e.prop){if(typeof e.value>"u")throw new Error("Value field is missed in node creation");typeof e.value!="string"&&(e.value=String(e.value)),e=[new IA(e)]}else if(e.selector||e.selectors)e=[new Hh(e)];else if(e.name)e=[new Bh(e)];else if(e.text)e=[new OA(e)];else throw new Error("Unknown node type in node creation");return e.map(i=>(i[DA]||t.rebuild(i),i=i.proxyOf,i.parent&&i.parent.removeChild(i),i[LA]&&jA(i),i.raws||(i.raws={}),typeof i.raws.before>"u"&&r&&typeof r.raws.before<"u"&&(i.raws.before=r.raws.before.replace(/\S/g,"")),i.parent=this.proxyOf,i))}prepend(...e){e=e.reverse();for(let r of e){let n=this.normalize(r,this.first,"prepend").reverse();for(let i of n)this.proxyOf.nodes.unshift(i);for(let i in this.indexes)this.indexes[i]=this.indexes[i]+n.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);let r;for(let n in this.indexes)r=this.indexes[n],r>=e&&(this.indexes[n]=r-1);return this.markDirty(),this}replaceValues(e,r,n){return n||(n=r,r={}),this.walkDecls(i=>{r.props&&!r.props.includes(i.prop)||r.fast&&!i.value.includes(r.fast)||(i.value=i.value.replace(e,n))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((r,n)=>{let i;try{i=e(r,n)}catch(s){throw r.addToError(s)}return i!==!1&&r.walk&&(i=r.walk(e)),i})}walkAtRules(e,r){return r?e instanceof RegExp?this.walk((n,i)=>{if(n.type==="atrule"&&e.test(n.name))return r(n,i)}):this.walk((n,i)=>{if(n.type==="atrule"&&n.name===e)return r(n,i)}):(r=e,this.walk((n,i)=>{if(n.type==="atrule")return r(n,i)}))}walkComments(e){return this.walk((r,n)=>{if(r.type==="comment")return e(r,n)})}walkDecls(e,r){return r?e instanceof RegExp?this.walk((n,i)=>{if(n.type==="decl"&&e.test(n.prop))return r(n,i)}):this.walk((n,i)=>{if(n.type==="decl"&&n.prop===e)return r(n,i)}):(r=e,this.walk((n,i)=>{if(n.type==="decl")return r(n,i)}))}walkRules(e,r){return r?e instanceof RegExp?this.walk((n,i)=>{if(n.type==="rule"&&e.test(n.selector))return r(n,i)}):this.walk((n,i)=>{if(n.type==="rule"&&n.selector===e)return r(n,i)}):(r=e,this.walk((n,i)=>{if(n.type==="rule")return r(n,i)}))}};ur.registerParse=t=>{NA=t};ur.registerRule=t=>{Hh=t};ur.registerAtRule=t=>{Bh=t};ur.registerRoot=t=>{FA=t};qA.exports=ur;ur.default=ur;ur.rebuild=t=>{t.type==="atrule"?Object.setPrototypeOf(t,Bh.prototype):t.type==="rule"?Object.setPrototypeOf(t,Hh.prototype):t.type==="decl"?Object.setPrototypeOf(t,IA.prototype):t.type==="comment"?Object.setPrototypeOf(t,OA.prototype):t.type==="root"&&Object.setPrototypeOf(t,FA.prototype),t[DA]=!0,t.nodes&&t.nodes.forEach(e=>{ur.rebuild(e)})}});var xl=y((Hse,GA)=>{"use strict";var UA=kn(),$s=class extends UA{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};GA.exports=$s;$s.default=$s;UA.registerAtRule($s)});var _l=y(($se,$A)=>{"use strict";var BJ=kn(),BA,HA,Ai=class extends BJ{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new BA(new HA,this,e).stringify()}};Ai.registerLazyResult=t=>{BA=t};Ai.registerProcessor=t=>{HA=t};$A.exports=Ai;Ai.default=Ai});var WA=y((zse,zA)=>{var HJ="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",$J=(t,e=21)=>(r=e)=>{let n="",i=r|0;for(;i--;)n+=t[Math.random()*t.length|0];return n},zJ=(t=21)=>{let e="",r=t|0;for(;r--;)e+=HJ[Math.random()*64|0];return e};zA.exports={nanoid:zJ,customAlphabet:$J}});var JA=y($h=>{var VA="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");$h.encode=function(t){if(0<=t&&t<VA.length)return VA[t];throw new TypeError("Must be between 0 and 63: "+t)};$h.decode=function(t){var e=65,r=90,n=97,i=122,s=48,a=57,o=43,u=47,c=26,l=52;return e<=t&&t<=r?t-e:n<=t&&t<=i?t-n+c:s<=t&&t<=a?t-s+l:t==o?62:t==u?63:-1}});var Vh=y(Wh=>{var XA=JA(),zh=5,KA=1<<zh,QA=KA-1,YA=KA;function WJ(t){return t<0?(-t<<1)+1:(t<<1)+0}function VJ(t){var e=(t&1)===1,r=t>>1;return e?-r:r}Wh.encode=function(e){var r="",n,i=WJ(e);do n=i&QA,i>>>=zh,i>0&&(n|=YA),r+=XA.encode(n);while(i>0);return r};Wh.decode=function(e,r,n){var i=e.length,s=0,a=0,o,u;do{if(r>=i)throw new Error("Expected more digits in base 64 VLQ value.");if(u=XA.decode(e.charCodeAt(r++)),u===-1)throw new Error("Invalid base64 digit: "+e.charAt(r-1));o=!!(u&YA),u&=QA,s=s+(u<<a),a+=zh}while(o);n.value=VJ(s),n.rest=r}});var Ws=y(Qe=>{function JJ(t,e,r){if(e in t)return t[e];if(arguments.length===3)return r;throw new Error('"'+e+'" is a required argument.')}Qe.getArg=JJ;var ZA=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,XJ=/^data:.+\,.+$/;function To(t){var e=t.match(ZA);return e?{scheme:e[1],auth:e[2],host:e[3],port:e[4],path:e[5]}:null}Qe.urlParse=To;function zs(t){var e="";return t.scheme&&(e+=t.scheme+":"),e+="//",t.auth&&(e+=t.auth+"@"),t.host&&(e+=t.host),t.port&&(e+=":"+t.port),t.path&&(e+=t.path),e}Qe.urlGenerate=zs;var KJ=32;function QJ(t){var e=[];return function(r){for(var n=0;n<e.length;n++)if(e[n].input===r){var i=e[0];return e[0]=e[n],e[n]=i,e[0].result}var s=t(r);return e.unshift({input:r,result:s}),e.length>KJ&&e.pop(),s}}var Jh=QJ(function(e){var r=e,n=To(e);if(n){if(!n.path)return e;r=n.path}for(var i=Qe.isAbsolute(r),s=[],a=0,o=0;;)if(a=o,o=r.indexOf("/",a),o===-1){s.push(r.slice(a));break}else for(s.push(r.slice(a,o));o<r.length&&r[o]==="/";)o++;for(var u,c=0,o=s.length-1;o>=0;o--)u=s[o],u==="."?s.splice(o,1):u===".."?c++:c>0&&(u===""?(s.splice(o+1,c),c=0):(s.splice(o,2),c--));return r=s.join("/"),r===""&&(r=i?"/":"."),n?(n.path=r,zs(n)):r});Qe.normalize=Jh;function e3(t,e){t===""&&(t="."),e===""&&(e=".");var r=To(e),n=To(t);if(n&&(t=n.path||"/"),r&&!r.scheme)return n&&(r.scheme=n.scheme),zs(r);if(r||e.match(XJ))return e;if(n&&!n.host&&!n.path)return n.host=e,zs(n);var i=e.charAt(0)==="/"?e:Jh(t.replace(/\/+$/,"")+"/"+e);return n?(n.path=i,zs(n)):i}Qe.join=e3;Qe.isAbsolute=function(t){return t.charAt(0)==="/"||ZA.test(t)};function YJ(t,e){t===""&&(t="."),t=t.replace(/\/$/,"");for(var r=0;e.indexOf(t+"/")!==0;){var n=t.lastIndexOf("/");if(n<0||(t=t.slice(0,n),t.match(/^([^\/]+:\/)?\/*$/)))return e;++r}return Array(r+1).join("../")+e.substr(t.length+1)}Qe.relative=YJ;var t3=(function(){var t=Object.create(null);return!("__proto__"in t)})();function r3(t){return t}function ZJ(t){return n3(t)?"$"+t:t}Qe.toSetString=t3?r3:ZJ;function eX(t){return n3(t)?t.slice(1):t}Qe.fromSetString=t3?r3:eX;function n3(t){if(!t)return!1;var e=t.length;if(e<9||t.charCodeAt(e-1)!==95||t.charCodeAt(e-2)!==95||t.charCodeAt(e-3)!==111||t.charCodeAt(e-4)!==116||t.charCodeAt(e-5)!==111||t.charCodeAt(e-6)!==114||t.charCodeAt(e-7)!==112||t.charCodeAt(e-8)!==95||t.charCodeAt(e-9)!==95)return!1;for(var r=e-10;r>=0;r--)if(t.charCodeAt(r)!==36)return!1;return!0}function tX(t,e,r){var n=Kr(t.source,e.source);return n!==0||(n=t.originalLine-e.originalLine,n!==0)||(n=t.originalColumn-e.originalColumn,n!==0||r)||(n=t.generatedColumn-e.generatedColumn,n!==0)||(n=t.generatedLine-e.generatedLine,n!==0)?n:Kr(t.name,e.name)}Qe.compareByOriginalPositions=tX;function rX(t,e,r){var n;return n=t.originalLine-e.originalLine,n!==0||(n=t.originalColumn-e.originalColumn,n!==0||r)||(n=t.generatedColumn-e.generatedColumn,n!==0)||(n=t.generatedLine-e.generatedLine,n!==0)?n:Kr(t.name,e.name)}Qe.compareByOriginalPositionsNoSource=rX;function nX(t,e,r){var n=t.generatedLine-e.generatedLine;return n!==0||(n=t.generatedColumn-e.generatedColumn,n!==0||r)||(n=Kr(t.source,e.source),n!==0)||(n=t.originalLine-e.originalLine,n!==0)||(n=t.originalColumn-e.originalColumn,n!==0)?n:Kr(t.name,e.name)}Qe.compareByGeneratedPositionsDeflated=nX;function iX(t,e,r){var n=t.generatedColumn-e.generatedColumn;return n!==0||r||(n=Kr(t.source,e.source),n!==0)||(n=t.originalLine-e.originalLine,n!==0)||(n=t.originalColumn-e.originalColumn,n!==0)?n:Kr(t.name,e.name)}Qe.compareByGeneratedPositionsDeflatedNoLine=iX;function Kr(t,e){return t===e?0:t===null?1:e===null?-1:t>e?1:-1}function sX(t,e){var r=t.generatedLine-e.generatedLine;return r!==0||(r=t.generatedColumn-e.generatedColumn,r!==0)||(r=Kr(t.source,e.source),r!==0)||(r=t.originalLine-e.originalLine,r!==0)||(r=t.originalColumn-e.originalColumn,r!==0)?r:Kr(t.name,e.name)}Qe.compareByGeneratedPositionsInflated=sX;function aX(t){return JSON.parse(t.replace(/^\)]}'[^\n]*\n/,""))}Qe.parseSourceMapInput=aX;function oX(t,e,r){if(e=e||"",t&&(t[t.length-1]!=="/"&&e[0]!=="/"&&(t+="/"),e=t+e),r){var n=To(r);if(!n)throw new Error("sourceMapURL could not be parsed");if(n.path){var i=n.path.lastIndexOf("/");i>=0&&(n.path=n.path.substring(0,i+1))}e=e3(zs(n),e)}return Jh(e)}Qe.computeSourceURL=oX});var Qh=y(i3=>{var Xh=Ws(),Kh=Object.prototype.hasOwnProperty,Pi=typeof Map<"u";function Qr(){this._array=[],this._set=Pi?new Map:Object.create(null)}Qr.fromArray=function(e,r){for(var n=new Qr,i=0,s=e.length;i<s;i++)n.add(e[i],r);return n};Qr.prototype.size=function(){return Pi?this._set.size:Object.getOwnPropertyNames(this._set).length};Qr.prototype.add=function(e,r){var n=Pi?e:Xh.toSetString(e),i=Pi?this.has(e):Kh.call(this._set,n),s=this._array.length;(!i||r)&&this._array.push(e),i||(Pi?this._set.set(e,s):this._set[n]=s)};Qr.prototype.has=function(e){if(Pi)return this._set.has(e);var r=Xh.toSetString(e);return Kh.call(this._set,r)};Qr.prototype.indexOf=function(e){if(Pi){var r=this._set.get(e);if(r>=0)return r}else{var n=Xh.toSetString(e);if(Kh.call(this._set,n))return this._set[n]}throw new Error('"'+e+'" is not in the set.')};Qr.prototype.at=function(e){if(e>=0&&e<this._array.length)return this._array[e];throw new Error("No element indexed by "+e)};Qr.prototype.toArray=function(){return this._array.slice()};i3.ArraySet=Qr});var o3=y(a3=>{var s3=Ws();function uX(t,e){var r=t.generatedLine,n=e.generatedLine,i=t.generatedColumn,s=e.generatedColumn;return n>r||n==r&&s>=i||s3.compareByGeneratedPositionsInflated(t,e)<=0}function El(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}El.prototype.unsortedForEach=function(e,r){this._array.forEach(e,r)};El.prototype.add=function(e){uX(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))};El.prototype.toArray=function(){return this._sorted||(this._array.sort(s3.compareByGeneratedPositionsInflated),this._sorted=!0),this._array};a3.MappingList=El});var Yh=y(u3=>{var So=Vh(),Fe=Ws(),Tl=Qh().ArraySet,cX=o3().MappingList;function Wt(t){t||(t={}),this._file=Fe.getArg(t,"file",null),this._sourceRoot=Fe.getArg(t,"sourceRoot",null),this._skipValidation=Fe.getArg(t,"skipValidation",!1),this._ignoreInvalidMapping=Fe.getArg(t,"ignoreInvalidMapping",!1),this._sources=new Tl,this._names=new Tl,this._mappings=new cX,this._sourcesContents=null}Wt.prototype._version=3;Wt.fromSourceMap=function(e,r){var n=e.sourceRoot,i=new Wt(Object.assign(r||{},{file:e.file,sourceRoot:n}));return e.eachMapping(function(s){var a={generated:{line:s.generatedLine,column:s.generatedColumn}};s.source!=null&&(a.source=s.source,n!=null&&(a.source=Fe.relative(n,a.source)),a.original={line:s.originalLine,column:s.originalColumn},s.name!=null&&(a.name=s.name)),i.addMapping(a)}),e.sources.forEach(function(s){var a=s;n!==null&&(a=Fe.relative(n,s)),i._sources.has(a)||i._sources.add(a);var o=e.sourceContentFor(s);o!=null&&i.setSourceContent(s,o)}),i};Wt.prototype.addMapping=function(e){var r=Fe.getArg(e,"generated"),n=Fe.getArg(e,"original",null),i=Fe.getArg(e,"source",null),s=Fe.getArg(e,"name",null);!this._skipValidation&&this._validateMapping(r,n,i,s)===!1||(i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),s!=null&&(s=String(s),this._names.has(s)||this._names.add(s)),this._mappings.add({generatedLine:r.line,generatedColumn:r.column,originalLine:n!=null&&n.line,originalColumn:n!=null&&n.column,source:i,name:s}))};Wt.prototype.setSourceContent=function(e,r){var n=e;this._sourceRoot!=null&&(n=Fe.relative(this._sourceRoot,n)),r!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[Fe.toSetString(n)]=r):this._sourcesContents&&(delete this._sourcesContents[Fe.toSetString(n)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))};Wt.prototype.applySourceMap=function(e,r,n){var i=r;if(r==null){if(e.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);i=e.file}var s=this._sourceRoot;s!=null&&(i=Fe.relative(s,i));var a=new Tl,o=new Tl;this._mappings.unsortedForEach(function(u){if(u.source===i&&u.originalLine!=null){var c=e.originalPositionFor({line:u.originalLine,column:u.originalColumn});c.source!=null&&(u.source=c.source,n!=null&&(u.source=Fe.join(n,u.source)),s!=null&&(u.source=Fe.relative(s,u.source)),u.originalLine=c.line,u.originalColumn=c.column,c.name!=null&&(u.name=c.name))}var l=u.source;l!=null&&!a.has(l)&&a.add(l);var p=u.name;p!=null&&!o.has(p)&&o.add(p)},this),this._sources=a,this._names=o,e.sources.forEach(function(u){var c=e.sourceContentFor(u);c!=null&&(n!=null&&(u=Fe.join(n,u)),s!=null&&(u=Fe.relative(s,u)),this.setSourceContent(u,c))},this)};Wt.prototype._validateMapping=function(e,r,n,i){if(r&&typeof r.line!="number"&&typeof r.column!="number"){var s="original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.";if(this._ignoreInvalidMapping)return typeof console<"u"&&console.warn&&console.warn(s),!1;throw new Error(s)}if(!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!r&&!n&&!i)){if(e&&"line"in e&&"column"in e&&r&&"line"in r&&"column"in r&&e.line>0&&e.column>=0&&r.line>0&&r.column>=0&&n)return;var s="Invalid mapping: "+JSON.stringify({generated:e,source:n,original:r,name:i});if(this._ignoreInvalidMapping)return typeof console<"u"&&console.warn&&console.warn(s),!1;throw new Error(s)}};Wt.prototype._serializeMappings=function(){for(var e=0,r=1,n=0,i=0,s=0,a=0,o="",u,c,l,p,d=this._mappings.toArray(),m=0,f=d.length;m<f;m++){if(c=d[m],u="",c.generatedLine!==r)for(e=0;c.generatedLine!==r;)u+=";",r++;else if(m>0){if(!Fe.compareByGeneratedPositionsInflated(c,d[m-1]))continue;u+=","}u+=So.encode(c.generatedColumn-e),e=c.generatedColumn,c.source!=null&&(p=this._sources.indexOf(c.source),u+=So.encode(p-a),a=p,u+=So.encode(c.originalLine-1-i),i=c.originalLine-1,u+=So.encode(c.originalColumn-n),n=c.originalColumn,c.name!=null&&(l=this._names.indexOf(c.name),u+=So.encode(l-s),s=l)),o+=u}return o};Wt.prototype._generateSourcesContent=function(e,r){return e.map(function(n){if(!this._sourcesContents)return null;r!=null&&(n=Fe.relative(r,n));var i=Fe.toSetString(n);return Object.prototype.hasOwnProperty.call(this._sourcesContents,i)?this._sourcesContents[i]:null},this)};Wt.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(e.file=this._file),this._sourceRoot!=null&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e};Wt.prototype.toString=function(){return JSON.stringify(this.toJSON())};u3.SourceMapGenerator=Wt});var c3=y(Ci=>{Ci.GREATEST_LOWER_BOUND=1;Ci.LEAST_UPPER_BOUND=2;function Zh(t,e,r,n,i,s){var a=Math.floor((e-t)/2)+t,o=i(r,n[a],!0);return o===0?a:o>0?e-a>1?Zh(a,e,r,n,i,s):s==Ci.LEAST_UPPER_BOUND?e<n.length?e:-1:a:a-t>1?Zh(t,a,r,n,i,s):s==Ci.LEAST_UPPER_BOUND?a:t<0?-1:t}Ci.search=function(e,r,n,i){if(r.length===0)return-1;var s=Zh(-1,r.length,e,r,n,i||Ci.GREATEST_LOWER_BOUND);if(s<0)return-1;for(;s-1>=0&&n(r[s],r[s-1],!0)===0;)--s;return s}});var d3=y(p3=>{function lX(t){function e(i,s,a){var o=i[s];i[s]=i[a],i[a]=o}function r(i,s){return Math.round(i+Math.random()*(s-i))}function n(i,s,a,o){if(a<o){var u=r(a,o),c=a-1;e(i,u,o);for(var l=i[o],p=a;p<o;p++)s(i[p],l,!1)<=0&&(c+=1,e(i,c,p));e(i,c+1,p);var d=c+1;n(i,s,a,d-1),n(i,s,d+1,o)}}return n}function pX(t){let e=lX.toString();return new Function(`return ${e}`)()(t)}var l3=new WeakMap;p3.quickSort=function(t,e,r=0){let n=l3.get(e);n===void 0&&(n=pX(e),l3.set(e,n)),n(t,e,r,t.length-1)}});var g3=y(Sl=>{var W=Ws(),t0=c3(),Vs=Qh().ArraySet,dX=Vh(),ko=d3().quickSort;function Ae(t,e){var r=t;return typeof t=="string"&&(r=W.parseSourceMapInput(t)),r.sections!=null?new cr(r,e):new rt(r,e)}Ae.fromSourceMap=function(t,e){return rt.fromSourceMap(t,e)};Ae.prototype._version=3;Ae.prototype.__generatedMappings=null;Object.defineProperty(Ae.prototype,"_generatedMappings",{configurable:!0,enumerable:!0,get:function(){return this.__generatedMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappings}});Ae.prototype.__originalMappings=null;Object.defineProperty(Ae.prototype,"_originalMappings",{configurable:!0,enumerable:!0,get:function(){return this.__originalMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappings}});Ae.prototype._charIsMappingSeparator=function(e,r){var n=e.charAt(r);return n===";"||n===","};Ae.prototype._parseMappings=function(e,r){throw new Error("Subclasses must implement _parseMappings")};Ae.GENERATED_ORDER=1;Ae.ORIGINAL_ORDER=2;Ae.GREATEST_LOWER_BOUND=1;Ae.LEAST_UPPER_BOUND=2;Ae.prototype.eachMapping=function(e,r,n){var i=r||null,s=n||Ae.GENERATED_ORDER,a;switch(s){case Ae.GENERATED_ORDER:a=this._generatedMappings;break;case Ae.ORIGINAL_ORDER:a=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}for(var o=this.sourceRoot,u=e.bind(i),c=this._names,l=this._sources,p=this._sourceMapURL,d=0,m=a.length;d<m;d++){var f=a[d],g=f.source===null?null:l.at(f.source);g!==null&&(g=W.computeSourceURL(o,g,p)),u({source:g,generatedLine:f.generatedLine,generatedColumn:f.generatedColumn,originalLine:f.originalLine,originalColumn:f.originalColumn,name:f.name===null?null:c.at(f.name)})}};Ae.prototype.allGeneratedPositionsFor=function(e){var r=W.getArg(e,"line"),n={source:W.getArg(e,"source"),originalLine:r,originalColumn:W.getArg(e,"column",0)};if(n.source=this._findSourceIndex(n.source),n.source<0)return[];var i=[],s=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",W.compareByOriginalPositions,t0.LEAST_UPPER_BOUND);if(s>=0){var a=this._originalMappings[s];if(e.column===void 0)for(var o=a.originalLine;a&&a.originalLine===o;)i.push({line:W.getArg(a,"generatedLine",null),column:W.getArg(a,"generatedColumn",null),lastColumn:W.getArg(a,"lastGeneratedColumn",null)}),a=this._originalMappings[++s];else for(var u=a.originalColumn;a&&a.originalLine===r&&a.originalColumn==u;)i.push({line:W.getArg(a,"generatedLine",null),column:W.getArg(a,"generatedColumn",null),lastColumn:W.getArg(a,"lastGeneratedColumn",null)}),a=this._originalMappings[++s]}return i};Sl.SourceMapConsumer=Ae;function rt(t,e){var r=t;typeof t=="string"&&(r=W.parseSourceMapInput(t));var n=W.getArg(r,"version"),i=W.getArg(r,"sources"),s=W.getArg(r,"names",[]),a=W.getArg(r,"sourceRoot",null),o=W.getArg(r,"sourcesContent",null),u=W.getArg(r,"mappings"),c=W.getArg(r,"file",null);if(n!=this._version)throw new Error("Unsupported version: "+n);a&&(a=W.normalize(a)),i=i.map(String).map(W.normalize).map(function(l){return a&&W.isAbsolute(a)&&W.isAbsolute(l)?W.relative(a,l):l}),this._names=Vs.fromArray(s.map(String),!0),this._sources=Vs.fromArray(i,!0),this._absoluteSources=this._sources.toArray().map(function(l){return W.computeSourceURL(a,l,e)}),this.sourceRoot=a,this.sourcesContent=o,this._mappings=u,this._sourceMapURL=e,this.file=c}rt.prototype=Object.create(Ae.prototype);rt.prototype.consumer=Ae;rt.prototype._findSourceIndex=function(t){var e=t;if(this.sourceRoot!=null&&(e=W.relative(this.sourceRoot,e)),this._sources.has(e))return this._sources.indexOf(e);var r;for(r=0;r<this._absoluteSources.length;++r)if(this._absoluteSources[r]==t)return r;return-1};rt.fromSourceMap=function(e,r){var n=Object.create(rt.prototype),i=n._names=Vs.fromArray(e._names.toArray(),!0),s=n._sources=Vs.fromArray(e._sources.toArray(),!0);n.sourceRoot=e._sourceRoot,n.sourcesContent=e._generateSourcesContent(n._sources.toArray(),n.sourceRoot),n.file=e._file,n._sourceMapURL=r,n._absoluteSources=n._sources.toArray().map(function(m){return W.computeSourceURL(n.sourceRoot,m,r)});for(var a=e._mappings.toArray().slice(),o=n.__generatedMappings=[],u=n.__originalMappings=[],c=0,l=a.length;c<l;c++){var p=a[c],d=new m3;d.generatedLine=p.generatedLine,d.generatedColumn=p.generatedColumn,p.source&&(d.source=s.indexOf(p.source),d.originalLine=p.originalLine,d.originalColumn=p.originalColumn,p.name&&(d.name=i.indexOf(p.name)),u.push(d)),o.push(d)}return ko(n.__originalMappings,W.compareByOriginalPositions),n};rt.prototype._version=3;Object.defineProperty(rt.prototype,"sources",{get:function(){return this._absoluteSources.slice()}});function m3(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}var e0=W.compareByGeneratedPositionsDeflatedNoLine;function f3(t,e){let r=t.length,n=t.length-e;if(!(n<=1))if(n==2){let i=t[e],s=t[e+1];e0(i,s)>0&&(t[e]=s,t[e+1]=i)}else if(n<20)for(let i=e;i<r;i++)for(let s=i;s>e;s--){let a=t[s-1],o=t[s];if(e0(a,o)<=0)break;t[s-1]=o,t[s]=a}else ko(t,e0,e)}rt.prototype._parseMappings=function(e,r){var n=1,i=0,s=0,a=0,o=0,u=0,c=e.length,l=0,p={},d={},m=[],f=[],g,h,T,R,S;let P=0;for(;l<c;)if(e.charAt(l)===";")n++,l++,i=0,f3(f,P),P=f.length;else if(e.charAt(l)===",")l++;else{for(g=new m3,g.generatedLine=n,R=l;R<c&&!this._charIsMappingSeparator(e,R);R++);for(h=e.slice(l,R),T=[];l<R;)dX.decode(e,l,d),S=d.value,l=d.rest,T.push(S);if(T.length===2)throw new Error("Found a source, but no line and column");if(T.length===3)throw new Error("Found a source and line, but no column");if(g.generatedColumn=i+T[0],i=g.generatedColumn,T.length>1&&(g.source=o+T[1],o+=T[1],g.originalLine=s+T[2],s=g.originalLine,g.originalLine+=1,g.originalColumn=a+T[3],a=g.originalColumn,T.length>4&&(g.name=u+T[4],u+=T[4])),f.push(g),typeof g.originalLine=="number"){let I=g.source;for(;m.length<=I;)m.push(null);m[I]===null&&(m[I]=[]),m[I].push(g)}}f3(f,P),this.__generatedMappings=f;for(var F=0;F<m.length;F++)m[F]!=null&&ko(m[F],W.compareByOriginalPositionsNoSource);this.__originalMappings=[].concat(...m)};rt.prototype._findMapping=function(e,r,n,i,s,a){if(e[n]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[n]);if(e[i]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[i]);return t0.search(e,r,s,a)};rt.prototype.computeColumnSpans=function(){for(var e=0;e<this._generatedMappings.length;++e){var r=this._generatedMappings[e];if(e+1<this._generatedMappings.length){var n=this._generatedMappings[e+1];if(r.generatedLine===n.generatedLine){r.lastGeneratedColumn=n.generatedColumn-1;continue}}r.lastGeneratedColumn=1/0}};rt.prototype.originalPositionFor=function(e){var r={generatedLine:W.getArg(e,"line"),generatedColumn:W.getArg(e,"column")},n=this._findMapping(r,this._generatedMappings,"generatedLine","generatedColumn",W.compareByGeneratedPositionsDeflated,W.getArg(e,"bias",Ae.GREATEST_LOWER_BOUND));if(n>=0){var i=this._generatedMappings[n];if(i.generatedLine===r.generatedLine){var s=W.getArg(i,"source",null);s!==null&&(s=this._sources.at(s),s=W.computeSourceURL(this.sourceRoot,s,this._sourceMapURL));var a=W.getArg(i,"name",null);return a!==null&&(a=this._names.at(a)),{source:s,line:W.getArg(i,"originalLine",null),column:W.getArg(i,"originalColumn",null),name:a}}}return{source:null,line:null,column:null,name:null}};rt.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return e==null}):!1};rt.prototype.sourceContentFor=function(e,r){if(!this.sourcesContent)return null;var n=this._findSourceIndex(e);if(n>=0)return this.sourcesContent[n];var i=e;this.sourceRoot!=null&&(i=W.relative(this.sourceRoot,i));var s;if(this.sourceRoot!=null&&(s=W.urlParse(this.sourceRoot))){var a=i.replace(/^file:\/\//,"");if(s.scheme=="file"&&this._sources.has(a))return this.sourcesContent[this._sources.indexOf(a)];if((!s.path||s.path=="/")&&this._sources.has("/"+i))return this.sourcesContent[this._sources.indexOf("/"+i)]}if(r)return null;throw new Error('"'+i+'" is not in the SourceMap.')};rt.prototype.generatedPositionFor=function(e){var r=W.getArg(e,"source");if(r=this._findSourceIndex(r),r<0)return{line:null,column:null,lastColumn:null};var n={source:r,originalLine:W.getArg(e,"line"),originalColumn:W.getArg(e,"column")},i=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",W.compareByOriginalPositions,W.getArg(e,"bias",Ae.GREATEST_LOWER_BOUND));if(i>=0){var s=this._originalMappings[i];if(s.source===n.source)return{line:W.getArg(s,"generatedLine",null),column:W.getArg(s,"generatedColumn",null),lastColumn:W.getArg(s,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}};Sl.BasicSourceMapConsumer=rt;function cr(t,e){var r=t;typeof t=="string"&&(r=W.parseSourceMapInput(t));var n=W.getArg(r,"version"),i=W.getArg(r,"sections");if(n!=this._version)throw new Error("Unsupported version: "+n);this._sources=new Vs,this._names=new Vs;var s={line:-1,column:0};this._sections=i.map(function(a){if(a.url)throw new Error("Support for url field in sections not implemented.");var o=W.getArg(a,"offset"),u=W.getArg(o,"line"),c=W.getArg(o,"column");if(u<s.line||u===s.line&&c<s.column)throw new Error("Section offsets must be ordered and non-overlapping.");return s=o,{generatedOffset:{generatedLine:u+1,generatedColumn:c+1},consumer:new Ae(W.getArg(a,"map"),e)}})}cr.prototype=Object.create(Ae.prototype);cr.prototype.constructor=Ae;cr.prototype._version=3;Object.defineProperty(cr.prototype,"sources",{get:function(){for(var t=[],e=0;e<this._sections.length;e++)for(var r=0;r<this._sections[e].consumer.sources.length;r++)t.push(this._sections[e].consumer.sources[r]);return t}});cr.prototype.originalPositionFor=function(e){var r={generatedLine:W.getArg(e,"line"),generatedColumn:W.getArg(e,"column")},n=t0.search(r,this._sections,function(s,a){var o=s.generatedLine-a.generatedOffset.generatedLine;return o||s.generatedColumn-a.generatedOffset.generatedColumn}),i=this._sections[n];return i?i.consumer.originalPositionFor({line:r.generatedLine-(i.generatedOffset.generatedLine-1),column:r.generatedColumn-(i.generatedOffset.generatedLine===r.generatedLine?i.generatedOffset.generatedColumn-1:0),bias:e.bias}):{source:null,line:null,column:null,name:null}};cr.prototype.hasContentsOfAllSources=function(){return this._sections.every(function(e){return e.consumer.hasContentsOfAllSources()})};cr.prototype.sourceContentFor=function(e,r){for(var n=0;n<this._sections.length;n++){var i=this._sections[n],s=i.consumer.sourceContentFor(e,!0);if(s||s==="")return s}if(r)return null;throw new Error('"'+e+'" is not in the SourceMap.')};cr.prototype.generatedPositionFor=function(e){for(var r=0;r<this._sections.length;r++){var n=this._sections[r];if(n.consumer._findSourceIndex(W.getArg(e,"source"))!==-1){var i=n.consumer.generatedPositionFor(e);if(i){var s={line:i.line+(n.generatedOffset.generatedLine-1),column:i.column+(n.generatedOffset.generatedLine===i.line?n.generatedOffset.generatedColumn-1:0)};return s}}}return{line:null,column:null}};cr.prototype._parseMappings=function(e,r){this.__generatedMappings=[],this.__originalMappings=[];for(var n=0;n<this._sections.length;n++)for(var i=this._sections[n],s=i.consumer._generatedMappings,a=0;a<s.length;a++){var o=s[a],u=i.consumer._sources.at(o.source);u!==null&&(u=W.computeSourceURL(i.consumer.sourceRoot,u,this._sourceMapURL)),this._sources.add(u),u=this._sources.indexOf(u);var c=null;o.name&&(c=i.consumer._names.at(o.name),this._names.add(c),c=this._names.indexOf(c));var l={source:u,generatedLine:o.generatedLine+(i.generatedOffset.generatedLine-1),generatedColumn:o.generatedColumn+(i.generatedOffset.generatedLine===o.generatedLine?i.generatedOffset.generatedColumn-1:0),originalLine:o.originalLine,originalColumn:o.originalColumn,name:c};this.__generatedMappings.push(l),typeof l.originalLine=="number"&&this.__originalMappings.push(l)}ko(this.__generatedMappings,W.compareByGeneratedPositionsDeflated),ko(this.__originalMappings,W.compareByOriginalPositions)};Sl.IndexedSourceMapConsumer=cr});var b3=y(h3=>{var fX=Yh().SourceMapGenerator,kl=Ws(),mX=/(\r?\n)/,gX=10,Js="$$$isSourceNode$$$";function Lt(t,e,r,n,i){this.children=[],this.sourceContents={},this.line=t??null,this.column=e??null,this.source=r??null,this.name=i??null,this[Js]=!0,n!=null&&this.add(n)}Lt.fromStringWithSourceMap=function(e,r,n){var i=new Lt,s=e.split(mX),a=0,o=function(){var d=f(),m=f()||"";return d+m;function f(){return a<s.length?s[a++]:void 0}},u=1,c=0,l=null;return r.eachMapping(function(d){if(l!==null)if(u<d.generatedLine)p(l,o()),u++,c=0;else{var m=s[a]||"",f=m.substr(0,d.generatedColumn-c);s[a]=m.substr(d.generatedColumn-c),c=d.generatedColumn,p(l,f),l=d;return}for(;u<d.generatedLine;)i.add(o()),u++;if(c<d.generatedColumn){var m=s[a]||"";i.add(m.substr(0,d.generatedColumn)),s[a]=m.substr(d.generatedColumn),c=d.generatedColumn}l=d},this),a<s.length&&(l&&p(l,o()),i.add(s.splice(a).join(""))),r.sources.forEach(function(d){var m=r.sourceContentFor(d);m!=null&&(n!=null&&(d=kl.join(n,d)),i.setSourceContent(d,m))}),i;function p(d,m){if(d===null||d.source===void 0)i.add(m);else{var f=n?kl.join(n,d.source):d.source;i.add(new Lt(d.originalLine,d.originalColumn,f,m,d.name))}}};Lt.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(r){this.add(r)},this);else if(e[Js]||typeof e=="string")e&&this.children.push(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this};Lt.prototype.prepend=function(e){if(Array.isArray(e))for(var r=e.length-1;r>=0;r--)this.prepend(e[r]);else if(e[Js]||typeof e=="string")this.children.unshift(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this};Lt.prototype.walk=function(e){for(var r,n=0,i=this.children.length;n<i;n++)r=this.children[n],r[Js]?r.walk(e):r!==""&&e(r,{source:this.source,line:this.line,column:this.column,name:this.name})};Lt.prototype.join=function(e){var r,n,i=this.children.length;if(i>0){for(r=[],n=0;n<i-1;n++)r.push(this.children[n]),r.push(e);r.push(this.children[n]),this.children=r}return this};Lt.prototype.replaceRight=function(e,r){var n=this.children[this.children.length-1];return n[Js]?n.replaceRight(e,r):typeof n=="string"?this.children[this.children.length-1]=n.replace(e,r):this.children.push("".replace(e,r)),this};Lt.prototype.setSourceContent=function(e,r){this.sourceContents[kl.toSetString(e)]=r};Lt.prototype.walkSourceContents=function(e){for(var r=0,n=this.children.length;r<n;r++)this.children[r][Js]&&this.children[r].walkSourceContents(e);for(var i=Object.keys(this.sourceContents),r=0,n=i.length;r<n;r++)e(kl.fromSetString(i[r]),this.sourceContents[i[r]])};Lt.prototype.toString=function(){var e="";return this.walk(function(r){e+=r}),e};Lt.prototype.toStringWithSourceMap=function(e){var r={code:"",line:1,column:0},n=new fX(e),i=!1,s=null,a=null,o=null,u=null;return this.walk(function(c,l){r.code+=c,l.source!==null&&l.line!==null&&l.column!==null?((s!==l.source||a!==l.line||o!==l.column||u!==l.name)&&n.addMapping({source:l.source,original:{line:l.line,column:l.column},generated:{line:r.line,column:r.column},name:l.name}),s=l.source,a=l.line,o=l.column,u=l.name,i=!0):i&&(n.addMapping({generated:{line:r.line,column:r.column}}),s=null,i=!1);for(var p=0,d=c.length;p<d;p++)c.charCodeAt(p)===gX?(r.line++,r.column=0,p+1===d?(s=null,i=!1):i&&n.addMapping({source:l.source,original:{line:l.line,column:l.column},generated:{line:r.line,column:r.column},name:l.name})):r.column++}),this.walkSourceContents(function(c,l){n.setSourceContent(c,l)}),{code:r.code,map:n}};h3.SourceNode=Lt});var Al=y(Rl=>{Rl.SourceMapGenerator=Yh().SourceMapGenerator;Rl.SourceMapConsumer=g3().SourceMapConsumer;Rl.SourceNode=b3().SourceNode});var n0=y((nae,w3)=>{"use strict";var{existsSync:hX,readFileSync:bX}=require("fs"),{dirname:r0,join:yX}=require("path"),{SourceMapConsumer:y3,SourceMapGenerator:v3}=Al();function vX(t){return Buffer?Buffer.from(t,"base64").toString():window.atob(t)}var Ro=class{constructor(e,r){if(r.map===!1)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");let n=r.map?r.map.prev:void 0,i=this.loadMap(r.from,n);!this.mapFile&&r.from&&(this.mapFile=r.from),this.mapFile&&(this.root=r0(this.mapFile)),i&&(this.text=i)}consumer(){return this.consumerCache||(this.consumerCache=new y3(this.text)),this.consumerCache}decodeInline(e){let r=/^data:application\/json;charset=utf-?8;base64,/,n=/^data:application\/json;base64,/,i=/^data:application\/json;charset=utf-?8,/,s=/^data:application\/json,/,a=e.match(i)||e.match(s);if(a)return decodeURIComponent(e.substr(a[0].length));let o=e.match(r)||e.match(n);if(o)return vX(e.substr(o[0].length));let u=e.slice(22);throw u=u.slice(0,u.indexOf(",")),new Error("Unsupported source map encoding "+u)}getAnnotationURL(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(e){return typeof e!="object"?!1:typeof e.mappings=="string"||typeof e._mappings=="string"||Array.isArray(e.sections)}loadAnnotation(e){let r=e.match(/\/\*\s*# sourceMappingURL=/g);if(!r)return;let n=e.lastIndexOf(r.pop()),i=e.indexOf("*/",n);n>-1&&i>-1&&(this.annotation=this.getAnnotationURL(e.substring(n,i)))}loadFile(e){if(this.root=r0(e),hX(e))return this.mapFile=e,bX(e,"utf-8").toString().trim()}loadMap(e,r){if(r===!1)return!1;if(r){if(typeof r=="string")return r;if(typeof r=="function"){let n=r(e);if(n){let i=this.loadFile(n);if(!i)throw new Error("Unable to load previous source map: "+n.toString());return i}}else{if(r instanceof y3)return v3.fromSourceMap(r).toString();if(r instanceof v3)return r.toString();if(this.isMap(r))return JSON.stringify(r);throw new Error("Unsupported previous source map format: "+r.toString())}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let n=this.annotation;return e&&(n=yX(r0(e),n)),this.loadFile(n)}}}startWith(e,r){return e?e.substr(0,r.length)===r:!1}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};w3.exports=Ro;Ro.default=Ro});var Ao=y((iae,S3)=>{"use strict";var{nanoid:wX}=WA(),{isAbsolute:a0,resolve:o0}=require("path"),{SourceMapConsumer:xX,SourceMapGenerator:_X}=Al(),{fileURLToPath:x3,pathToFileURL:Pl}=require("url"),_3=vl(),EX=n0(),i0=Mh(),s0=Symbol("lineToIndexCache"),TX=!!(xX&&_X),E3=!!(o0&&a0);function T3(t){if(t[s0])return t[s0];let e=t.css.split(`
|
|
99
|
+
`?(r=1,n+=1):r+=1;return{column:r,line:n,offset:a}}prev(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e-1]}rangeBy(e={}){let r="document"in this.source.input?this.source.input.document:this.source.input.css,n={column:this.source.start.column,line:this.source.start.line,offset:Xr(r,this.source.start)},i=this.source.end?{column:this.source.end.column+1,line:this.source.end.line,offset:typeof this.source.end.offset=="number"?this.source.end.offset:Xr(r,this.source.end)+1}:{column:n.column+1,line:n.line,offset:n.offset+1};if(e.word){let a=r.slice(Xr(r,this.source.start),Xr(r,this.source.end)).indexOf(e.word);a!==-1&&(n=this.positionInside(a),i=this.positionInside(a+e.word.length))}else e.start?n={column:e.start.column,line:e.start.line,offset:Xr(r,e.start)}:e.index&&(n=this.positionInside(e.index)),e.end?i={column:e.end.column,line:e.end.line,offset:Xr(r,e.end)}:typeof e.endIndex=="number"?i=this.positionInside(e.endIndex):e.index&&(i=this.positionInside(e.index+1));return(i.line<n.line||i.line===n.line&&i.column<=n.column)&&(i={column:n.column+1,line:n.line,offset:n.offset+1}),{end:i,start:n}}raw(e,r){return new FJ().raw(this,e,r)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...e){if(this.parent){let r=this,n=!1;for(let i of e)i===this?n=!0:n?(this.parent.insertAfter(r,i),r=i):this.parent.insertBefore(r,i);n||this.remove()}return this}root(){let e=this;for(;e.parent&&e.parent.type!=="document";)e=e.parent;return e}toJSON(e,r){let n={},i=r==null;r=r||new Map;let s=0;for(let a in this){if(!Object.prototype.hasOwnProperty.call(this,a)||a==="parent"||a==="proxyCache")continue;let o=this[a];if(Array.isArray(o))n[a]=o.map(u=>typeof u=="object"&&u.toJSON?u.toJSON(null,r):u);else if(typeof o=="object"&&o.toJSON)n[a]=o.toJSON(null,r);else if(a==="source"){if(o==null)continue;let u=r.get(o.input);u==null&&(u=s,r.set(o.input,s),s++),n[a]={end:o.end,inputId:u,start:o.start}}else n[a]=o}return i&&(n.inputs=[...r.keys()].map(a=>a.toJSON())),n}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=MJ){e.stringify&&(e=e.stringify);let r="";return e(this,n=>{r+=n}),r}warn(e,r,n={}){let i={node:this};for(let s in n)i[s]=n[s];return e.warn(r,i)}};AA.exports=yo;yo.default=yo});var xo=y((Use,PA)=>{"use strict";var qJ=vo(),wo=class extends qJ{constructor(e){super(e),this.type="comment"}};PA.exports=wo;wo.default=wo});var Eo=y((Gse,CA)=>{"use strict";var UJ=vo(),_o=class extends UJ{get variable(){return this.prop.startsWith("--")||this.prop[0]==="$"}constructor(e){e&&typeof e.value<"u"&&typeof e.value!="string"&&(e={...e,value:String(e.value)}),super(e),this.type="decl"}};CA.exports=_o;_o.default=_o});var kn=y((Bse,qA)=>{"use strict";var OA=xo(),IA=Eo(),GJ=vo(),{isClean:LA,my:DA}=wl(),Bh,NA,FA,Hh;function MA(t){return t.map(e=>(e.nodes&&(e.nodes=MA(e.nodes)),delete e.source,e))}function jA(t){if(t[LA]=!1,t.proxyOf.nodes)for(let e of t.proxyOf.nodes)jA(e)}var ur=class t extends GJ{get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}append(...e){for(let r of e){let n=this.normalize(r,this.last);for(let i of n)this.proxyOf.nodes.push(i)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let r of this.nodes)r.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let r=this.getIterator(),n,i;for(;this.indexes[r]<this.proxyOf.nodes.length&&(n=this.indexes[r],i=e(this.proxyOf.nodes[n],n),i!==!1);)this.indexes[r]+=1;return delete this.indexes[r],i}every(e){return this.nodes.every(e)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let e=this.lastEach;return this.indexes[e]=0,e}getProxyProcessor(){return{get(e,r){return r==="proxyOf"?e:e[r]?r==="each"||typeof r=="string"&&r.startsWith("walk")?(...n)=>e[r](...n.map(i=>typeof i=="function"?(s,a)=>i(s.toProxy(),a):i)):r==="every"||r==="some"?n=>e[r]((i,...s)=>n(i.toProxy(),...s)):r==="root"?()=>e.root().toProxy():r==="nodes"?e.nodes.map(n=>n.toProxy()):r==="first"||r==="last"?e[r].toProxy():e[r]:e[r]},set(e,r,n){return e[r]===n||(e[r]=n,(r==="name"||r==="params"||r==="selector")&&e.markDirty()),!0}}}index(e){return typeof e=="number"?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,r){let n=this.index(e),i=this.normalize(r,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(let a of i)this.proxyOf.nodes.splice(n+1,0,a);let s;for(let a in this.indexes)s=this.indexes[a],n<s&&(this.indexes[a]=s+i.length);return this.markDirty(),this}insertBefore(e,r){let n=this.index(e),i=n===0?"prepend":!1,s=this.normalize(r,this.proxyOf.nodes[n],i).reverse();n=this.index(e);for(let o of s)this.proxyOf.nodes.splice(n,0,o);let a;for(let o in this.indexes)a=this.indexes[o],n<=a&&(this.indexes[o]=a+s.length);return this.markDirty(),this}normalize(e,r){if(typeof e=="string")e=MA(NA(e).nodes);else if(typeof e>"u")e=[];else if(Array.isArray(e)){e=e.slice(0);for(let i of e)i.parent&&i.parent.removeChild(i,"ignore")}else if(e.type==="root"&&this.type!=="document"){e=e.nodes.slice(0);for(let i of e)i.parent&&i.parent.removeChild(i,"ignore")}else if(e.type)e=[e];else if(e.prop){if(typeof e.value>"u")throw new Error("Value field is missed in node creation");typeof e.value!="string"&&(e.value=String(e.value)),e=[new IA(e)]}else if(e.selector||e.selectors)e=[new Hh(e)];else if(e.name)e=[new Bh(e)];else if(e.text)e=[new OA(e)];else throw new Error("Unknown node type in node creation");return e.map(i=>(i[DA]||t.rebuild(i),i=i.proxyOf,i.parent&&i.parent.removeChild(i),i[LA]&&jA(i),i.raws||(i.raws={}),typeof i.raws.before>"u"&&r&&typeof r.raws.before<"u"&&(i.raws.before=r.raws.before.replace(/\S/g,"")),i.parent=this.proxyOf,i))}prepend(...e){e=e.reverse();for(let r of e){let n=this.normalize(r,this.first,"prepend").reverse();for(let i of n)this.proxyOf.nodes.unshift(i);for(let i in this.indexes)this.indexes[i]=this.indexes[i]+n.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);let r;for(let n in this.indexes)r=this.indexes[n],r>=e&&(this.indexes[n]=r-1);return this.markDirty(),this}replaceValues(e,r,n){return n||(n=r,r={}),this.walkDecls(i=>{r.props&&!r.props.includes(i.prop)||r.fast&&!i.value.includes(r.fast)||(i.value=i.value.replace(e,n))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((r,n)=>{let i;try{i=e(r,n)}catch(s){throw r.addToError(s)}return i!==!1&&r.walk&&(i=r.walk(e)),i})}walkAtRules(e,r){return r?e instanceof RegExp?this.walk((n,i)=>{if(n.type==="atrule"&&e.test(n.name))return r(n,i)}):this.walk((n,i)=>{if(n.type==="atrule"&&n.name===e)return r(n,i)}):(r=e,this.walk((n,i)=>{if(n.type==="atrule")return r(n,i)}))}walkComments(e){return this.walk((r,n)=>{if(r.type==="comment")return e(r,n)})}walkDecls(e,r){return r?e instanceof RegExp?this.walk((n,i)=>{if(n.type==="decl"&&e.test(n.prop))return r(n,i)}):this.walk((n,i)=>{if(n.type==="decl"&&n.prop===e)return r(n,i)}):(r=e,this.walk((n,i)=>{if(n.type==="decl")return r(n,i)}))}walkRules(e,r){return r?e instanceof RegExp?this.walk((n,i)=>{if(n.type==="rule"&&e.test(n.selector))return r(n,i)}):this.walk((n,i)=>{if(n.type==="rule"&&n.selector===e)return r(n,i)}):(r=e,this.walk((n,i)=>{if(n.type==="rule")return r(n,i)}))}};ur.registerParse=t=>{NA=t};ur.registerRule=t=>{Hh=t};ur.registerAtRule=t=>{Bh=t};ur.registerRoot=t=>{FA=t};qA.exports=ur;ur.default=ur;ur.rebuild=t=>{t.type==="atrule"?Object.setPrototypeOf(t,Bh.prototype):t.type==="rule"?Object.setPrototypeOf(t,Hh.prototype):t.type==="decl"?Object.setPrototypeOf(t,IA.prototype):t.type==="comment"?Object.setPrototypeOf(t,OA.prototype):t.type==="root"&&Object.setPrototypeOf(t,FA.prototype),t[DA]=!0,t.nodes&&t.nodes.forEach(e=>{ur.rebuild(e)})}});var xl=y((Hse,GA)=>{"use strict";var UA=kn(),$s=class extends UA{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};GA.exports=$s;$s.default=$s;UA.registerAtRule($s)});var _l=y(($se,$A)=>{"use strict";var BJ=kn(),BA,HA,Ai=class extends BJ{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new BA(new HA,this,e).stringify()}};Ai.registerLazyResult=t=>{BA=t};Ai.registerProcessor=t=>{HA=t};$A.exports=Ai;Ai.default=Ai});var WA=y((zse,zA)=>{var HJ="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",$J=(t,e=21)=>(r=e)=>{let n="",i=r|0;for(;i--;)n+=t[Math.random()*t.length|0];return n},zJ=(t=21)=>{let e="",r=t|0;for(;r--;)e+=HJ[Math.random()*64|0];return e};zA.exports={nanoid:zJ,customAlphabet:$J}});var JA=y($h=>{var VA="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");$h.encode=function(t){if(0<=t&&t<VA.length)return VA[t];throw new TypeError("Must be between 0 and 63: "+t)};$h.decode=function(t){var e=65,r=90,n=97,i=122,s=48,a=57,o=43,u=47,c=26,l=52;return e<=t&&t<=r?t-e:n<=t&&t<=i?t-n+c:s<=t&&t<=a?t-s+l:t==o?62:t==u?63:-1}});var Vh=y(Wh=>{var XA=JA(),zh=5,KA=1<<zh,QA=KA-1,YA=KA;function WJ(t){return t<0?(-t<<1)+1:(t<<1)+0}function VJ(t){var e=(t&1)===1,r=t>>1;return e?-r:r}Wh.encode=function(e){var r="",n,i=WJ(e);do n=i&QA,i>>>=zh,i>0&&(n|=YA),r+=XA.encode(n);while(i>0);return r};Wh.decode=function(e,r,n){var i=e.length,s=0,a=0,o,u;do{if(r>=i)throw new Error("Expected more digits in base 64 VLQ value.");if(u=XA.decode(e.charCodeAt(r++)),u===-1)throw new Error("Invalid base64 digit: "+e.charAt(r-1));o=!!(u&YA),u&=QA,s=s+(u<<a),a+=zh}while(o);n.value=VJ(s),n.rest=r}});var Ws=y(Qe=>{function JJ(t,e,r){if(e in t)return t[e];if(arguments.length===3)return r;throw new Error('"'+e+'" is a required argument.')}Qe.getArg=JJ;var ZA=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,XJ=/^data:.+\,.+$/;function To(t){var e=t.match(ZA);return e?{scheme:e[1],auth:e[2],host:e[3],port:e[4],path:e[5]}:null}Qe.urlParse=To;function zs(t){var e="";return t.scheme&&(e+=t.scheme+":"),e+="//",t.auth&&(e+=t.auth+"@"),t.host&&(e+=t.host),t.port&&(e+=":"+t.port),t.path&&(e+=t.path),e}Qe.urlGenerate=zs;var KJ=32;function QJ(t){var e=[];return function(r){for(var n=0;n<e.length;n++)if(e[n].input===r){var i=e[0];return e[0]=e[n],e[n]=i,e[0].result}var s=t(r);return e.unshift({input:r,result:s}),e.length>KJ&&e.pop(),s}}var Jh=QJ(function(e){var r=e,n=To(e);if(n){if(!n.path)return e;r=n.path}for(var i=Qe.isAbsolute(r),s=[],a=0,o=0;;)if(a=o,o=r.indexOf("/",a),o===-1){s.push(r.slice(a));break}else for(s.push(r.slice(a,o));o<r.length&&r[o]==="/";)o++;for(var u,c=0,o=s.length-1;o>=0;o--)u=s[o],u==="."?s.splice(o,1):u===".."?c++:c>0&&(u===""?(s.splice(o+1,c),c=0):(s.splice(o,2),c--));return r=s.join("/"),r===""&&(r=i?"/":"."),n?(n.path=r,zs(n)):r});Qe.normalize=Jh;function e3(t,e){t===""&&(t="."),e===""&&(e=".");var r=To(e),n=To(t);if(n&&(t=n.path||"/"),r&&!r.scheme)return n&&(r.scheme=n.scheme),zs(r);if(r||e.match(XJ))return e;if(n&&!n.host&&!n.path)return n.host=e,zs(n);var i=e.charAt(0)==="/"?e:Jh(t.replace(/\/+$/,"")+"/"+e);return n?(n.path=i,zs(n)):i}Qe.join=e3;Qe.isAbsolute=function(t){return t.charAt(0)==="/"||ZA.test(t)};function YJ(t,e){t===""&&(t="."),t=t.replace(/\/$/,"");for(var r=0;e.indexOf(t+"/")!==0;){var n=t.lastIndexOf("/");if(n<0||(t=t.slice(0,n),t.match(/^([^\/]+:\/)?\/*$/)))return e;++r}return Array(r+1).join("../")+e.substr(t.length+1)}Qe.relative=YJ;var t3=(function(){var t=Object.create(null);return!("__proto__"in t)})();function r3(t){return t}function ZJ(t){return n3(t)?"$"+t:t}Qe.toSetString=t3?r3:ZJ;function eX(t){return n3(t)?t.slice(1):t}Qe.fromSetString=t3?r3:eX;function n3(t){if(!t)return!1;var e=t.length;if(e<9||t.charCodeAt(e-1)!==95||t.charCodeAt(e-2)!==95||t.charCodeAt(e-3)!==111||t.charCodeAt(e-4)!==116||t.charCodeAt(e-5)!==111||t.charCodeAt(e-6)!==114||t.charCodeAt(e-7)!==112||t.charCodeAt(e-8)!==95||t.charCodeAt(e-9)!==95)return!1;for(var r=e-10;r>=0;r--)if(t.charCodeAt(r)!==36)return!1;return!0}function tX(t,e,r){var n=Kr(t.source,e.source);return n!==0||(n=t.originalLine-e.originalLine,n!==0)||(n=t.originalColumn-e.originalColumn,n!==0||r)||(n=t.generatedColumn-e.generatedColumn,n!==0)||(n=t.generatedLine-e.generatedLine,n!==0)?n:Kr(t.name,e.name)}Qe.compareByOriginalPositions=tX;function rX(t,e,r){var n;return n=t.originalLine-e.originalLine,n!==0||(n=t.originalColumn-e.originalColumn,n!==0||r)||(n=t.generatedColumn-e.generatedColumn,n!==0)||(n=t.generatedLine-e.generatedLine,n!==0)?n:Kr(t.name,e.name)}Qe.compareByOriginalPositionsNoSource=rX;function nX(t,e,r){var n=t.generatedLine-e.generatedLine;return n!==0||(n=t.generatedColumn-e.generatedColumn,n!==0||r)||(n=Kr(t.source,e.source),n!==0)||(n=t.originalLine-e.originalLine,n!==0)||(n=t.originalColumn-e.originalColumn,n!==0)?n:Kr(t.name,e.name)}Qe.compareByGeneratedPositionsDeflated=nX;function iX(t,e,r){var n=t.generatedColumn-e.generatedColumn;return n!==0||r||(n=Kr(t.source,e.source),n!==0)||(n=t.originalLine-e.originalLine,n!==0)||(n=t.originalColumn-e.originalColumn,n!==0)?n:Kr(t.name,e.name)}Qe.compareByGeneratedPositionsDeflatedNoLine=iX;function Kr(t,e){return t===e?0:t===null?1:e===null?-1:t>e?1:-1}function sX(t,e){var r=t.generatedLine-e.generatedLine;return r!==0||(r=t.generatedColumn-e.generatedColumn,r!==0)||(r=Kr(t.source,e.source),r!==0)||(r=t.originalLine-e.originalLine,r!==0)||(r=t.originalColumn-e.originalColumn,r!==0)?r:Kr(t.name,e.name)}Qe.compareByGeneratedPositionsInflated=sX;function aX(t){return JSON.parse(t.replace(/^\)]}'[^\n]*\n/,""))}Qe.parseSourceMapInput=aX;function oX(t,e,r){if(e=e||"",t&&(t[t.length-1]!=="/"&&e[0]!=="/"&&(t+="/"),e=t+e),r){var n=To(r);if(!n)throw new Error("sourceMapURL could not be parsed");if(n.path){var i=n.path.lastIndexOf("/");i>=0&&(n.path=n.path.substring(0,i+1))}e=e3(zs(n),e)}return Jh(e)}Qe.computeSourceURL=oX});var Qh=y(i3=>{var Xh=Ws(),Kh=Object.prototype.hasOwnProperty,Pi=typeof Map<"u";function Qr(){this._array=[],this._set=Pi?new Map:Object.create(null)}Qr.fromArray=function(e,r){for(var n=new Qr,i=0,s=e.length;i<s;i++)n.add(e[i],r);return n};Qr.prototype.size=function(){return Pi?this._set.size:Object.getOwnPropertyNames(this._set).length};Qr.prototype.add=function(e,r){var n=Pi?e:Xh.toSetString(e),i=Pi?this.has(e):Kh.call(this._set,n),s=this._array.length;(!i||r)&&this._array.push(e),i||(Pi?this._set.set(e,s):this._set[n]=s)};Qr.prototype.has=function(e){if(Pi)return this._set.has(e);var r=Xh.toSetString(e);return Kh.call(this._set,r)};Qr.prototype.indexOf=function(e){if(Pi){var r=this._set.get(e);if(r>=0)return r}else{var n=Xh.toSetString(e);if(Kh.call(this._set,n))return this._set[n]}throw new Error('"'+e+'" is not in the set.')};Qr.prototype.at=function(e){if(e>=0&&e<this._array.length)return this._array[e];throw new Error("No element indexed by "+e)};Qr.prototype.toArray=function(){return this._array.slice()};i3.ArraySet=Qr});var o3=y(a3=>{var s3=Ws();function uX(t,e){var r=t.generatedLine,n=e.generatedLine,i=t.generatedColumn,s=e.generatedColumn;return n>r||n==r&&s>=i||s3.compareByGeneratedPositionsInflated(t,e)<=0}function El(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}El.prototype.unsortedForEach=function(e,r){this._array.forEach(e,r)};El.prototype.add=function(e){uX(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))};El.prototype.toArray=function(){return this._sorted||(this._array.sort(s3.compareByGeneratedPositionsInflated),this._sorted=!0),this._array};a3.MappingList=El});var Yh=y(u3=>{var So=Vh(),Fe=Ws(),Tl=Qh().ArraySet,cX=o3().MappingList;function Wt(t){t||(t={}),this._file=Fe.getArg(t,"file",null),this._sourceRoot=Fe.getArg(t,"sourceRoot",null),this._skipValidation=Fe.getArg(t,"skipValidation",!1),this._ignoreInvalidMapping=Fe.getArg(t,"ignoreInvalidMapping",!1),this._sources=new Tl,this._names=new Tl,this._mappings=new cX,this._sourcesContents=null}Wt.prototype._version=3;Wt.fromSourceMap=function(e,r){var n=e.sourceRoot,i=new Wt(Object.assign(r||{},{file:e.file,sourceRoot:n}));return e.eachMapping(function(s){var a={generated:{line:s.generatedLine,column:s.generatedColumn}};s.source!=null&&(a.source=s.source,n!=null&&(a.source=Fe.relative(n,a.source)),a.original={line:s.originalLine,column:s.originalColumn},s.name!=null&&(a.name=s.name)),i.addMapping(a)}),e.sources.forEach(function(s){var a=s;n!==null&&(a=Fe.relative(n,s)),i._sources.has(a)||i._sources.add(a);var o=e.sourceContentFor(s);o!=null&&i.setSourceContent(s,o)}),i};Wt.prototype.addMapping=function(e){var r=Fe.getArg(e,"generated"),n=Fe.getArg(e,"original",null),i=Fe.getArg(e,"source",null),s=Fe.getArg(e,"name",null);!this._skipValidation&&this._validateMapping(r,n,i,s)===!1||(i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),s!=null&&(s=String(s),this._names.has(s)||this._names.add(s)),this._mappings.add({generatedLine:r.line,generatedColumn:r.column,originalLine:n!=null&&n.line,originalColumn:n!=null&&n.column,source:i,name:s}))};Wt.prototype.setSourceContent=function(e,r){var n=e;this._sourceRoot!=null&&(n=Fe.relative(this._sourceRoot,n)),r!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[Fe.toSetString(n)]=r):this._sourcesContents&&(delete this._sourcesContents[Fe.toSetString(n)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))};Wt.prototype.applySourceMap=function(e,r,n){var i=r;if(r==null){if(e.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);i=e.file}var s=this._sourceRoot;s!=null&&(i=Fe.relative(s,i));var a=new Tl,o=new Tl;this._mappings.unsortedForEach(function(u){if(u.source===i&&u.originalLine!=null){var c=e.originalPositionFor({line:u.originalLine,column:u.originalColumn});c.source!=null&&(u.source=c.source,n!=null&&(u.source=Fe.join(n,u.source)),s!=null&&(u.source=Fe.relative(s,u.source)),u.originalLine=c.line,u.originalColumn=c.column,c.name!=null&&(u.name=c.name))}var l=u.source;l!=null&&!a.has(l)&&a.add(l);var p=u.name;p!=null&&!o.has(p)&&o.add(p)},this),this._sources=a,this._names=o,e.sources.forEach(function(u){var c=e.sourceContentFor(u);c!=null&&(n!=null&&(u=Fe.join(n,u)),s!=null&&(u=Fe.relative(s,u)),this.setSourceContent(u,c))},this)};Wt.prototype._validateMapping=function(e,r,n,i){if(r&&typeof r.line!="number"&&typeof r.column!="number"){var s="original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.";if(this._ignoreInvalidMapping)return typeof console<"u"&&console.warn&&console.warn(s),!1;throw new Error(s)}if(!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!r&&!n&&!i)){if(e&&"line"in e&&"column"in e&&r&&"line"in r&&"column"in r&&e.line>0&&e.column>=0&&r.line>0&&r.column>=0&&n)return;var s="Invalid mapping: "+JSON.stringify({generated:e,source:n,original:r,name:i});if(this._ignoreInvalidMapping)return typeof console<"u"&&console.warn&&console.warn(s),!1;throw new Error(s)}};Wt.prototype._serializeMappings=function(){for(var e=0,r=1,n=0,i=0,s=0,a=0,o="",u,c,l,p,d=this._mappings.toArray(),m=0,f=d.length;m<f;m++){if(c=d[m],u="",c.generatedLine!==r)for(e=0;c.generatedLine!==r;)u+=";",r++;else if(m>0){if(!Fe.compareByGeneratedPositionsInflated(c,d[m-1]))continue;u+=","}u+=So.encode(c.generatedColumn-e),e=c.generatedColumn,c.source!=null&&(p=this._sources.indexOf(c.source),u+=So.encode(p-a),a=p,u+=So.encode(c.originalLine-1-i),i=c.originalLine-1,u+=So.encode(c.originalColumn-n),n=c.originalColumn,c.name!=null&&(l=this._names.indexOf(c.name),u+=So.encode(l-s),s=l)),o+=u}return o};Wt.prototype._generateSourcesContent=function(e,r){return e.map(function(n){if(!this._sourcesContents)return null;r!=null&&(n=Fe.relative(r,n));var i=Fe.toSetString(n);return Object.prototype.hasOwnProperty.call(this._sourcesContents,i)?this._sourcesContents[i]:null},this)};Wt.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(e.file=this._file),this._sourceRoot!=null&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e};Wt.prototype.toString=function(){return JSON.stringify(this.toJSON())};u3.SourceMapGenerator=Wt});var c3=y(Ci=>{Ci.GREATEST_LOWER_BOUND=1;Ci.LEAST_UPPER_BOUND=2;function Zh(t,e,r,n,i,s){var a=Math.floor((e-t)/2)+t,o=i(r,n[a],!0);return o===0?a:o>0?e-a>1?Zh(a,e,r,n,i,s):s==Ci.LEAST_UPPER_BOUND?e<n.length?e:-1:a:a-t>1?Zh(t,a,r,n,i,s):s==Ci.LEAST_UPPER_BOUND?a:t<0?-1:t}Ci.search=function(e,r,n,i){if(r.length===0)return-1;var s=Zh(-1,r.length,e,r,n,i||Ci.GREATEST_LOWER_BOUND);if(s<0)return-1;for(;s-1>=0&&n(r[s],r[s-1],!0)===0;)--s;return s}});var d3=y(p3=>{function lX(t){function e(i,s,a){var o=i[s];i[s]=i[a],i[a]=o}function r(i,s){return Math.round(i+Math.random()*(s-i))}function n(i,s,a,o){if(a<o){var u=r(a,o),c=a-1;e(i,u,o);for(var l=i[o],p=a;p<o;p++)s(i[p],l,!1)<=0&&(c+=1,e(i,c,p));e(i,c+1,p);var d=c+1;n(i,s,a,d-1),n(i,s,d+1,o)}}return n}function pX(t){let e=lX.toString();return new Function(`return ${e}`)()(t)}var l3=new WeakMap;p3.quickSort=function(t,e,r=0){let n=l3.get(e);n===void 0&&(n=pX(e),l3.set(e,n)),n(t,e,r,t.length-1)}});var g3=y(Sl=>{var W=Ws(),t0=c3(),Vs=Qh().ArraySet,dX=Vh(),ko=d3().quickSort;function Ae(t,e){var r=t;return typeof t=="string"&&(r=W.parseSourceMapInput(t)),r.sections!=null?new cr(r,e):new nt(r,e)}Ae.fromSourceMap=function(t,e){return nt.fromSourceMap(t,e)};Ae.prototype._version=3;Ae.prototype.__generatedMappings=null;Object.defineProperty(Ae.prototype,"_generatedMappings",{configurable:!0,enumerable:!0,get:function(){return this.__generatedMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappings}});Ae.prototype.__originalMappings=null;Object.defineProperty(Ae.prototype,"_originalMappings",{configurable:!0,enumerable:!0,get:function(){return this.__originalMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappings}});Ae.prototype._charIsMappingSeparator=function(e,r){var n=e.charAt(r);return n===";"||n===","};Ae.prototype._parseMappings=function(e,r){throw new Error("Subclasses must implement _parseMappings")};Ae.GENERATED_ORDER=1;Ae.ORIGINAL_ORDER=2;Ae.GREATEST_LOWER_BOUND=1;Ae.LEAST_UPPER_BOUND=2;Ae.prototype.eachMapping=function(e,r,n){var i=r||null,s=n||Ae.GENERATED_ORDER,a;switch(s){case Ae.GENERATED_ORDER:a=this._generatedMappings;break;case Ae.ORIGINAL_ORDER:a=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}for(var o=this.sourceRoot,u=e.bind(i),c=this._names,l=this._sources,p=this._sourceMapURL,d=0,m=a.length;d<m;d++){var f=a[d],g=f.source===null?null:l.at(f.source);g!==null&&(g=W.computeSourceURL(o,g,p)),u({source:g,generatedLine:f.generatedLine,generatedColumn:f.generatedColumn,originalLine:f.originalLine,originalColumn:f.originalColumn,name:f.name===null?null:c.at(f.name)})}};Ae.prototype.allGeneratedPositionsFor=function(e){var r=W.getArg(e,"line"),n={source:W.getArg(e,"source"),originalLine:r,originalColumn:W.getArg(e,"column",0)};if(n.source=this._findSourceIndex(n.source),n.source<0)return[];var i=[],s=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",W.compareByOriginalPositions,t0.LEAST_UPPER_BOUND);if(s>=0){var a=this._originalMappings[s];if(e.column===void 0)for(var o=a.originalLine;a&&a.originalLine===o;)i.push({line:W.getArg(a,"generatedLine",null),column:W.getArg(a,"generatedColumn",null),lastColumn:W.getArg(a,"lastGeneratedColumn",null)}),a=this._originalMappings[++s];else for(var u=a.originalColumn;a&&a.originalLine===r&&a.originalColumn==u;)i.push({line:W.getArg(a,"generatedLine",null),column:W.getArg(a,"generatedColumn",null),lastColumn:W.getArg(a,"lastGeneratedColumn",null)}),a=this._originalMappings[++s]}return i};Sl.SourceMapConsumer=Ae;function nt(t,e){var r=t;typeof t=="string"&&(r=W.parseSourceMapInput(t));var n=W.getArg(r,"version"),i=W.getArg(r,"sources"),s=W.getArg(r,"names",[]),a=W.getArg(r,"sourceRoot",null),o=W.getArg(r,"sourcesContent",null),u=W.getArg(r,"mappings"),c=W.getArg(r,"file",null);if(n!=this._version)throw new Error("Unsupported version: "+n);a&&(a=W.normalize(a)),i=i.map(String).map(W.normalize).map(function(l){return a&&W.isAbsolute(a)&&W.isAbsolute(l)?W.relative(a,l):l}),this._names=Vs.fromArray(s.map(String),!0),this._sources=Vs.fromArray(i,!0),this._absoluteSources=this._sources.toArray().map(function(l){return W.computeSourceURL(a,l,e)}),this.sourceRoot=a,this.sourcesContent=o,this._mappings=u,this._sourceMapURL=e,this.file=c}nt.prototype=Object.create(Ae.prototype);nt.prototype.consumer=Ae;nt.prototype._findSourceIndex=function(t){var e=t;if(this.sourceRoot!=null&&(e=W.relative(this.sourceRoot,e)),this._sources.has(e))return this._sources.indexOf(e);var r;for(r=0;r<this._absoluteSources.length;++r)if(this._absoluteSources[r]==t)return r;return-1};nt.fromSourceMap=function(e,r){var n=Object.create(nt.prototype),i=n._names=Vs.fromArray(e._names.toArray(),!0),s=n._sources=Vs.fromArray(e._sources.toArray(),!0);n.sourceRoot=e._sourceRoot,n.sourcesContent=e._generateSourcesContent(n._sources.toArray(),n.sourceRoot),n.file=e._file,n._sourceMapURL=r,n._absoluteSources=n._sources.toArray().map(function(m){return W.computeSourceURL(n.sourceRoot,m,r)});for(var a=e._mappings.toArray().slice(),o=n.__generatedMappings=[],u=n.__originalMappings=[],c=0,l=a.length;c<l;c++){var p=a[c],d=new m3;d.generatedLine=p.generatedLine,d.generatedColumn=p.generatedColumn,p.source&&(d.source=s.indexOf(p.source),d.originalLine=p.originalLine,d.originalColumn=p.originalColumn,p.name&&(d.name=i.indexOf(p.name)),u.push(d)),o.push(d)}return ko(n.__originalMappings,W.compareByOriginalPositions),n};nt.prototype._version=3;Object.defineProperty(nt.prototype,"sources",{get:function(){return this._absoluteSources.slice()}});function m3(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}var e0=W.compareByGeneratedPositionsDeflatedNoLine;function f3(t,e){let r=t.length,n=t.length-e;if(!(n<=1))if(n==2){let i=t[e],s=t[e+1];e0(i,s)>0&&(t[e]=s,t[e+1]=i)}else if(n<20)for(let i=e;i<r;i++)for(let s=i;s>e;s--){let a=t[s-1],o=t[s];if(e0(a,o)<=0)break;t[s-1]=o,t[s]=a}else ko(t,e0,e)}nt.prototype._parseMappings=function(e,r){var n=1,i=0,s=0,a=0,o=0,u=0,c=e.length,l=0,p={},d={},m=[],f=[],g,h,T,R,S;let P=0;for(;l<c;)if(e.charAt(l)===";")n++,l++,i=0,f3(f,P),P=f.length;else if(e.charAt(l)===",")l++;else{for(g=new m3,g.generatedLine=n,R=l;R<c&&!this._charIsMappingSeparator(e,R);R++);for(h=e.slice(l,R),T=[];l<R;)dX.decode(e,l,d),S=d.value,l=d.rest,T.push(S);if(T.length===2)throw new Error("Found a source, but no line and column");if(T.length===3)throw new Error("Found a source and line, but no column");if(g.generatedColumn=i+T[0],i=g.generatedColumn,T.length>1&&(g.source=o+T[1],o+=T[1],g.originalLine=s+T[2],s=g.originalLine,g.originalLine+=1,g.originalColumn=a+T[3],a=g.originalColumn,T.length>4&&(g.name=u+T[4],u+=T[4])),f.push(g),typeof g.originalLine=="number"){let I=g.source;for(;m.length<=I;)m.push(null);m[I]===null&&(m[I]=[]),m[I].push(g)}}f3(f,P),this.__generatedMappings=f;for(var F=0;F<m.length;F++)m[F]!=null&&ko(m[F],W.compareByOriginalPositionsNoSource);this.__originalMappings=[].concat(...m)};nt.prototype._findMapping=function(e,r,n,i,s,a){if(e[n]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[n]);if(e[i]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[i]);return t0.search(e,r,s,a)};nt.prototype.computeColumnSpans=function(){for(var e=0;e<this._generatedMappings.length;++e){var r=this._generatedMappings[e];if(e+1<this._generatedMappings.length){var n=this._generatedMappings[e+1];if(r.generatedLine===n.generatedLine){r.lastGeneratedColumn=n.generatedColumn-1;continue}}r.lastGeneratedColumn=1/0}};nt.prototype.originalPositionFor=function(e){var r={generatedLine:W.getArg(e,"line"),generatedColumn:W.getArg(e,"column")},n=this._findMapping(r,this._generatedMappings,"generatedLine","generatedColumn",W.compareByGeneratedPositionsDeflated,W.getArg(e,"bias",Ae.GREATEST_LOWER_BOUND));if(n>=0){var i=this._generatedMappings[n];if(i.generatedLine===r.generatedLine){var s=W.getArg(i,"source",null);s!==null&&(s=this._sources.at(s),s=W.computeSourceURL(this.sourceRoot,s,this._sourceMapURL));var a=W.getArg(i,"name",null);return a!==null&&(a=this._names.at(a)),{source:s,line:W.getArg(i,"originalLine",null),column:W.getArg(i,"originalColumn",null),name:a}}}return{source:null,line:null,column:null,name:null}};nt.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return e==null}):!1};nt.prototype.sourceContentFor=function(e,r){if(!this.sourcesContent)return null;var n=this._findSourceIndex(e);if(n>=0)return this.sourcesContent[n];var i=e;this.sourceRoot!=null&&(i=W.relative(this.sourceRoot,i));var s;if(this.sourceRoot!=null&&(s=W.urlParse(this.sourceRoot))){var a=i.replace(/^file:\/\//,"");if(s.scheme=="file"&&this._sources.has(a))return this.sourcesContent[this._sources.indexOf(a)];if((!s.path||s.path=="/")&&this._sources.has("/"+i))return this.sourcesContent[this._sources.indexOf("/"+i)]}if(r)return null;throw new Error('"'+i+'" is not in the SourceMap.')};nt.prototype.generatedPositionFor=function(e){var r=W.getArg(e,"source");if(r=this._findSourceIndex(r),r<0)return{line:null,column:null,lastColumn:null};var n={source:r,originalLine:W.getArg(e,"line"),originalColumn:W.getArg(e,"column")},i=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",W.compareByOriginalPositions,W.getArg(e,"bias",Ae.GREATEST_LOWER_BOUND));if(i>=0){var s=this._originalMappings[i];if(s.source===n.source)return{line:W.getArg(s,"generatedLine",null),column:W.getArg(s,"generatedColumn",null),lastColumn:W.getArg(s,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}};Sl.BasicSourceMapConsumer=nt;function cr(t,e){var r=t;typeof t=="string"&&(r=W.parseSourceMapInput(t));var n=W.getArg(r,"version"),i=W.getArg(r,"sections");if(n!=this._version)throw new Error("Unsupported version: "+n);this._sources=new Vs,this._names=new Vs;var s={line:-1,column:0};this._sections=i.map(function(a){if(a.url)throw new Error("Support for url field in sections not implemented.");var o=W.getArg(a,"offset"),u=W.getArg(o,"line"),c=W.getArg(o,"column");if(u<s.line||u===s.line&&c<s.column)throw new Error("Section offsets must be ordered and non-overlapping.");return s=o,{generatedOffset:{generatedLine:u+1,generatedColumn:c+1},consumer:new Ae(W.getArg(a,"map"),e)}})}cr.prototype=Object.create(Ae.prototype);cr.prototype.constructor=Ae;cr.prototype._version=3;Object.defineProperty(cr.prototype,"sources",{get:function(){for(var t=[],e=0;e<this._sections.length;e++)for(var r=0;r<this._sections[e].consumer.sources.length;r++)t.push(this._sections[e].consumer.sources[r]);return t}});cr.prototype.originalPositionFor=function(e){var r={generatedLine:W.getArg(e,"line"),generatedColumn:W.getArg(e,"column")},n=t0.search(r,this._sections,function(s,a){var o=s.generatedLine-a.generatedOffset.generatedLine;return o||s.generatedColumn-a.generatedOffset.generatedColumn}),i=this._sections[n];return i?i.consumer.originalPositionFor({line:r.generatedLine-(i.generatedOffset.generatedLine-1),column:r.generatedColumn-(i.generatedOffset.generatedLine===r.generatedLine?i.generatedOffset.generatedColumn-1:0),bias:e.bias}):{source:null,line:null,column:null,name:null}};cr.prototype.hasContentsOfAllSources=function(){return this._sections.every(function(e){return e.consumer.hasContentsOfAllSources()})};cr.prototype.sourceContentFor=function(e,r){for(var n=0;n<this._sections.length;n++){var i=this._sections[n],s=i.consumer.sourceContentFor(e,!0);if(s||s==="")return s}if(r)return null;throw new Error('"'+e+'" is not in the SourceMap.')};cr.prototype.generatedPositionFor=function(e){for(var r=0;r<this._sections.length;r++){var n=this._sections[r];if(n.consumer._findSourceIndex(W.getArg(e,"source"))!==-1){var i=n.consumer.generatedPositionFor(e);if(i){var s={line:i.line+(n.generatedOffset.generatedLine-1),column:i.column+(n.generatedOffset.generatedLine===i.line?n.generatedOffset.generatedColumn-1:0)};return s}}}return{line:null,column:null}};cr.prototype._parseMappings=function(e,r){this.__generatedMappings=[],this.__originalMappings=[];for(var n=0;n<this._sections.length;n++)for(var i=this._sections[n],s=i.consumer._generatedMappings,a=0;a<s.length;a++){var o=s[a],u=i.consumer._sources.at(o.source);u!==null&&(u=W.computeSourceURL(i.consumer.sourceRoot,u,this._sourceMapURL)),this._sources.add(u),u=this._sources.indexOf(u);var c=null;o.name&&(c=i.consumer._names.at(o.name),this._names.add(c),c=this._names.indexOf(c));var l={source:u,generatedLine:o.generatedLine+(i.generatedOffset.generatedLine-1),generatedColumn:o.generatedColumn+(i.generatedOffset.generatedLine===o.generatedLine?i.generatedOffset.generatedColumn-1:0),originalLine:o.originalLine,originalColumn:o.originalColumn,name:c};this.__generatedMappings.push(l),typeof l.originalLine=="number"&&this.__originalMappings.push(l)}ko(this.__generatedMappings,W.compareByGeneratedPositionsDeflated),ko(this.__originalMappings,W.compareByOriginalPositions)};Sl.IndexedSourceMapConsumer=cr});var b3=y(h3=>{var fX=Yh().SourceMapGenerator,kl=Ws(),mX=/(\r?\n)/,gX=10,Js="$$$isSourceNode$$$";function Lt(t,e,r,n,i){this.children=[],this.sourceContents={},this.line=t??null,this.column=e??null,this.source=r??null,this.name=i??null,this[Js]=!0,n!=null&&this.add(n)}Lt.fromStringWithSourceMap=function(e,r,n){var i=new Lt,s=e.split(mX),a=0,o=function(){var d=f(),m=f()||"";return d+m;function f(){return a<s.length?s[a++]:void 0}},u=1,c=0,l=null;return r.eachMapping(function(d){if(l!==null)if(u<d.generatedLine)p(l,o()),u++,c=0;else{var m=s[a]||"",f=m.substr(0,d.generatedColumn-c);s[a]=m.substr(d.generatedColumn-c),c=d.generatedColumn,p(l,f),l=d;return}for(;u<d.generatedLine;)i.add(o()),u++;if(c<d.generatedColumn){var m=s[a]||"";i.add(m.substr(0,d.generatedColumn)),s[a]=m.substr(d.generatedColumn),c=d.generatedColumn}l=d},this),a<s.length&&(l&&p(l,o()),i.add(s.splice(a).join(""))),r.sources.forEach(function(d){var m=r.sourceContentFor(d);m!=null&&(n!=null&&(d=kl.join(n,d)),i.setSourceContent(d,m))}),i;function p(d,m){if(d===null||d.source===void 0)i.add(m);else{var f=n?kl.join(n,d.source):d.source;i.add(new Lt(d.originalLine,d.originalColumn,f,m,d.name))}}};Lt.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(r){this.add(r)},this);else if(e[Js]||typeof e=="string")e&&this.children.push(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this};Lt.prototype.prepend=function(e){if(Array.isArray(e))for(var r=e.length-1;r>=0;r--)this.prepend(e[r]);else if(e[Js]||typeof e=="string")this.children.unshift(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this};Lt.prototype.walk=function(e){for(var r,n=0,i=this.children.length;n<i;n++)r=this.children[n],r[Js]?r.walk(e):r!==""&&e(r,{source:this.source,line:this.line,column:this.column,name:this.name})};Lt.prototype.join=function(e){var r,n,i=this.children.length;if(i>0){for(r=[],n=0;n<i-1;n++)r.push(this.children[n]),r.push(e);r.push(this.children[n]),this.children=r}return this};Lt.prototype.replaceRight=function(e,r){var n=this.children[this.children.length-1];return n[Js]?n.replaceRight(e,r):typeof n=="string"?this.children[this.children.length-1]=n.replace(e,r):this.children.push("".replace(e,r)),this};Lt.prototype.setSourceContent=function(e,r){this.sourceContents[kl.toSetString(e)]=r};Lt.prototype.walkSourceContents=function(e){for(var r=0,n=this.children.length;r<n;r++)this.children[r][Js]&&this.children[r].walkSourceContents(e);for(var i=Object.keys(this.sourceContents),r=0,n=i.length;r<n;r++)e(kl.fromSetString(i[r]),this.sourceContents[i[r]])};Lt.prototype.toString=function(){var e="";return this.walk(function(r){e+=r}),e};Lt.prototype.toStringWithSourceMap=function(e){var r={code:"",line:1,column:0},n=new fX(e),i=!1,s=null,a=null,o=null,u=null;return this.walk(function(c,l){r.code+=c,l.source!==null&&l.line!==null&&l.column!==null?((s!==l.source||a!==l.line||o!==l.column||u!==l.name)&&n.addMapping({source:l.source,original:{line:l.line,column:l.column},generated:{line:r.line,column:r.column},name:l.name}),s=l.source,a=l.line,o=l.column,u=l.name,i=!0):i&&(n.addMapping({generated:{line:r.line,column:r.column}}),s=null,i=!1);for(var p=0,d=c.length;p<d;p++)c.charCodeAt(p)===gX?(r.line++,r.column=0,p+1===d?(s=null,i=!1):i&&n.addMapping({source:l.source,original:{line:l.line,column:l.column},generated:{line:r.line,column:r.column},name:l.name})):r.column++}),this.walkSourceContents(function(c,l){n.setSourceContent(c,l)}),{code:r.code,map:n}};h3.SourceNode=Lt});var Al=y(Rl=>{Rl.SourceMapGenerator=Yh().SourceMapGenerator;Rl.SourceMapConsumer=g3().SourceMapConsumer;Rl.SourceNode=b3().SourceNode});var n0=y((nae,w3)=>{"use strict";var{existsSync:hX,readFileSync:bX}=require("fs"),{dirname:r0,join:yX}=require("path"),{SourceMapConsumer:y3,SourceMapGenerator:v3}=Al();function vX(t){return Buffer?Buffer.from(t,"base64").toString():window.atob(t)}var Ro=class{constructor(e,r){if(r.map===!1)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");let n=r.map?r.map.prev:void 0,i=this.loadMap(r.from,n);!this.mapFile&&r.from&&(this.mapFile=r.from),this.mapFile&&(this.root=r0(this.mapFile)),i&&(this.text=i)}consumer(){return this.consumerCache||(this.consumerCache=new y3(this.text)),this.consumerCache}decodeInline(e){let r=/^data:application\/json;charset=utf-?8;base64,/,n=/^data:application\/json;base64,/,i=/^data:application\/json;charset=utf-?8,/,s=/^data:application\/json,/,a=e.match(i)||e.match(s);if(a)return decodeURIComponent(e.substr(a[0].length));let o=e.match(r)||e.match(n);if(o)return vX(e.substr(o[0].length));let u=e.slice(22);throw u=u.slice(0,u.indexOf(",")),new Error("Unsupported source map encoding "+u)}getAnnotationURL(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(e){return typeof e!="object"?!1:typeof e.mappings=="string"||typeof e._mappings=="string"||Array.isArray(e.sections)}loadAnnotation(e){let r=e.match(/\/\*\s*# sourceMappingURL=/g);if(!r)return;let n=e.lastIndexOf(r.pop()),i=e.indexOf("*/",n);n>-1&&i>-1&&(this.annotation=this.getAnnotationURL(e.substring(n,i)))}loadFile(e){if(this.root=r0(e),hX(e))return this.mapFile=e,bX(e,"utf-8").toString().trim()}loadMap(e,r){if(r===!1)return!1;if(r){if(typeof r=="string")return r;if(typeof r=="function"){let n=r(e);if(n){let i=this.loadFile(n);if(!i)throw new Error("Unable to load previous source map: "+n.toString());return i}}else{if(r instanceof y3)return v3.fromSourceMap(r).toString();if(r instanceof v3)return r.toString();if(this.isMap(r))return JSON.stringify(r);throw new Error("Unsupported previous source map format: "+r.toString())}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let n=this.annotation;return e&&(n=yX(r0(e),n)),this.loadFile(n)}}}startWith(e,r){return e?e.substr(0,r.length)===r:!1}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};w3.exports=Ro;Ro.default=Ro});var Ao=y((iae,S3)=>{"use strict";var{nanoid:wX}=WA(),{isAbsolute:a0,resolve:o0}=require("path"),{SourceMapConsumer:xX,SourceMapGenerator:_X}=Al(),{fileURLToPath:x3,pathToFileURL:Pl}=require("url"),_3=vl(),EX=n0(),i0=Mh(),s0=Symbol("lineToIndexCache"),TX=!!(xX&&_X),E3=!!(o0&&a0);function T3(t){if(t[s0])return t[s0];let e=t.css.split(`
|
|
100
100
|
`),r=new Array(e.length),n=0;for(let i=0,s=e.length;i<s;i++)r[i]=n,n+=e[i].length+1;return t[s0]=r,r}var Xs=class{get from(){return this.file||this.id}constructor(e,r={}){if(e===null||typeof e>"u"||typeof e=="object"&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),this.css[0]==="\uFEFF"||this.css[0]==="\uFFFE"?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,this.document=this.css,r.document&&(this.document=r.document.toString()),r.from&&(!E3||/^\w+:\/\//.test(r.from)||a0(r.from)?this.file=r.from:this.file=o0(r.from)),E3&&TX){let n=new EX(this.css,r);if(n.text){this.map=n;let i=n.consumer().file;!this.file&&i&&(this.file=this.mapResolve(i))}}this.file||(this.id="<input css "+wX(6)+">"),this.map&&(this.map.file=this.from)}error(e,r,n,i={}){let s,a,o,u,c;if(r&&typeof r=="object"){let p=r,d=n;if(typeof p.offset=="number"){u=p.offset;let m=this.fromOffset(u);r=m.line,n=m.col}else r=p.line,n=p.column,u=this.fromLineAndColumn(r,n);if(typeof d.offset=="number"){o=d.offset;let m=this.fromOffset(o);a=m.line,s=m.col}else a=d.line,s=d.column,o=this.fromLineAndColumn(d.line,d.column)}else if(n)u=this.fromLineAndColumn(r,n);else{u=r;let p=this.fromOffset(u);r=p.line,n=p.col}let l=this.origin(r,n,a,s);return l?c=new _3(e,l.endLine===void 0?l.line:{column:l.column,line:l.line},l.endLine===void 0?l.column:{column:l.endColumn,line:l.endLine},l.source,l.file,i.plugin):c=new _3(e,a===void 0?r:{column:n,line:r},a===void 0?n:{column:s,line:a},this.css,this.file,i.plugin),c.input={column:n,endColumn:s,endLine:a,endOffset:o,line:r,offset:u,source:this.css},this.file&&(Pl&&(c.input.url=Pl(this.file).toString()),c.input.file=this.file),c}fromLineAndColumn(e,r){return T3(this)[e-1]+r-1}fromOffset(e){let r=T3(this),n=r[r.length-1],i=0;if(e>=n)i=r.length-1;else{let s=r.length-2,a;for(;i<s;)if(a=i+(s-i>>1),e<r[a])s=a-1;else if(e>=r[a+1])i=a+1;else{i=a;break}}return{col:e-r[i]+1,line:i+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:o0(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,r,n,i){if(!this.map)return!1;let s=this.map.consumer(),a=s.originalPositionFor({column:r,line:e});if(!a.source)return!1;let o;typeof n=="number"&&(o=s.originalPositionFor({column:i,line:n}));let u;a0(a.source)?u=Pl(a.source):u=new URL(a.source,this.map.consumer().sourceRoot||Pl(this.map.mapFile));let c={column:a.column,endColumn:o&&o.column,endLine:o&&o.line,line:a.line,url:u.toString()};if(u.protocol==="file:")if(x3)c.file=x3(u);else throw new Error("file: protocol is not available in this PostCSS build");let l=s.sourceContentFor(a.source);return l&&(c.source=l),c}toJSON(){let e={};for(let r of["hasBOM","css","file","id"])this[r]!=null&&(e[r]=this[r]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}};S3.exports=Xs;Xs.default=Xs;i0&&i0.registerInput&&i0.registerInput(Xs)});var Ks=y((sae,P3)=>{"use strict";var k3=kn(),R3,A3,Rn=class extends k3{constructor(e){super(e),this.type="root",this.nodes||(this.nodes=[])}normalize(e,r,n){let i=super.normalize(e);if(r){if(n==="prepend")this.nodes.length>1?r.raws.before=this.nodes[1].raws.before:delete r.raws.before;else if(this.first!==r)for(let s of i)s.raws.before=r.raws.before}return i}removeChild(e,r){let n=this.index(e);return!r&&n===0&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[n].raws.before),super.removeChild(e)}toResult(e={}){return new R3(new A3,this,e).stringify()}};Rn.registerLazyResult=t=>{R3=t};Rn.registerProcessor=t=>{A3=t};P3.exports=Rn;Rn.default=Rn;k3.registerRoot(Rn)});var u0=y((aae,C3)=>{"use strict";var Po={comma(t){return Po.split(t,[","],!0)},space(t){let e=[" ",`
|
|
101
101
|
`," "];return Po.split(t,e)},split(t,e,r){let n=[],i="",s=!1,a=0,o=!1,u="",c=!1;for(let l of t)c?c=!1:l==="\\"?c=!0:o?l===u&&(o=!1):l==='"'||l==="'"?(o=!0,u=l):l==="("?a+=1:l===")"?a>0&&(a-=1):a===0&&e.includes(l)&&(s=!0),s?(i!==""&&n.push(i.trim()),i="",s=!1):i+=l;return(r||i!=="")&&n.push(i.trim()),n}};C3.exports=Po;Po.default=Po});var Cl=y((oae,I3)=>{"use strict";var O3=kn(),SX=u0(),Qs=class extends O3{get selectors(){return SX.comma(this.selector)}set selectors(e){let r=this.selector?this.selector.match(/,\s*/):null,n=r?r[0]:","+this.raw("between","beforeOpen");this.selector=e.join(n)}constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}};I3.exports=Qs;Qs.default=Qs;O3.registerRule(Qs)});var D3=y((uae,L3)=>{"use strict";var kX=xl(),RX=xo(),AX=Eo(),PX=Ao(),CX=n0(),OX=Ks(),IX=Cl();function Co(t,e){if(Array.isArray(t))return t.map(i=>Co(i));let{inputs:r,...n}=t;if(r){e=[];for(let i of r){let s={...i,__proto__:PX.prototype};s.map&&(s.map={...s.map,__proto__:CX.prototype}),e.push(s)}}if(n.nodes&&(n.nodes=t.nodes.map(i=>Co(i,e))),n.source){let{inputId:i,...s}=n.source;n.source=s,i!=null&&(n.source.input=e[i])}if(n.type==="root")return new OX(n);if(n.type==="decl")return new AX(n);if(n.type==="rule")return new IX(n);if(n.type==="comment")return new RX(n);if(n.type==="atrule")return new kX(n);throw new Error("Unknown node type: "+t.type)}L3.exports=Co;Co.default=Co});var l0=y((cae,U3)=>{"use strict";var{dirname:Ol,relative:F3,resolve:M3,sep:j3}=require("path"),{SourceMapConsumer:q3,SourceMapGenerator:Il}=Al(),{pathToFileURL:N3}=require("url"),LX=Ao(),DX=!!(q3&&Il),NX=!!(Ol&&M3&&F3&&j3),c0=class{constructor(e,r,n,i){this.stringify=e,this.mapOpts=n.map||{},this.root=r,this.opts=n,this.css=i,this.originalCSS=i,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;this.isInline()?e="data:application/json;base64,"+this.toBase64(this.map.toString()):typeof this.mapOpts.annotation=="string"?e=this.mapOpts.annotation:typeof this.mapOpts.annotation=="function"?e=this.mapOpts.annotation(this.opts.to,this.root):e=this.outputFile()+".map";let r=`
|
|
102
102
|
`;this.css.includes(`\r
|
|
@@ -112,7 +112,7 @@ vulnerable to XSS attacks. Please remove it from \`allowedTags\`.
|
|
|
112
112
|
Or, to disable this warning, add the \`allowVulnerableTags\` option
|
|
113
113
|
and ensure you are accounting for this risk.
|
|
114
114
|
|
|
115
|
-
`)});let o=e.nonTextTags||["script","style","textarea","option"],u,c;e.allowedAttributes&&(u={},c={},Zs(e.allowedAttributes,function(_,D){u[D]=[];let E=[];_.forEach(function(U){typeof U=="string"&&U.indexOf("*")>=0?E.push(d4(U).replace(/\\\*/g,".*")):u[D].push(U)}),E.length&&(c[D]=new RegExp("^("+E.join("|")+")$"))}));let l={},p={},d={};Zs(e.allowedClasses,function(_,D){if(u&&(Yr(u,D)||(u[D]=[]),u[D].push("class")),l[D]=_,Array.isArray(_)){let E=[];l[D]=[],d[D]=[],_.forEach(function(U){typeof U=="string"&&U.indexOf("*")>=0?E.push(d4(U).replace(/\\\*/g,".*")):U instanceof RegExp?d[D].push(U):l[D].push(U)}),E.length&&(p[D]=new RegExp("^("+E.join("|")+")$"))}});let m={},f;Zs(e.transformTags,function(_,D){let E;typeof _=="function"?E=_:typeof _=="string"&&(E=No.simpleTransform(_)),D==="*"?f=E:m[D]=E});let g,h,T,R,S,P,F=!1;A();let I=new xK.Parser({onopentag:function(_,D){if(e.onOpenTag&&e.onOpenTag(_,D),e.enforceHtmlBoundary&&_==="html"&&A(),S){P++;return}let E=new s(_,D);h.push(E);let U=!1,Z=!!E.text,ge;if(Yr(m,_)&&(ge=m[_](_,D),E.attribs=D=ge.attribs,ge.text!==void 0&&(E.innerText=ge.text),_!==ge.tagName&&(E.name=_=ge.tagName,R[g]=ge.tagName)),f&&(ge=f(_,D),E.attribs=D=ge.attribs,_!==ge.tagName&&(E.name=_=ge.tagName,R[g]=ge.tagName)),(!a(_)||e.disallowedTagsMode==="recursiveEscape"&&!RK(T)||e.nestingLimit!=null&&g>=e.nestingLimit)&&(U=!0,T[g]=!0,(e.disallowedTagsMode==="discard"||e.disallowedTagsMode==="completelyDiscard")&&o.indexOf(_)!==-1&&(S=!0,P=1)),g++,U){if(e.disallowedTagsMode==="discard"||e.disallowedTagsMode==="completelyDiscard"){if(E.innerText&&!Z){let oe=j(E.innerText);e.textFilter?n+=e.textFilter(oe,_):n+=oe,F=!0}return}i=n,n=""}n+="<"+_,_==="script"&&(e.allowedScriptHostnames||e.allowedScriptDomains)&&(E.innerText=""),U&&(e.disallowedTagsMode==="escape"||e.disallowedTagsMode==="recursiveEscape")&&e.preserveEscapedAttributes?Zs(D,function(oe,pe){n+=" "+pe+'="'+j(oe||"",!0)+'"'}):(!u||Yr(u,_)||u["*"])&&Zs(D,function(oe,pe){if(!PK.test(pe)){delete E.attribs[pe];return}if(oe===""&&!e.allowedEmptyAttributes.includes(pe)&&(e.nonBooleanAttributes.includes(pe)||e.nonBooleanAttributes.includes("*"))){delete E.attribs[pe];return}let Ie=!1;if(!u||Yr(u,_)&&u[_].indexOf(pe)!==-1||u["*"]&&u["*"].indexOf(pe)!==-1||Yr(c,_)&&c[_].test(pe)||c["*"]&&c["*"].test(pe))Ie=!0;else if(u&&u[_]){for(let G of u[_])if(_K(G)&&G.name&&G.name===pe){Ie=!0;let le="";if(G.multiple===!0){let Ir=oe.split(" ");for(let mt of Ir)G.values.indexOf(mt)!==-1&&(le===""?le=mt:le+=" "+mt)}else G.values.indexOf(oe)>=0&&(le=oe);oe=le}}if(Ie){if(e.allowedSchemesAppliedToAttributes.indexOf(pe)!==-1&&v(_,oe)){delete E.attribs[pe];return}if(_==="script"&&pe==="src"){let G=!0;try{let le=L(oe);if(e.allowedScriptHostnames||e.allowedScriptDomains){let Ir=(e.allowedScriptHostnames||[]).find(function(it){return it===le.url.hostname}),mt=(e.allowedScriptDomains||[]).find(function(it){return le.url.hostname===it||le.url.hostname.endsWith(`.${it}`)});G=Ir||mt}}catch{G=!1}if(!G){delete E.attribs[pe];return}}if(_==="iframe"&&pe==="src"){let G=!0;try{let le=L(oe);if(le.isRelativeUrl)G=Yr(e,"allowIframeRelativeUrls")?e.allowIframeRelativeUrls:!e.allowedIframeHostnames&&!e.allowedIframeDomains;else if(e.allowedIframeHostnames||e.allowedIframeDomains){let Ir=(e.allowedIframeHostnames||[]).find(function(it){return it===le.url.hostname}),mt=(e.allowedIframeDomains||[]).find(function(it){return le.url.hostname===it||le.url.hostname.endsWith(`.${it}`)});G=Ir||mt}}catch{G=!1}if(!G){delete E.attribs[pe];return}}if(pe==="srcset")try{let G=EK(oe);if(G.forEach(function(le){v("srcset",le.url)&&(le.evil=!0)}),G=m4(G,function(le){return!le.evil}),G.length)oe=AK(m4(G,function(le){return!le.evil})),E.attribs[pe]=oe;else{delete E.attribs[pe];return}}catch{delete E.attribs[pe];return}if(pe==="class"){let G=l[_],le=l["*"],Ir=p[_],mt=d[_],it=d["*"],sp=p["*"],Zr=[Ir,sp].concat(mt,it).filter(function(aa){return aa});if(G&&le?oe=C(oe,f4(G,le),Zr):oe=C(oe,G||le,Zr),!oe.length){delete E.attribs[pe];return}}if(pe==="style"){if(e.parseStyleAttributes)try{let G=TK(_+" {"+oe+"}",{map:!1}),le=w(G,e.allowedStyles);if(oe=k(le),oe.length===0){delete E.attribs[pe];return}}catch{typeof window<"u"&&console.warn('Failed to parse "'+_+" {"+oe+`}", If you're running this in a browser, we recommend to disable style parsing: options.parseStyleAttributes: false, since this only works in a node environment due to a postcss dependency, More info: https://github.com/apostrophecms/sanitize-html/issues/547`),delete E.attribs[pe];return}else if(e.allowedStyles)throw new Error("allowedStyles option cannot be used together with parseStyleAttributes: false.")}n+=" "+pe,oe&&oe.length?n+='="'+j(oe,!0)+'"':e.allowedEmptyAttributes.includes(pe)&&(n+='=""')}else delete E.attribs[pe]}),e.selfClosing.indexOf(_)!==-1?n+=" />":(n+=">",E.innerText&&!Z&&!e.textFilter&&(n+=j(E.innerText),F=!0)),U&&(n=i+j(n),i=""),E.openingTagLength=n.length-E.tagPosition},ontext:function(_){if(S)return;let D=h[h.length-1],E;if(D&&(E=D.tag,_=D.innerText!==void 0?D.innerText:_),e.disallowedTagsMode==="completelyDiscard"&&!a(E))_="";else if((e.disallowedTagsMode==="discard"||e.disallowedTagsMode==="completelyDiscard")&&(E==="script"||E==="style"))n+=_;else if(!F){let U=j(_,!1);e.textFilter?n+=e.textFilter(U,E):n+=U}if(h.length){let U=h[h.length-1];U.text+=_}},onclosetag:function(_,D){if(e.onCloseTag&&e.onCloseTag(_,D),S)if(P--,!P)S=!1;else return;let E=h.pop();if(!E)return;if(E.tag!==_){h.push(E);return}S=e.enforceHtmlBoundary?_==="html":!1,g--;let U=T[g];if(U){if(delete T[g],e.disallowedTagsMode==="discard"||e.disallowedTagsMode==="completelyDiscard"){E.updateParentNodeText();return}i=n,n=""}if(R[g]&&(_=R[g],delete R[g]),e.exclusiveFilter){let Z=e.exclusiveFilter(E);if(Z==="excludeTag"){U&&(n=i,i=""),n=n.substring(0,E.tagPosition)+n.substring(E.tagPosition+E.openingTagLength);return}else if(Z){n=n.substring(0,E.tagPosition);return}}if(E.updateParentNodeMediaChildren(),E.updateParentNodeText(),e.selfClosing.indexOf(_)!==-1||D&&!a(_)&&["escape","recursiveEscape"].indexOf(e.disallowedTagsMode)>=0){U&&(n=i,i="");return}n+="</"+_+">",U&&(n=i+j(n),i=""),F=!1}},e.parser);if(I.write(t),I.end(),e.disallowedTagsMode==="escape"||e.disallowedTagsMode==="recursiveEscape"){let _=I.endIndex;if(_!=null&&_>=0&&_<t.length){let D=t.substring(_);n+=j(D)}else(_==null||_<0)&&t.length>0&&n===""&&(n=j(t))}return n;function A(){n="",g=0,h=[],T={},R={},S=!1,P=0}function j(_,D){return typeof _!="string"&&(_=_+""),e.parser.decodeEntities&&(_=_.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),D&&(_=_.replace(/"/g,"""))),_=_.replace(/&(?![a-zA-Z0-9#]{1,20};)/g,"&").replace(/</g,"<").replace(/>/g,">"),D&&(_=_.replace(/"/g,""")),_}function v(_,D){for(D=D.replace(/[\x00-\x20]+/g,"");;){let Z=D.indexOf("<!--");if(Z===-1)break;let ge=D.indexOf("-->",Z+4);if(ge===-1)break;D=D.substring(0,Z)+D.substring(ge+3)}let E=D.match(/^([a-zA-Z][a-zA-Z0-9.\-+]*):/);if(!E)return D.match(/^[/\\]{2}/)?!e.allowProtocolRelative:!1;let U=E[1].toLowerCase();return Yr(e.allowedSchemesByTag,_)?e.allowedSchemesByTag[_].indexOf(U)===-1:!e.allowedSchemes||e.allowedSchemes.indexOf(U)===-1}function L(_){if(_=_.replace(/^(\w+:)?\s*[\\/]\s*[\\/]/,"$1//"),_.startsWith("relative:"))throw new Error("relative: exploit attempt");let D="relative://relative-site";for(let Z=0;Z<100;Z++)D+=`/${Z}`;let E=new URL(_,D);return{isRelativeUrl:E&&E.hostname==="relative-site"&&E.protocol==="relative:",url:E}}function w(_,D){if(!D)return _;let E=_.nodes[0],U;return D[E.selector]&&D["*"]?U=f4(D[E.selector],D["*"]):U=D[E.selector]||D["*"],U&&(_.nodes[0].nodes=E.nodes.reduce(x(U),[])),_}function k(_){return _.nodes[0].nodes.reduce(function(D,E){return D.push(`${E.prop}:${E.value}${E.important?" !important":""}`),D},[]).join(";")}function x(_){return function(D,E){return Yr(_,E.prop)&&_[E.prop].some(function(Z){return Z.test(E.value)})&&D.push(E),D}}function C(_,D,E){return D?(_=_.split(/\s+/),_.filter(function(U){return D.indexOf(U)!==-1||E.some(function(Z){return Z.test(U)})}).join(" ")):_}}var CK={decodeEntities:!0};No.defaults={allowedTags:["address","article","aside","footer","header","h1","h2","h3","h4","h5","h6","hgroup","main","nav","section","blockquote","dd","div","dl","dt","figcaption","figure","hr","li","menu","ol","p","pre","ul","a","abbr","b","bdi","bdo","br","cite","code","data","dfn","em","i","kbd","mark","q","rb","rp","rt","rtc","ruby","s","samp","small","span","strong","sub","sup","time","u","var","wbr","caption","col","colgroup","table","tbody","td","tfoot","th","thead","tr"],nonBooleanAttributes:["abbr","accept","accept-charset","accesskey","action","allow","alt","as","autocapitalize","autocomplete","blocking","charset","cite","class","color","cols","colspan","content","contenteditable","coords","crossorigin","data","datetime","decoding","dir","dirname","download","draggable","enctype","enterkeyhint","fetchpriority","for","form","formaction","formenctype","formmethod","formtarget","headers","height","hidden","high","href","hreflang","http-equiv","id","imagesizes","imagesrcset","inputmode","integrity","is","itemid","itemprop","itemref","itemtype","kind","label","lang","list","loading","low","max","maxlength","media","method","min","minlength","name","nonce","optimum","pattern","ping","placeholder","popover","popovertarget","popovertargetaction","poster","preload","referrerpolicy","rel","rows","rowspan","sandbox","scope","shape","size","sizes","slot","span","spellcheck","src","srcdoc","srclang","srcset","start","step","style","tabindex","target","title","translate","type","usemap","value","width","wrap","onauxclick","onafterprint","onbeforematch","onbeforeprint","onbeforeunload","onbeforetoggle","onblur","oncancel","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextlost","oncontextmenu","oncontextrestored","oncopy","oncuechange","oncut","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","onhashchange","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onlanguagechange","onload","onloadeddata","onloadedmetadata","onloadstart","onmessage","onmessageerror","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onoffline","ononline","onpagehide","onpageshow","onpaste","onpause","onplay","onplaying","onpopstate","onprogress","onratechange","onreset","onresize","onrejectionhandled","onscroll","onscrollend","onsecuritypolicyviolation","onseeked","onseeking","onselect","onslotchange","onstalled","onstorage","onsubmit","onsuspend","ontimeupdate","ontoggle","onunhandledrejection","onunload","onvolumechange","onwaiting","onwheel"],disallowedTagsMode:"discard",allowedAttributes:{a:["href","name","target"],img:["src","srcset","alt","title","width","height","loading"]},allowedEmptyAttributes:["alt"],selfClosing:["img","br","hr","area","base","basefont","input","link","meta"],allowedSchemes:["http","https","ftp","mailto","tel"],allowedSchemesByTag:{},allowedSchemesAppliedToAttributes:["href","src","cite"],allowProtocolRelative:!0,enforceHtmlBoundary:!1,parseStyleAttributes:!0,preserveEscapedAttributes:!1};No.simpleTransform=function(t,e,r){return r=r===void 0?!0:r,e=e||{},function(n,i){let s;if(r)for(s in e)i[s]=e[s];else i=e;return{tagName:t,attribs:i}}}});var oZ={};J0(oZ,{log:()=>fC});module.exports=wC(oZ);var ip=qe(Sf(),1);var b={};J0(b,{BRAND:()=>fF,DIRTY:()=>Jn,EMPTY_PATH:()=>zN,INVALID:()=>Q,NEVER:()=>QF,OK:()=>ot,ParseStatus:()=>tt,Schema:()=>ie,ZodAny:()=>cn,ZodArray:()=>Hr,ZodBigInt:()=>Kn,ZodBoolean:()=>Qn,ZodBranded:()=>ja,ZodCatch:()=>ui,ZodDate:()=>Yn,ZodDefault:()=>oi,ZodDiscriminatedUnion:()=>ec,ZodEffects:()=>Bt,ZodEnum:()=>si,ZodError:()=>bt,ZodFirstPartyTypeKind:()=>Y,ZodFunction:()=>rc,ZodIntersection:()=>ri,ZodIssueCode:()=>q,ZodLazy:()=>ni,ZodLiteral:()=>ii,ZodMap:()=>hs,ZodNaN:()=>ys,ZodNativeEnum:()=>ai,ZodNever:()=>er,ZodNull:()=>ei,ZodNullable:()=>wr,ZodNumber:()=>Xn,ZodObject:()=>yt,ZodOptional:()=>Ut,ZodParsedType:()=>$,ZodPipeline:()=>qa,ZodPromise:()=>ln,ZodReadonly:()=>ci,ZodRecord:()=>tc,ZodSchema:()=>ie,ZodSet:()=>bs,ZodString:()=>un,ZodSymbol:()=>ms,ZodTransformer:()=>Bt,ZodTuple:()=>vr,ZodType:()=>ie,ZodUndefined:()=>Zn,ZodUnion:()=>ti,ZodUnknown:()=>Br,ZodVoid:()=>gs,addIssueToContext:()=>B,any:()=>_F,array:()=>kF,bigint:()=>bF,boolean:()=>j_,coerce:()=>KF,custom:()=>N_,date:()=>yF,datetimeRegex:()=>L_,defaultErrorMap:()=>Ur,discriminatedUnion:()=>CF,effect:()=>BF,enum:()=>qF,function:()=>FF,getErrorMap:()=>ps,getParsedType:()=>yr,instanceof:()=>gF,intersection:()=>OF,isAborted:()=>Yu,isAsync:()=>ds,isDirty:()=>Zu,isValid:()=>on,late:()=>mF,lazy:()=>MF,literal:()=>jF,makeIssue:()=>Ma,map:()=>DF,nan:()=>hF,nativeEnum:()=>UF,never:()=>TF,null:()=>xF,nullable:()=>$F,number:()=>M_,object:()=>RF,objectUtil:()=>kf,oboolean:()=>XF,onumber:()=>JF,optional:()=>HF,ostring:()=>VF,pipeline:()=>WF,preprocess:()=>zF,promise:()=>GF,quotelessJson:()=>BN,record:()=>LF,set:()=>NF,setErrorMap:()=>$N,strictObject:()=>AF,string:()=>F_,symbol:()=>vF,transformer:()=>BF,tuple:()=>IF,undefined:()=>wF,union:()=>PF,unknown:()=>EF,util:()=>ce,void:()=>SF});var ce;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let a of i)s[a]=a;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),a={};for(let o of s)a[o]=i[o];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},t.find=(i,s)=>{for(let a of i)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));var kf;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(kf||(kf={}));var $=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yr=t=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(t)?$.array:t===null?$.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?$.promise:typeof Map<"u"&&t instanceof Map?$.map:typeof Set<"u"&&t instanceof Set?$.set:typeof Date<"u"&&t instanceof Date?$.date:$.object;default:return $.unknown}};var q=ce.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),BN=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),bt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let o=n,u=0;for(;u<a.path.length;){let c=a.path[u];u===a.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(r(a))):o[c]=o[c]||{_errors:[]},o=o[c],u++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ce.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};bt.create=t=>new bt(t);var HN=(t,e)=>{let r;switch(t.code){case q.invalid_type:t.received===$.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case q.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case q.unrecognized_keys:r=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case q.invalid_union:r="Invalid input";break;case q.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case q.invalid_enum_value:r=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case q.invalid_arguments:r="Invalid function arguments";break;case q.invalid_return_type:r="Invalid function return type";break;case q.invalid_date:r="Invalid date";break;case q.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case q.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case q.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case q.custom:r="Invalid input";break;case q.invalid_intersection_types:r="Intersection results could not be merged";break;case q.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case q.not_finite:r="Number must be finite";break;default:r=e.defaultError,ce.assertNever(t)}return{message:r}},Ur=HN;var A_=Ur;function $N(t){A_=t}function ps(){return A_}var Ma=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)o=c(a,{data:e,defaultError:o}).message;return{...i,path:s,message:o}},zN=[];function B(t,e){let r=ps(),n=Ma({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ur?void 0:Ur].filter(i=>!!i)});t.common.issues.push(n)}var tt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return Q;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,a=await i.value;n.push({key:s,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return Q;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}},Q=Object.freeze({status:"aborted"}),Jn=t=>({status:"dirty",value:t}),ot=t=>({status:"valid",value:t}),Yu=t=>t.status==="aborted",Zu=t=>t.status==="dirty",on=t=>t.status==="valid",ds=t=>typeof Promise<"u"&&t instanceof Promise;var V;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(V||(V={}));var Gt=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},P_=(t,e)=>{if(on(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new bt(t.common.issues);return this._error=r,this._error}}};function re(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,o)=>{let{message:u}=t;return a.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:u??r??o.defaultError}},description:i}}var ie=class{get description(){return this._def.description}_getType(e){return yr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new tt,ctx:{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ds(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yr(e)},i=this._parseSync({data:e,path:n.path,parent:n});return P_(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return on(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>on(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yr(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(ds(i)?i:Promise.resolve(i));return P_(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let a=e(i),o=()=>s.addIssue({code:q.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Bt({schema:this,typeName:Y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Ut.create(this,this._def)}nullable(){return wr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Hr.create(this)}promise(){return ln.create(this,this._def)}or(e){return ti.create([this,e],this._def)}and(e){return ri.create(this,e,this._def)}transform(e){return new Bt({...re(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new oi({...re(this._def),innerType:this,defaultValue:r,typeName:Y.ZodDefault})}brand(){return new ja({typeName:Y.ZodBranded,type:this,...re(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new ui({...re(this._def),innerType:this,catchValue:r,typeName:Y.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return qa.create(this,e)}readonly(){return ci.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},WN=/^c[^\s-]{8,}$/i,VN=/^[0-9a-z]+$/,JN=/^[0-9A-HJKMNP-TV-Z]{26}$/i,XN=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,KN=/^[a-z0-9_-]{21}$/i,QN=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,YN=/^[-+]?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)?)??$/,ZN=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,eF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Rf,tF=/^(?:(?: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])$/,rF=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,nF=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,iF=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sF=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,aF=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,O_="((\\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])))",oF=new RegExp(`^${O_}$`);function I_(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function uF(t){return new RegExp(`^${I_(t)}$`)}function L_(t){let e=`${O_}T${I_(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function cF(t,e){return!!((e==="v4"||!e)&&tF.test(t)||(e==="v6"||!e)&&nF.test(t))}function lF(t,e){if(!QN.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function pF(t,e){return!!((e==="v4"||!e)&&rF.test(t)||(e==="v6"||!e)&&iF.test(t))}var un=class t extends ie{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.string){let s=this._getOrReturnCtx(e);return B(s,{code:q.invalid_type,expected:$.string,received:s.parsedType}),Q}let n=new tt,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),B(i,{code:q.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),B(i,{code:q.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,o=e.data.length<s.value;(a||o)&&(i=this._getOrReturnCtx(e,i),a?B(i,{code:q.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&B(i,{code:q.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")ZN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"email",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Rf||(Rf=new RegExp(eF,"u")),Rf.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"emoji",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")XN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"uuid",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")KN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"nanoid",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")WN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"cuid",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")VN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"cuid2",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")JN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"ulid",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),B(i,{validation:"url",code:q.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"regex",code:q.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?L_(s).test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?oF.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?uF(s).test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?YN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"duration",code:q.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?cF(e.data,s.version)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"ip",code:q.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?lF(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"jwt",code:q.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?pF(e.data,s.version)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"cidr",code:q.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?sF.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"base64",code:q.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?aF.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"base64url",code:q.invalid_string,message:s.message}),n.dirty()):ce.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:q.invalid_string,...V.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...V.errToObj(e)})}url(e){return this._addCheck({kind:"url",...V.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...V.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...V.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...V.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...V.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...V.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...V.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...V.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...V.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...V.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...V.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...V.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...V.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...V.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...V.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...V.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...V.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...V.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...V.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...V.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...V.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...V.errToObj(r)})}nonempty(e){return this.min(1,V.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};un.create=t=>new un({checks:[],typeName:Y.ZodString,coerce:t?.coerce??!1,...re(t)});function dF(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return s%a/10**i}var Xn=class t extends ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==$.number){let s=this._getOrReturnCtx(e);return B(s,{code:q.invalid_type,expected:$.number,received:s.parsedType}),Q}let n,i=new tt;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{code:q.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?dF(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{code:q.not_finite,message:s.message}),i.dirty()):ce.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:V.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:V.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:V.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ce.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Xn.create=t=>new Xn({checks:[],typeName:Y.ZodNumber,coerce:t?.coerce||!1,...re(t)});var Kn=class t extends ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==$.bigint)return this._getInvalidInput(e);let n,i=new tt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):ce.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return B(r,{code:q.invalid_type,expected:$.bigint,received:r.parsedType}),Q}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:V.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Kn.create=t=>new Kn({checks:[],typeName:Y.ZodBigInt,coerce:t?.coerce??!1,...re(t)});var Qn=class extends ie{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.boolean){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.boolean,received:n.parsedType}),Q}return ot(e.data)}};Qn.create=t=>new Qn({typeName:Y.ZodBoolean,coerce:t?.coerce||!1,...re(t)});var Yn=class t extends ie{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.date){let s=this._getOrReturnCtx(e);return B(s,{code:q.invalid_type,expected:$.date,received:s.parsedType}),Q}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return B(s,{code:q.invalid_date}),Q}let n=new tt,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),B(i,{code:q.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),B(i,{code:q.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ce.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:V.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:V.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Yn.create=t=>new Yn({checks:[],coerce:t?.coerce||!1,typeName:Y.ZodDate,...re(t)});var ms=class extends ie{_parse(e){if(this._getType(e)!==$.symbol){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.symbol,received:n.parsedType}),Q}return ot(e.data)}};ms.create=t=>new ms({typeName:Y.ZodSymbol,...re(t)});var Zn=class extends ie{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.undefined,received:n.parsedType}),Q}return ot(e.data)}};Zn.create=t=>new Zn({typeName:Y.ZodUndefined,...re(t)});var ei=class extends ie{_parse(e){if(this._getType(e)!==$.null){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.null,received:n.parsedType}),Q}return ot(e.data)}};ei.create=t=>new ei({typeName:Y.ZodNull,...re(t)});var cn=class extends ie{constructor(){super(...arguments),this._any=!0}_parse(e){return ot(e.data)}};cn.create=t=>new cn({typeName:Y.ZodAny,...re(t)});var Br=class extends ie{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ot(e.data)}};Br.create=t=>new Br({typeName:Y.ZodUnknown,...re(t)});var er=class extends ie{_parse(e){let r=this._getOrReturnCtx(e);return B(r,{code:q.invalid_type,expected:$.never,received:r.parsedType}),Q}};er.create=t=>new er({typeName:Y.ZodNever,...re(t)});var gs=class extends ie{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.void,received:n.parsedType}),Q}return ot(e.data)}};gs.create=t=>new gs({typeName:Y.ZodVoid,...re(t)});var Hr=class t extends ie{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==$.array)return B(r,{code:q.invalid_type,expected:$.array,received:r.parsedType}),Q;if(i.exactLength!==null){let a=r.data.length>i.exactLength.value,o=r.data.length<i.exactLength.value;(a||o)&&(B(r,{code:a?q.too_big:q.too_small,minimum:o?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(B(r,{code:q.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(B(r,{code:q.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>i.type._parseAsync(new Gt(r,a,r.path,o)))).then(a=>tt.mergeArray(n,a));let s=[...r.data].map((a,o)=>i.type._parseSync(new Gt(r,a,r.path,o)));return tt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:V.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:V.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:V.toString(r)}})}nonempty(e){return this.min(1,e)}};Hr.create=(t,e)=>new Hr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...re(e)});function fs(t){if(t instanceof yt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ut.create(fs(n))}return new yt({...t._def,shape:()=>e})}else return t instanceof Hr?new Hr({...t._def,type:fs(t.element)}):t instanceof Ut?Ut.create(fs(t.unwrap())):t instanceof wr?wr.create(fs(t.unwrap())):t instanceof vr?vr.create(t.items.map(e=>fs(e))):t}var yt=class t extends ie{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ce.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==$.object){let c=this._getOrReturnCtx(e);return B(c,{code:q.invalid_type,expected:$.object,received:c.parsedType}),Q}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof er&&this._def.unknownKeys==="strip"))for(let c in i.data)a.includes(c)||o.push(c);let u=[];for(let c of a){let l=s[c],p=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new Gt(i,p,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof er){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of o)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")o.length>0&&(B(i,{code:q.unrecognized_keys,keys:o}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of o){let p=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new Gt(i,p,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let p=await l.key,d=await l.value;c.push({key:p,value:d,alwaysSet:l.alwaysSet})}return c}).then(c=>tt.mergeObjectSync(n,c)):tt.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return V.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:V.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ce.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ce.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return fs(this)}partial(e){let r={};for(let n of ce.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ce.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ut;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return D_(ce.objectKeys(this.shape))}};yt.create=(t,e)=>new yt({shape:()=>t,unknownKeys:"strip",catchall:er.create(),typeName:Y.ZodObject,...re(e)});yt.strictCreate=(t,e)=>new yt({shape:()=>t,unknownKeys:"strict",catchall:er.create(),typeName:Y.ZodObject,...re(e)});yt.lazycreate=(t,e)=>new yt({shape:t,unknownKeys:"strip",catchall:er.create(),typeName:Y.ZodObject,...re(e)});var ti=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let o of s)if(o.result.status==="valid")return o.result;for(let o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(o=>new bt(o.ctx.common.issues));return B(r,{code:q.invalid_union,unionErrors:a}),Q}if(r.common.async)return Promise.all(n.map(async s=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let s,a=[];for(let u of n){let c={...r,common:{...r.common,issues:[]},parent:null},l=u._parseSync({data:r.data,path:r.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(u=>new bt(u));return B(r,{code:q.invalid_union,unionErrors:o}),Q}}get options(){return this._def.options}};ti.create=(t,e)=>new ti({options:t,typeName:Y.ZodUnion,...re(e)});var Gr=t=>t instanceof ni?Gr(t.schema):t instanceof Bt?Gr(t.innerType()):t instanceof ii?[t.value]:t instanceof si?t.options:t instanceof ai?ce.objectValues(t.enum):t instanceof oi?Gr(t._def.innerType):t instanceof Zn?[void 0]:t instanceof ei?[null]:t instanceof Ut?[void 0,...Gr(t.unwrap())]:t instanceof wr?[null,...Gr(t.unwrap())]:t instanceof ja||t instanceof ci?Gr(t.unwrap()):t instanceof ui?Gr(t._def.innerType):[],ec=class t extends ie{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.object)return B(r,{code:q.invalid_type,expected:$.object,received:r.parsedType}),Q;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(B(r,{code:q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let a=Gr(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of a){if(i.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);i.set(o,s)}}return new t({typeName:Y.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...re(n)})}};function Af(t,e){let r=yr(t),n=yr(e);if(t===e)return{valid:!0,data:t};if(r===$.object&&n===$.object){let i=ce.objectKeys(e),s=ce.objectKeys(t).filter(o=>i.indexOf(o)!==-1),a={...t,...e};for(let o of s){let u=Af(t[o],e[o]);if(!u.valid)return{valid:!1};a[o]=u.data}return{valid:!0,data:a}}else if(r===$.array&&n===$.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<t.length;s++){let a=t[s],o=e[s],u=Af(a,o);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===$.date&&n===$.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ri=class extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(s,a)=>{if(Yu(s)||Yu(a))return Q;let o=Af(s.value,a.value);return o.valid?((Zu(s)||Zu(a))&&r.dirty(),{status:r.value,value:o.data}):(B(n,{code:q.invalid_intersection_types}),Q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ri.create=(t,e,r)=>new ri({left:t,right:e,typeName:Y.ZodIntersection,...re(r)});var vr=class t extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.array)return B(n,{code:q.invalid_type,expected:$.array,received:n.parsedType}),Q;if(n.data.length<this._def.items.length)return B(n,{code:q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;!this._def.rest&&n.data.length>this._def.items.length&&(B(n,{code:q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((a,o)=>{let u=this._def.items[o]||this._def.rest;return u?u._parse(new Gt(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>tt.mergeArray(r,a)):tt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};vr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new vr({items:t,typeName:Y.ZodTuple,rest:null,...re(e)})};var tc=class t extends ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.object)return B(n,{code:q.invalid_type,expected:$.object,received:n.parsedType}),Q;let i=[],s=this._def.keyType,a=this._def.valueType;for(let o in n.data)i.push({key:s._parse(new Gt(n,o,n.path,o)),value:a._parse(new Gt(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?tt.mergeObjectAsync(r,i):tt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ie?new t({keyType:e,valueType:r,typeName:Y.ZodRecord,...re(n)}):new t({keyType:un.create(),valueType:e,typeName:Y.ZodRecord,...re(r)})}},hs=class extends ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.map)return B(n,{code:q.invalid_type,expected:$.map,received:n.parsedType}),Q;let i=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([o,u],c)=>({key:i._parse(new Gt(n,o,n.path,[c,"key"])),value:s._parse(new Gt(n,u,n.path,[c,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let u of a){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return Q;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(c.value,l.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let u of a){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return Q;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(c.value,l.value)}return{status:r.value,value:o}}}};hs.create=(t,e,r)=>new hs({valueType:e,keyType:t,typeName:Y.ZodMap,...re(r)});var bs=class t extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.set)return B(n,{code:q.invalid_type,expected:$.set,received:n.parsedType}),Q;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(B(n,{code:q.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(B(n,{code:q.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function a(u){let c=new Set;for(let l of u){if(l.status==="aborted")return Q;l.status==="dirty"&&r.dirty(),c.add(l.value)}return{status:r.value,value:c}}let o=[...n.data.values()].map((u,c)=>s._parse(new Gt(n,u,n.path,c)));return n.common.async?Promise.all(o).then(u=>a(u)):a(o)}min(e,r){return new t({...this._def,minSize:{value:e,message:V.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:V.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};bs.create=(t,e)=>new bs({valueType:t,minSize:null,maxSize:null,typeName:Y.ZodSet,...re(e)});var rc=class t extends ie{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.function)return B(r,{code:q.invalid_type,expected:$.function,received:r.parsedType}),Q;function n(o,u){return Ma({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ps(),Ur].filter(c=>!!c),issueData:{code:q.invalid_arguments,argumentsError:u}})}function i(o,u){return Ma({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ps(),Ur].filter(c=>!!c),issueData:{code:q.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof ln){let o=this;return ot(async function(...u){let c=new bt([]),l=await o._def.args.parseAsync(u,s).catch(m=>{throw c.addIssue(n(u,m)),c}),p=await Reflect.apply(a,this,l);return await o._def.returns._def.type.parseAsync(p,s).catch(m=>{throw c.addIssue(i(p,m)),c})})}else{let o=this;return ot(function(...u){let c=o._def.args.safeParse(u,s);if(!c.success)throw new bt([n(u,c.error)]);let l=Reflect.apply(a,this,c.data),p=o._def.returns.safeParse(l,s);if(!p.success)throw new bt([i(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:vr.create(e).rest(Br.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||vr.create([]).rest(Br.create()),returns:r||Br.create(),typeName:Y.ZodFunction,...re(n)})}},ni=class extends ie{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ni.create=(t,e)=>new ni({getter:t,typeName:Y.ZodLazy,...re(e)});var ii=class extends ie{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return B(r,{received:r.data,code:q.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:e.data}}get value(){return this._def.value}};ii.create=(t,e)=>new ii({value:t,typeName:Y.ZodLiteral,...re(e)});function D_(t,e){return new si({values:t,typeName:Y.ZodEnum,...re(e)})}var si=class t extends ie{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return B(r,{expected:ce.joinValues(n),received:r.parsedType,code:q.invalid_type}),Q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return B(r,{received:r.data,code:q.invalid_enum_value,options:n}),Q}return ot(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};si.create=D_;var ai=class extends ie{_parse(e){let r=ce.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==$.string&&n.parsedType!==$.number){let i=ce.objectValues(r);return B(n,{expected:ce.joinValues(i),received:n.parsedType,code:q.invalid_type}),Q}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ce.objectValues(r);return B(n,{received:n.data,code:q.invalid_enum_value,options:i}),Q}return ot(e.data)}get enum(){return this._def.values}};ai.create=(t,e)=>new ai({values:t,typeName:Y.ZodNativeEnum,...re(e)});var ln=class extends ie{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.promise&&r.common.async===!1)return B(r,{code:q.invalid_type,expected:$.promise,received:r.parsedType}),Q;let n=r.parsedType===$.promise?r.data:Promise.resolve(r.data);return ot(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ln.create=(t,e)=>new ln({type:t,typeName:Y.ZodPromise,...re(e)});var Bt=class extends ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:a=>{B(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let a=i.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return Q;let u=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return u.status==="aborted"?Q:u.status==="dirty"?Jn(u.value):r.value==="dirty"?Jn(u.value):u});{if(r.value==="aborted")return Q;let o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?Q:o.status==="dirty"?Jn(o.value):r.value==="dirty"?Jn(o.value):o}}if(i.type==="refinement"){let a=o=>{let u=i.refinement(o,s);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Q:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?Q:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(i.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!on(a))return Q;let o=i.transform(a.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>on(a)?Promise.resolve(i.transform(a.value,s)).then(o=>({status:r.value,value:o})):Q);ce.assertNever(i)}};Bt.create=(t,e,r)=>new Bt({schema:t,typeName:Y.ZodEffects,effect:e,...re(r)});Bt.createWithPreprocess=(t,e,r)=>new Bt({schema:e,effect:{type:"preprocess",transform:t},typeName:Y.ZodEffects,...re(r)});var Ut=class extends ie{_parse(e){return this._getType(e)===$.undefined?ot(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ut.create=(t,e)=>new Ut({innerType:t,typeName:Y.ZodOptional,...re(e)});var wr=class extends ie{_parse(e){return this._getType(e)===$.null?ot(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};wr.create=(t,e)=>new wr({innerType:t,typeName:Y.ZodNullable,...re(e)});var oi=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===$.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};oi.create=(t,e)=>new oi({innerType:t,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});var ui=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ds(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new bt(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ui.create=(t,e)=>new ui({innerType:t,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});var ys=class extends ie{_parse(e){if(this._getType(e)!==$.nan){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.nan,received:n.parsedType}),Q}return{status:"valid",value:e.data}}};ys.create=t=>new ys({typeName:Y.ZodNaN,...re(t)});var fF=Symbol("zod_brand"),ja=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},qa=class t extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Q:s.status==="dirty"?(r.dirty(),Jn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Q:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Y.ZodPipeline})}},ci=class extends ie{_parse(e){let r=this._def.innerType._parse(e),n=i=>(on(i)&&(i.value=Object.freeze(i.value)),i);return ds(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};ci.create=(t,e)=>new ci({innerType:t,typeName:Y.ZodReadonly,...re(e)});function C_(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function N_(t,e={},r){return t?cn.create().superRefine((n,i)=>{let s=t(n);if(s instanceof Promise)return s.then(a=>{if(!a){let o=C_(e,n),u=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:u})}});if(!s){let a=C_(e,n),o=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:o})}}):cn.create()}var mF={object:yt.lazycreate},Y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Y||(Y={}));var gF=(t,e={message:`Input not instance of ${t.name}`})=>N_(r=>r instanceof t,e),F_=un.create,M_=Xn.create,hF=ys.create,bF=Kn.create,j_=Qn.create,yF=Yn.create,vF=ms.create,wF=Zn.create,xF=ei.create,_F=cn.create,EF=Br.create,TF=er.create,SF=gs.create,kF=Hr.create,RF=yt.create,AF=yt.strictCreate,PF=ti.create,CF=ec.create,OF=ri.create,IF=vr.create,LF=tc.create,DF=hs.create,NF=bs.create,FF=rc.create,MF=ni.create,jF=ii.create,qF=si.create,UF=ai.create,GF=ln.create,BF=Bt.create,HF=Ut.create,$F=wr.create,zF=Bt.createWithPreprocess,WF=qa.create,VF=()=>F_().optional(),JF=()=>M_().optional(),XF=()=>j_().optional(),KF={string:(t=>un.create({...t,coerce:!0})),number:(t=>Xn.create({...t,coerce:!0})),boolean:(t=>Qn.create({...t,coerce:!0})),bigint:(t=>Kn.create({...t,coerce:!0})),date:(t=>Yn.create({...t,coerce:!0}))};var QF=Q;var YF=b.enum(["watching","processing","done","error","archived"]),ZF=b.enum(["accept","reject","flag"]),Cf=b.enum(["pending","queued","in_progress","resolved","failed","warning","rejected","flagged"]),q_=b.object({id:b.string(),author:b.string(),body:b.string(),bodyHtml:b.string(),replyKind:b.enum(["review_thread","review","general_comment"]),sourceId:b.string(),sourceNodeId:b.string().nullable(),sourceUrl:b.string().nullable(),threadId:b.string().nullable(),threadResolved:b.boolean().nullable(),auditToken:b.string(),file:b.string().nullable(),line:b.number().nullable(),type:b.enum(["review_comment","review","general_comment"]),createdAt:b.string(),decision:ZF.nullable(),decisionReason:b.string().nullable(),action:b.string().nullable(),status:Cf,statusReason:b.string().nullable()}),eM=b.enum(["needed","not_needed","failed"]),Of=b.object({headSha:b.string(),status:eM,summary:b.string(),assessedAt:b.string()}),nc=b.object({id:b.string(),number:b.number(),title:b.string(),repo:b.string(),branch:b.string(),author:b.string(),url:b.string(),status:YF,feedbackItems:b.array(q_),accepted:b.number(),rejected:b.number(),flagged:b.number(),testsPassed:b.boolean().nullable(),lintPassed:b.boolean().nullable(),lastChecked:b.string().nullable(),watchEnabled:b.boolean().default(!0),docsAssessment:Of.nullable().optional(),addedAt:b.string()}),sre=nc.omit({id:!0,addedAt:!0}),U_=b.object({url:b.string().url()}),G_=b.object({id:b.string(),prId:b.string(),runId:b.string().nullable(),timestamp:b.string(),level:b.enum(["info","warn","error"]),phase:b.string().nullable(),message:b.string(),metadata:b.record(b.string(),b.unknown()).nullable()}),tM=b.enum(["running","completed","failed"]),rM=b.object({id:b.string(),prId:b.string(),preferredAgent:b.enum(["codex","claude"]),resolvedAgent:b.enum(["codex","claude"]).nullable(),status:tM,phase:b.string(),prompt:b.string().nullable(),initialHeadSha:b.string().nullable(),metadata:b.record(b.string(),b.unknown()).nullable(),lastError:b.string().nullable(),createdAt:b.string(),updatedAt:b.string()}),are=b.object({drainMode:b.boolean(),drainRequestedAt:b.string().nullable(),drainReason:b.string().nullable()}),B_=b.enum(["sync_watched_repos","babysit_pr","process_release_run","answer_pr_question","generate_social_changelog","heal_deployment"]),If=b.enum(["queued","leased","completed","failed","canceled"]),Lf=b.object({id:b.string(),kind:B_,targetId:b.string(),dedupeKey:b.string(),status:If,priority:b.number().int(),availableAt:b.string(),leaseOwner:b.string().nullable(),leaseToken:b.string().nullable(),leaseExpiresAt:b.string().nullable(),heartbeatAt:b.string().nullable(),attemptCount:b.number().int().nonnegative(),lastError:b.string().nullable(),payload:b.record(b.string(),b.unknown()),createdAt:b.string(),updatedAt:b.string(),completedAt:b.string().nullable()}),nM=b.enum(["in_progress","queued","failed"]),Pf=b.object({id:b.string(),kind:B_,status:nM,label:b.string(),detail:b.string().nullable(),targetId:b.string(),targetUrl:b.string().nullable(),queuedAt:b.string(),availableAt:b.string(),startedAt:b.string().nullable(),updatedAt:b.string(),attemptCount:b.number().int().nonnegative(),lastError:b.string().nullable()}),iM=b.object({id:b.string(),severity:b.enum(["warning"]),title:b.string(),message:b.string(),fixSteps:b.array(b.string()),targetId:b.string(),targetUrl:b.string().nullable(),createdAt:b.string(),updatedAt:b.string()}),ore=b.object({failed:b.array(Pf),inProgress:b.array(Pf),queued:b.array(Pf),warnings:b.array(iM),generatedAt:b.string()}),sM=b.enum(["pending","answering","answered","error"]),Df=b.object({id:b.string(),prId:b.string(),question:b.string(),answer:b.string().nullable(),status:sM,error:b.string().nullable(),createdAt:b.string(),answeredAt:b.string().nullable()}),H_=b.object({question:b.string().min(1).max(2e3)}),aM=b.enum(["generating","done","error"]),oM=b.object({number:b.number(),title:b.string(),url:b.string(),author:b.string(),repo:b.string()}),Nf=b.object({id:b.string(),date:b.string(),triggerCount:b.number(),prSummaries:b.array(oM),content:b.string().nullable(),status:aM,error:b.string().nullable(),createdAt:b.string(),completedAt:b.string().nullable()}),uM=b.enum(["idle","triaging","awaiting_repair_slot","repairing","awaiting_ci","verifying","healed","cooldown","blocked","escalated","superseded"]),cM=b.enum(["healable_in_branch","blocked_external","flaky_or_ambiguous","unknown"]),lM=b.enum(["queued","running","awaiting_ci","verified","failed","canceled"]),$_=b.object({id:b.string(),prId:b.string(),sha:b.string(),provider:b.string(),context:b.string(),status:b.string(),conclusion:b.string().nullable(),description:b.string(),targetUrl:b.string().nullable(),observedAt:b.string()}),z_=b.object({id:b.string(),sessionId:b.string(),sha:b.string(),fingerprint:b.string(),category:b.string(),classification:cM,summary:b.string(),selectedEvidence:b.array(b.string()),createdAt:b.string()}),Ff=b.object({id:b.string(),prId:b.string(),repo:b.string(),prNumber:b.number(),initialHeadSha:b.string(),currentHeadSha:b.string(),state:uM,startedAt:b.string(),updatedAt:b.string(),endedAt:b.string().nullable(),blockedReason:b.string().nullable(),escalationReason:b.string().nullable(),latestFingerprint:b.string().nullable(),attemptCount:b.number(),lastImprovementScore:b.number().nullable()}),Mf=b.object({id:b.string(),sessionId:b.string(),attemptNumber:b.number(),inputSha:b.string(),outputSha:b.string().nullable(),status:lM,startedAt:b.string(),endedAt:b.string().nullable(),agent:b.enum(["codex","claude"]),promptDigest:b.string(),targetFingerprints:b.array(b.string()),summary:b.string().nullable(),improvementScore:b.number().nullable(),error:b.string().nullable()}),pM=b.enum(["detected","evaluating","skipped","proposed","publishing","published","error"]),dM=b.enum(["automatic","manual"]),fM=b.enum(["patch","minor","major"]),mM=b.object({number:b.number(),title:b.string(),url:b.string(),author:b.string(),mergedAt:b.string(),mergeSha:b.string()}),jf=b.object({id:b.string(),repo:b.string(),baseBranch:b.string(),triggerPrNumber:b.number(),triggerPrTitle:b.string(),triggerPrUrl:b.string(),triggerMergeSha:b.string(),triggerMergedAt:b.string(),source:dM.optional(),status:pM,decisionReason:b.string().nullable(),recommendedBump:fM.nullable(),proposedVersion:b.string().nullable(),releaseTitle:b.string().nullable(),releaseNotes:b.string().nullable(),includedPrs:b.array(mM),targetSha:b.string().nullable(),githubReleaseId:b.number().nullable(),githubReleaseUrl:b.string().nullable(),error:b.string().nullable(),createdAt:b.string(),updatedAt:b.string(),completedAt:b.string().nullable()}),gM=b.enum(["vercel","railway"]),hM=b.enum(["monitoring","failed","fixing","fix_submitted","escalated"]),qf=b.object({id:b.string(),repo:b.string(),platform:gM,triggerPrNumber:b.number(),triggerPrTitle:b.string(),triggerPrUrl:b.string(),mergeSha:b.string(),deploymentId:b.string().nullable(),deploymentLog:b.string().nullable(),fixBranch:b.string().nullable(),fixPrNumber:b.number().nullable(),fixPrUrl:b.string().nullable(),state:hM,error:b.string().nullable(),createdAt:b.string(),updatedAt:b.string(),completedAt:b.string().nullable()}),ic=b.object({githubTokens:b.array(b.string()),githubToken:b.string().optional(),codingAgent:b.enum(["codex","claude"]),fallbackToNextCodingAgent:b.boolean(),maxTurns:b.number(),batchWindowMs:b.number(),pollIntervalMs:b.number(),maxChangesPerRun:b.number(),autoResolveMergeConflicts:b.boolean(),autoCreateReleases:b.boolean(),autoUpdateDocs:b.boolean(),includeRepositoryLinksInGitHubComments:b.boolean(),postGitHubProgressReplies:b.boolean(),autoHealCI:b.boolean(),maxHealingAttemptsPerSession:b.number(),maxHealingAttemptsPerFingerprint:b.number(),maxConcurrentHealingRuns:b.number(),healingCooldownMs:b.number(),autoHealDeployments:b.boolean(),deploymentCheckDelayMs:b.number(),deploymentCheckTimeoutMs:b.number(),deploymentCheckPollIntervalMs:b.number(),watchedRepos:b.array(b.string()),trustedReviewers:b.array(b.string()),ignoredBots:b.array(b.string())}),W_=b.object({repo:b.string(),autoCreateReleases:b.boolean(),ownPrsOnly:b.boolean()}),ure=b.object({currentVersion:b.string(),latestVersion:b.string().nullable(),latestReleaseUrl:b.string(),updateAvailable:b.boolean()});var YP=require("node:events");var Ht=require("crypto");function Uf(t){return nc.parse({...t,id:(0,Ht.randomUUID)(),addedAt:new Date().toISOString()})}function Gf(t,e){return nc.parse({...t,...e,id:t.id,addedAt:t.addedAt})}function Bf(t,e,r,n){return G_.parse({id:(0,Ht.randomUUID)(),prId:t,runId:n?.runId??null,timestamp:new Date().toISOString(),level:e,phase:n?.phase??null,message:r,metadata:n?.metadata??null})}function Hf(t,e){return Df.parse({id:(0,Ht.randomUUID)(),prId:t,question:e,answer:null,status:"pending",error:null,createdAt:new Date().toISOString(),answeredAt:null})}function $f(t,e){return Df.parse({...t,...e,id:t.id,prId:t.prId,createdAt:t.createdAt})}function zf(t){let e=new Date().toISOString();return Lf.parse({...t,id:(0,Ht.randomUUID)(),status:"queued",priority:t.priority??100,leaseOwner:null,leaseToken:null,leaseExpiresAt:null,heartbeatAt:null,attemptCount:0,lastError:null,createdAt:e,updatedAt:e,completedAt:null})}function vs(t,e){return Lf.parse({...t,...e,id:t.id,createdAt:t.createdAt,updatedAt:new Date().toISOString()})}function Wf(t){return Nf.parse({...t,id:(0,Ht.randomUUID)(),createdAt:new Date().toISOString()})}function Vf(t,e){return Nf.parse({...t,...e,id:t.id,createdAt:t.createdAt})}function Jf(t){let e=new Date().toISOString();return jf.parse({...t,source:t.source??"automatic",id:(0,Ht.randomUUID)(),createdAt:e,updatedAt:e})}function Xf(t,e){return jf.parse({...t,...e,source:e.source??t.source??"automatic",id:t.id,createdAt:t.createdAt,updatedAt:new Date().toISOString()})}function ws(t){return $_.parse({...t,id:(0,Ht.randomUUID)()})}function Kf(t){return z_.parse({...t,id:(0,Ht.randomUUID)(),createdAt:new Date().toISOString()})}function Qf(t){let e=new Date().toISOString();return Ff.parse({...t,id:(0,Ht.randomUUID)(),startedAt:e,updatedAt:e})}function Yf(t,e){return Ff.parse({...t,...e,id:t.id,startedAt:t.startedAt,updatedAt:new Date().toISOString()})}function Zf(t){return Mf.parse({...t,id:(0,Ht.randomUUID)(),startedAt:new Date().toISOString()})}function em(t,e){return Mf.parse({...t,...e,id:t.id,sessionId:t.sessionId,attemptNumber:t.attemptNumber,startedAt:t.startedAt})}function tm(t){let e=new Date().toISOString();return qf.parse({...t,id:(0,Ht.randomUUID)(),createdAt:e,updatedAt:e})}function rm(t,e){return qf.parse({...t,...e,id:t.id,createdAt:t.createdAt,updatedAt:new Date().toISOString()})}function nm(t,e){let n=(e.githubTokens??(e.githubToken!==void 0?[e.githubToken]:t.githubTokens)).map(i=>i.trim()).filter(Boolean);return ic.parse({...t,...e,githubTokens:n,githubToken:void 0,watchedRepos:e.watchedRepos??t.watchedRepos,trustedReviewers:e.trustedReviewers??t.trustedReviewers,ignoredBots:e.ignoredBots??t.ignoredBots})}function im(t,e){return W_.parse({...t,...e,repo:t.repo})}var ut={githubTokens:[],codingAgent:"claude",fallbackToNextCodingAgent:!1,maxTurns:15,batchWindowMs:3e5,pollIntervalMs:12e4,maxChangesPerRun:20,autoResolveMergeConflicts:!0,autoCreateReleases:!0,autoUpdateDocs:!0,includeRepositoryLinksInGitHubComments:!0,postGitHubProgressReplies:!1,autoHealCI:!1,maxHealingAttemptsPerSession:3,maxHealingAttemptsPerFingerprint:2,maxConcurrentHealingRuns:1,healingCooldownMs:3e5,autoHealDeployments:!1,deploymentCheckDelayMs:6e4,deploymentCheckTimeoutMs:6e5,deploymentCheckPollIntervalMs:15e3,watchedRepos:[],trustedReviewers:[],ignoredBots:["dependabot[bot]","codecov[bot]","github-actions[bot]"]};var am=require("fs"),K_=require("node:sqlite");var V_=qe(require("os"),1),xs=qe(require("path"),1);function Ct(t){let e=t||process.env.OH_MY_PR_HOME||process.env.CODEFACTORY_HOME||xs.default.join(V_.default.homedir(),".oh-my-pr");return{rootDir:e,stateDbPath:xs.default.join(e,"state.sqlite"),logRootDir:xs.default.join(e,"log"),repoRootDir:xs.default.join(e,"repos"),worktreeRootDir:xs.default.join(e,"worktrees")}}var sc=require("fs"),sm=qe(require("path"),1);function bM(t){return t.replace(/[^a-zA-Z0-9_.-]+/g,"__")}function yM(t){let e=[t.timestamp,t.level.toUpperCase()];return t.phase&&e.push(`[${t.phase}]`),t.runId&&e.push(`run=${t.runId}`),e.push(t.message),t.metadata&&Object.keys(t.metadata).length>0&&e.push(JSON.stringify(t.metadata)),`${e.join(" ")}
|
|
115
|
+
`)});let o=e.nonTextTags||["script","style","textarea","option"],u,c;e.allowedAttributes&&(u={},c={},Zs(e.allowedAttributes,function(_,D){u[D]=[];let E=[];_.forEach(function(U){typeof U=="string"&&U.indexOf("*")>=0?E.push(d4(U).replace(/\\\*/g,".*")):u[D].push(U)}),E.length&&(c[D]=new RegExp("^("+E.join("|")+")$"))}));let l={},p={},d={};Zs(e.allowedClasses,function(_,D){if(u&&(Yr(u,D)||(u[D]=[]),u[D].push("class")),l[D]=_,Array.isArray(_)){let E=[];l[D]=[],d[D]=[],_.forEach(function(U){typeof U=="string"&&U.indexOf("*")>=0?E.push(d4(U).replace(/\\\*/g,".*")):U instanceof RegExp?d[D].push(U):l[D].push(U)}),E.length&&(p[D]=new RegExp("^("+E.join("|")+")$"))}});let m={},f;Zs(e.transformTags,function(_,D){let E;typeof _=="function"?E=_:typeof _=="string"&&(E=No.simpleTransform(_)),D==="*"?f=E:m[D]=E});let g,h,T,R,S,P,F=!1;A();let I=new xK.Parser({onopentag:function(_,D){if(e.onOpenTag&&e.onOpenTag(_,D),e.enforceHtmlBoundary&&_==="html"&&A(),S){P++;return}let E=new s(_,D);h.push(E);let U=!1,Z=!!E.text,ge;if(Yr(m,_)&&(ge=m[_](_,D),E.attribs=D=ge.attribs,ge.text!==void 0&&(E.innerText=ge.text),_!==ge.tagName&&(E.name=_=ge.tagName,R[g]=ge.tagName)),f&&(ge=f(_,D),E.attribs=D=ge.attribs,_!==ge.tagName&&(E.name=_=ge.tagName,R[g]=ge.tagName)),(!a(_)||e.disallowedTagsMode==="recursiveEscape"&&!RK(T)||e.nestingLimit!=null&&g>=e.nestingLimit)&&(U=!0,T[g]=!0,(e.disallowedTagsMode==="discard"||e.disallowedTagsMode==="completelyDiscard")&&o.indexOf(_)!==-1&&(S=!0,P=1)),g++,U){if(e.disallowedTagsMode==="discard"||e.disallowedTagsMode==="completelyDiscard"){if(E.innerText&&!Z){let oe=j(E.innerText);e.textFilter?n+=e.textFilter(oe,_):n+=oe,F=!0}return}i=n,n=""}n+="<"+_,_==="script"&&(e.allowedScriptHostnames||e.allowedScriptDomains)&&(E.innerText=""),U&&(e.disallowedTagsMode==="escape"||e.disallowedTagsMode==="recursiveEscape")&&e.preserveEscapedAttributes?Zs(D,function(oe,pe){n+=" "+pe+'="'+j(oe||"",!0)+'"'}):(!u||Yr(u,_)||u["*"])&&Zs(D,function(oe,pe){if(!PK.test(pe)){delete E.attribs[pe];return}if(oe===""&&!e.allowedEmptyAttributes.includes(pe)&&(e.nonBooleanAttributes.includes(pe)||e.nonBooleanAttributes.includes("*"))){delete E.attribs[pe];return}let Ie=!1;if(!u||Yr(u,_)&&u[_].indexOf(pe)!==-1||u["*"]&&u["*"].indexOf(pe)!==-1||Yr(c,_)&&c[_].test(pe)||c["*"]&&c["*"].test(pe))Ie=!0;else if(u&&u[_]){for(let G of u[_])if(_K(G)&&G.name&&G.name===pe){Ie=!0;let le="";if(G.multiple===!0){let Ir=oe.split(" ");for(let mt of Ir)G.values.indexOf(mt)!==-1&&(le===""?le=mt:le+=" "+mt)}else G.values.indexOf(oe)>=0&&(le=oe);oe=le}}if(Ie){if(e.allowedSchemesAppliedToAttributes.indexOf(pe)!==-1&&v(_,oe)){delete E.attribs[pe];return}if(_==="script"&&pe==="src"){let G=!0;try{let le=L(oe);if(e.allowedScriptHostnames||e.allowedScriptDomains){let Ir=(e.allowedScriptHostnames||[]).find(function(st){return st===le.url.hostname}),mt=(e.allowedScriptDomains||[]).find(function(st){return le.url.hostname===st||le.url.hostname.endsWith(`.${st}`)});G=Ir||mt}}catch{G=!1}if(!G){delete E.attribs[pe];return}}if(_==="iframe"&&pe==="src"){let G=!0;try{let le=L(oe);if(le.isRelativeUrl)G=Yr(e,"allowIframeRelativeUrls")?e.allowIframeRelativeUrls:!e.allowedIframeHostnames&&!e.allowedIframeDomains;else if(e.allowedIframeHostnames||e.allowedIframeDomains){let Ir=(e.allowedIframeHostnames||[]).find(function(st){return st===le.url.hostname}),mt=(e.allowedIframeDomains||[]).find(function(st){return le.url.hostname===st||le.url.hostname.endsWith(`.${st}`)});G=Ir||mt}}catch{G=!1}if(!G){delete E.attribs[pe];return}}if(pe==="srcset")try{let G=EK(oe);if(G.forEach(function(le){v("srcset",le.url)&&(le.evil=!0)}),G=m4(G,function(le){return!le.evil}),G.length)oe=AK(m4(G,function(le){return!le.evil})),E.attribs[pe]=oe;else{delete E.attribs[pe];return}}catch{delete E.attribs[pe];return}if(pe==="class"){let G=l[_],le=l["*"],Ir=p[_],mt=d[_],st=d["*"],sp=p["*"],Zr=[Ir,sp].concat(mt,st).filter(function(aa){return aa});if(G&&le?oe=C(oe,f4(G,le),Zr):oe=C(oe,G||le,Zr),!oe.length){delete E.attribs[pe];return}}if(pe==="style"){if(e.parseStyleAttributes)try{let G=TK(_+" {"+oe+"}",{map:!1}),le=w(G,e.allowedStyles);if(oe=k(le),oe.length===0){delete E.attribs[pe];return}}catch{typeof window<"u"&&console.warn('Failed to parse "'+_+" {"+oe+`}", If you're running this in a browser, we recommend to disable style parsing: options.parseStyleAttributes: false, since this only works in a node environment due to a postcss dependency, More info: https://github.com/apostrophecms/sanitize-html/issues/547`),delete E.attribs[pe];return}else if(e.allowedStyles)throw new Error("allowedStyles option cannot be used together with parseStyleAttributes: false.")}n+=" "+pe,oe&&oe.length?n+='="'+j(oe,!0)+'"':e.allowedEmptyAttributes.includes(pe)&&(n+='=""')}else delete E.attribs[pe]}),e.selfClosing.indexOf(_)!==-1?n+=" />":(n+=">",E.innerText&&!Z&&!e.textFilter&&(n+=j(E.innerText),F=!0)),U&&(n=i+j(n),i=""),E.openingTagLength=n.length-E.tagPosition},ontext:function(_){if(S)return;let D=h[h.length-1],E;if(D&&(E=D.tag,_=D.innerText!==void 0?D.innerText:_),e.disallowedTagsMode==="completelyDiscard"&&!a(E))_="";else if((e.disallowedTagsMode==="discard"||e.disallowedTagsMode==="completelyDiscard")&&(E==="script"||E==="style"))n+=_;else if(!F){let U=j(_,!1);e.textFilter?n+=e.textFilter(U,E):n+=U}if(h.length){let U=h[h.length-1];U.text+=_}},onclosetag:function(_,D){if(e.onCloseTag&&e.onCloseTag(_,D),S)if(P--,!P)S=!1;else return;let E=h.pop();if(!E)return;if(E.tag!==_){h.push(E);return}S=e.enforceHtmlBoundary?_==="html":!1,g--;let U=T[g];if(U){if(delete T[g],e.disallowedTagsMode==="discard"||e.disallowedTagsMode==="completelyDiscard"){E.updateParentNodeText();return}i=n,n=""}if(R[g]&&(_=R[g],delete R[g]),e.exclusiveFilter){let Z=e.exclusiveFilter(E);if(Z==="excludeTag"){U&&(n=i,i=""),n=n.substring(0,E.tagPosition)+n.substring(E.tagPosition+E.openingTagLength);return}else if(Z){n=n.substring(0,E.tagPosition);return}}if(E.updateParentNodeMediaChildren(),E.updateParentNodeText(),e.selfClosing.indexOf(_)!==-1||D&&!a(_)&&["escape","recursiveEscape"].indexOf(e.disallowedTagsMode)>=0){U&&(n=i,i="");return}n+="</"+_+">",U&&(n=i+j(n),i=""),F=!1}},e.parser);if(I.write(t),I.end(),e.disallowedTagsMode==="escape"||e.disallowedTagsMode==="recursiveEscape"){let _=I.endIndex;if(_!=null&&_>=0&&_<t.length){let D=t.substring(_);n+=j(D)}else(_==null||_<0)&&t.length>0&&n===""&&(n=j(t))}return n;function A(){n="",g=0,h=[],T={},R={},S=!1,P=0}function j(_,D){return typeof _!="string"&&(_=_+""),e.parser.decodeEntities&&(_=_.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),D&&(_=_.replace(/"/g,"""))),_=_.replace(/&(?![a-zA-Z0-9#]{1,20};)/g,"&").replace(/</g,"<").replace(/>/g,">"),D&&(_=_.replace(/"/g,""")),_}function v(_,D){for(D=D.replace(/[\x00-\x20]+/g,"");;){let Z=D.indexOf("<!--");if(Z===-1)break;let ge=D.indexOf("-->",Z+4);if(ge===-1)break;D=D.substring(0,Z)+D.substring(ge+3)}let E=D.match(/^([a-zA-Z][a-zA-Z0-9.\-+]*):/);if(!E)return D.match(/^[/\\]{2}/)?!e.allowProtocolRelative:!1;let U=E[1].toLowerCase();return Yr(e.allowedSchemesByTag,_)?e.allowedSchemesByTag[_].indexOf(U)===-1:!e.allowedSchemes||e.allowedSchemes.indexOf(U)===-1}function L(_){if(_=_.replace(/^(\w+:)?\s*[\\/]\s*[\\/]/,"$1//"),_.startsWith("relative:"))throw new Error("relative: exploit attempt");let D="relative://relative-site";for(let Z=0;Z<100;Z++)D+=`/${Z}`;let E=new URL(_,D);return{isRelativeUrl:E&&E.hostname==="relative-site"&&E.protocol==="relative:",url:E}}function w(_,D){if(!D)return _;let E=_.nodes[0],U;return D[E.selector]&&D["*"]?U=f4(D[E.selector],D["*"]):U=D[E.selector]||D["*"],U&&(_.nodes[0].nodes=E.nodes.reduce(x(U),[])),_}function k(_){return _.nodes[0].nodes.reduce(function(D,E){return D.push(`${E.prop}:${E.value}${E.important?" !important":""}`),D},[]).join(";")}function x(_){return function(D,E){return Yr(_,E.prop)&&_[E.prop].some(function(Z){return Z.test(E.value)})&&D.push(E),D}}function C(_,D,E){return D?(_=_.split(/\s+/),_.filter(function(U){return D.indexOf(U)!==-1||E.some(function(Z){return Z.test(U)})}).join(" ")):_}}var CK={decodeEntities:!0};No.defaults={allowedTags:["address","article","aside","footer","header","h1","h2","h3","h4","h5","h6","hgroup","main","nav","section","blockquote","dd","div","dl","dt","figcaption","figure","hr","li","menu","ol","p","pre","ul","a","abbr","b","bdi","bdo","br","cite","code","data","dfn","em","i","kbd","mark","q","rb","rp","rt","rtc","ruby","s","samp","small","span","strong","sub","sup","time","u","var","wbr","caption","col","colgroup","table","tbody","td","tfoot","th","thead","tr"],nonBooleanAttributes:["abbr","accept","accept-charset","accesskey","action","allow","alt","as","autocapitalize","autocomplete","blocking","charset","cite","class","color","cols","colspan","content","contenteditable","coords","crossorigin","data","datetime","decoding","dir","dirname","download","draggable","enctype","enterkeyhint","fetchpriority","for","form","formaction","formenctype","formmethod","formtarget","headers","height","hidden","high","href","hreflang","http-equiv","id","imagesizes","imagesrcset","inputmode","integrity","is","itemid","itemprop","itemref","itemtype","kind","label","lang","list","loading","low","max","maxlength","media","method","min","minlength","name","nonce","optimum","pattern","ping","placeholder","popover","popovertarget","popovertargetaction","poster","preload","referrerpolicy","rel","rows","rowspan","sandbox","scope","shape","size","sizes","slot","span","spellcheck","src","srcdoc","srclang","srcset","start","step","style","tabindex","target","title","translate","type","usemap","value","width","wrap","onauxclick","onafterprint","onbeforematch","onbeforeprint","onbeforeunload","onbeforetoggle","onblur","oncancel","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextlost","oncontextmenu","oncontextrestored","oncopy","oncuechange","oncut","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","onhashchange","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onlanguagechange","onload","onloadeddata","onloadedmetadata","onloadstart","onmessage","onmessageerror","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onoffline","ononline","onpagehide","onpageshow","onpaste","onpause","onplay","onplaying","onpopstate","onprogress","onratechange","onreset","onresize","onrejectionhandled","onscroll","onscrollend","onsecuritypolicyviolation","onseeked","onseeking","onselect","onslotchange","onstalled","onstorage","onsubmit","onsuspend","ontimeupdate","ontoggle","onunhandledrejection","onunload","onvolumechange","onwaiting","onwheel"],disallowedTagsMode:"discard",allowedAttributes:{a:["href","name","target"],img:["src","srcset","alt","title","width","height","loading"]},allowedEmptyAttributes:["alt"],selfClosing:["img","br","hr","area","base","basefont","input","link","meta"],allowedSchemes:["http","https","ftp","mailto","tel"],allowedSchemesByTag:{},allowedSchemesAppliedToAttributes:["href","src","cite"],allowProtocolRelative:!0,enforceHtmlBoundary:!1,parseStyleAttributes:!0,preserveEscapedAttributes:!1};No.simpleTransform=function(t,e,r){return r=r===void 0?!0:r,e=e||{},function(n,i){let s;if(r)for(s in e)i[s]=e[s];else i=e;return{tagName:t,attribs:i}}}});var oZ={};J0(oZ,{log:()=>fC});module.exports=wC(oZ);var ip=qe(Sf(),1);var b={};J0(b,{BRAND:()=>fF,DIRTY:()=>Jn,EMPTY_PATH:()=>zN,INVALID:()=>Q,NEVER:()=>QF,OK:()=>ut,ParseStatus:()=>tt,Schema:()=>ie,ZodAny:()=>cn,ZodArray:()=>Hr,ZodBigInt:()=>Kn,ZodBoolean:()=>Qn,ZodBranded:()=>ja,ZodCatch:()=>ui,ZodDate:()=>Yn,ZodDefault:()=>oi,ZodDiscriminatedUnion:()=>ec,ZodEffects:()=>Bt,ZodEnum:()=>si,ZodError:()=>bt,ZodFirstPartyTypeKind:()=>Y,ZodFunction:()=>rc,ZodIntersection:()=>ri,ZodIssueCode:()=>q,ZodLazy:()=>ni,ZodLiteral:()=>ii,ZodMap:()=>hs,ZodNaN:()=>ys,ZodNativeEnum:()=>ai,ZodNever:()=>er,ZodNull:()=>ei,ZodNullable:()=>wr,ZodNumber:()=>Xn,ZodObject:()=>yt,ZodOptional:()=>Ut,ZodParsedType:()=>$,ZodPipeline:()=>qa,ZodPromise:()=>ln,ZodReadonly:()=>ci,ZodRecord:()=>tc,ZodSchema:()=>ie,ZodSet:()=>bs,ZodString:()=>un,ZodSymbol:()=>ms,ZodTransformer:()=>Bt,ZodTuple:()=>vr,ZodType:()=>ie,ZodUndefined:()=>Zn,ZodUnion:()=>ti,ZodUnknown:()=>Br,ZodVoid:()=>gs,addIssueToContext:()=>B,any:()=>_F,array:()=>kF,bigint:()=>bF,boolean:()=>j_,coerce:()=>KF,custom:()=>N_,date:()=>yF,datetimeRegex:()=>L_,defaultErrorMap:()=>Ur,discriminatedUnion:()=>CF,effect:()=>BF,enum:()=>qF,function:()=>FF,getErrorMap:()=>ps,getParsedType:()=>yr,instanceof:()=>gF,intersection:()=>OF,isAborted:()=>Yu,isAsync:()=>ds,isDirty:()=>Zu,isValid:()=>on,late:()=>mF,lazy:()=>MF,literal:()=>jF,makeIssue:()=>Ma,map:()=>DF,nan:()=>hF,nativeEnum:()=>UF,never:()=>TF,null:()=>xF,nullable:()=>$F,number:()=>M_,object:()=>RF,objectUtil:()=>kf,oboolean:()=>XF,onumber:()=>JF,optional:()=>HF,ostring:()=>VF,pipeline:()=>WF,preprocess:()=>zF,promise:()=>GF,quotelessJson:()=>BN,record:()=>LF,set:()=>NF,setErrorMap:()=>$N,strictObject:()=>AF,string:()=>F_,symbol:()=>vF,transformer:()=>BF,tuple:()=>IF,undefined:()=>wF,union:()=>PF,unknown:()=>EF,util:()=>ce,void:()=>SF});var ce;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let a of i)s[a]=a;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),a={};for(let o of s)a[o]=i[o];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},t.find=(i,s)=>{for(let a of i)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));var kf;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(kf||(kf={}));var $=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yr=t=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(t)?$.array:t===null?$.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?$.promise:typeof Map<"u"&&t instanceof Map?$.map:typeof Set<"u"&&t instanceof Set?$.set:typeof Date<"u"&&t instanceof Date?$.date:$.object;default:return $.unknown}};var q=ce.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),BN=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),bt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let o=n,u=0;for(;u<a.path.length;){let c=a.path[u];u===a.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(r(a))):o[c]=o[c]||{_errors:[]},o=o[c],u++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ce.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};bt.create=t=>new bt(t);var HN=(t,e)=>{let r;switch(t.code){case q.invalid_type:t.received===$.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case q.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case q.unrecognized_keys:r=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case q.invalid_union:r="Invalid input";break;case q.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case q.invalid_enum_value:r=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case q.invalid_arguments:r="Invalid function arguments";break;case q.invalid_return_type:r="Invalid function return type";break;case q.invalid_date:r="Invalid date";break;case q.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case q.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case q.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case q.custom:r="Invalid input";break;case q.invalid_intersection_types:r="Intersection results could not be merged";break;case q.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case q.not_finite:r="Number must be finite";break;default:r=e.defaultError,ce.assertNever(t)}return{message:r}},Ur=HN;var A_=Ur;function $N(t){A_=t}function ps(){return A_}var Ma=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)o=c(a,{data:e,defaultError:o}).message;return{...i,path:s,message:o}},zN=[];function B(t,e){let r=ps(),n=Ma({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ur?void 0:Ur].filter(i=>!!i)});t.common.issues.push(n)}var tt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return Q;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,a=await i.value;n.push({key:s,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return Q;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}},Q=Object.freeze({status:"aborted"}),Jn=t=>({status:"dirty",value:t}),ut=t=>({status:"valid",value:t}),Yu=t=>t.status==="aborted",Zu=t=>t.status==="dirty",on=t=>t.status==="valid",ds=t=>typeof Promise<"u"&&t instanceof Promise;var V;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(V||(V={}));var Gt=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},P_=(t,e)=>{if(on(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new bt(t.common.issues);return this._error=r,this._error}}};function re(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,o)=>{let{message:u}=t;return a.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:u??r??o.defaultError}},description:i}}var ie=class{get description(){return this._def.description}_getType(e){return yr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new tt,ctx:{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ds(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yr(e)},i=this._parseSync({data:e,path:n.path,parent:n});return P_(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return on(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>on(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yr(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(ds(i)?i:Promise.resolve(i));return P_(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let a=e(i),o=()=>s.addIssue({code:q.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Bt({schema:this,typeName:Y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Ut.create(this,this._def)}nullable(){return wr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Hr.create(this)}promise(){return ln.create(this,this._def)}or(e){return ti.create([this,e],this._def)}and(e){return ri.create(this,e,this._def)}transform(e){return new Bt({...re(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new oi({...re(this._def),innerType:this,defaultValue:r,typeName:Y.ZodDefault})}brand(){return new ja({typeName:Y.ZodBranded,type:this,...re(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new ui({...re(this._def),innerType:this,catchValue:r,typeName:Y.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return qa.create(this,e)}readonly(){return ci.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},WN=/^c[^\s-]{8,}$/i,VN=/^[0-9a-z]+$/,JN=/^[0-9A-HJKMNP-TV-Z]{26}$/i,XN=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,KN=/^[a-z0-9_-]{21}$/i,QN=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,YN=/^[-+]?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)?)??$/,ZN=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,eF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Rf,tF=/^(?:(?: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])$/,rF=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,nF=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,iF=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sF=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,aF=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,O_="((\\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])))",oF=new RegExp(`^${O_}$`);function I_(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function uF(t){return new RegExp(`^${I_(t)}$`)}function L_(t){let e=`${O_}T${I_(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function cF(t,e){return!!((e==="v4"||!e)&&tF.test(t)||(e==="v6"||!e)&&nF.test(t))}function lF(t,e){if(!QN.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function pF(t,e){return!!((e==="v4"||!e)&&rF.test(t)||(e==="v6"||!e)&&iF.test(t))}var un=class t extends ie{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.string){let s=this._getOrReturnCtx(e);return B(s,{code:q.invalid_type,expected:$.string,received:s.parsedType}),Q}let n=new tt,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),B(i,{code:q.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),B(i,{code:q.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,o=e.data.length<s.value;(a||o)&&(i=this._getOrReturnCtx(e,i),a?B(i,{code:q.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&B(i,{code:q.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")ZN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"email",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Rf||(Rf=new RegExp(eF,"u")),Rf.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"emoji",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")XN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"uuid",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")KN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"nanoid",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")WN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"cuid",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")VN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"cuid2",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")JN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"ulid",code:q.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),B(i,{validation:"url",code:q.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"regex",code:q.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?L_(s).test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?oF.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?uF(s).test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{code:q.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?YN.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"duration",code:q.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?cF(e.data,s.version)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"ip",code:q.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?lF(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"jwt",code:q.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?pF(e.data,s.version)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"cidr",code:q.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?sF.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"base64",code:q.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?aF.test(e.data)||(i=this._getOrReturnCtx(e,i),B(i,{validation:"base64url",code:q.invalid_string,message:s.message}),n.dirty()):ce.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:q.invalid_string,...V.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...V.errToObj(e)})}url(e){return this._addCheck({kind:"url",...V.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...V.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...V.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...V.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...V.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...V.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...V.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...V.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...V.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...V.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...V.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...V.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...V.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...V.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...V.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...V.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...V.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...V.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...V.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...V.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...V.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...V.errToObj(r)})}nonempty(e){return this.min(1,V.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};un.create=t=>new un({checks:[],typeName:Y.ZodString,coerce:t?.coerce??!1,...re(t)});function dF(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return s%a/10**i}var Xn=class t extends ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==$.number){let s=this._getOrReturnCtx(e);return B(s,{code:q.invalid_type,expected:$.number,received:s.parsedType}),Q}let n,i=new tt;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{code:q.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?dF(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{code:q.not_finite,message:s.message}),i.dirty()):ce.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:V.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:V.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:V.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ce.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Xn.create=t=>new Xn({checks:[],typeName:Y.ZodNumber,coerce:t?.coerce||!1,...re(t)});var Kn=class t extends ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==$.bigint)return this._getInvalidInput(e);let n,i=new tt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),B(n,{code:q.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):ce.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return B(r,{code:q.invalid_type,expected:$.bigint,received:r.parsedType}),Q}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:V.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Kn.create=t=>new Kn({checks:[],typeName:Y.ZodBigInt,coerce:t?.coerce??!1,...re(t)});var Qn=class extends ie{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.boolean){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.boolean,received:n.parsedType}),Q}return ut(e.data)}};Qn.create=t=>new Qn({typeName:Y.ZodBoolean,coerce:t?.coerce||!1,...re(t)});var Yn=class t extends ie{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.date){let s=this._getOrReturnCtx(e);return B(s,{code:q.invalid_type,expected:$.date,received:s.parsedType}),Q}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return B(s,{code:q.invalid_date}),Q}let n=new tt,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),B(i,{code:q.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),B(i,{code:q.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ce.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:V.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:V.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Yn.create=t=>new Yn({checks:[],coerce:t?.coerce||!1,typeName:Y.ZodDate,...re(t)});var ms=class extends ie{_parse(e){if(this._getType(e)!==$.symbol){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.symbol,received:n.parsedType}),Q}return ut(e.data)}};ms.create=t=>new ms({typeName:Y.ZodSymbol,...re(t)});var Zn=class extends ie{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.undefined,received:n.parsedType}),Q}return ut(e.data)}};Zn.create=t=>new Zn({typeName:Y.ZodUndefined,...re(t)});var ei=class extends ie{_parse(e){if(this._getType(e)!==$.null){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.null,received:n.parsedType}),Q}return ut(e.data)}};ei.create=t=>new ei({typeName:Y.ZodNull,...re(t)});var cn=class extends ie{constructor(){super(...arguments),this._any=!0}_parse(e){return ut(e.data)}};cn.create=t=>new cn({typeName:Y.ZodAny,...re(t)});var Br=class extends ie{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ut(e.data)}};Br.create=t=>new Br({typeName:Y.ZodUnknown,...re(t)});var er=class extends ie{_parse(e){let r=this._getOrReturnCtx(e);return B(r,{code:q.invalid_type,expected:$.never,received:r.parsedType}),Q}};er.create=t=>new er({typeName:Y.ZodNever,...re(t)});var gs=class extends ie{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.void,received:n.parsedType}),Q}return ut(e.data)}};gs.create=t=>new gs({typeName:Y.ZodVoid,...re(t)});var Hr=class t extends ie{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==$.array)return B(r,{code:q.invalid_type,expected:$.array,received:r.parsedType}),Q;if(i.exactLength!==null){let a=r.data.length>i.exactLength.value,o=r.data.length<i.exactLength.value;(a||o)&&(B(r,{code:a?q.too_big:q.too_small,minimum:o?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(B(r,{code:q.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(B(r,{code:q.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>i.type._parseAsync(new Gt(r,a,r.path,o)))).then(a=>tt.mergeArray(n,a));let s=[...r.data].map((a,o)=>i.type._parseSync(new Gt(r,a,r.path,o)));return tt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:V.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:V.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:V.toString(r)}})}nonempty(e){return this.min(1,e)}};Hr.create=(t,e)=>new Hr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...re(e)});function fs(t){if(t instanceof yt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ut.create(fs(n))}return new yt({...t._def,shape:()=>e})}else return t instanceof Hr?new Hr({...t._def,type:fs(t.element)}):t instanceof Ut?Ut.create(fs(t.unwrap())):t instanceof wr?wr.create(fs(t.unwrap())):t instanceof vr?vr.create(t.items.map(e=>fs(e))):t}var yt=class t extends ie{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ce.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==$.object){let c=this._getOrReturnCtx(e);return B(c,{code:q.invalid_type,expected:$.object,received:c.parsedType}),Q}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof er&&this._def.unknownKeys==="strip"))for(let c in i.data)a.includes(c)||o.push(c);let u=[];for(let c of a){let l=s[c],p=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new Gt(i,p,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof er){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of o)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")o.length>0&&(B(i,{code:q.unrecognized_keys,keys:o}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of o){let p=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new Gt(i,p,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let p=await l.key,d=await l.value;c.push({key:p,value:d,alwaysSet:l.alwaysSet})}return c}).then(c=>tt.mergeObjectSync(n,c)):tt.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return V.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:V.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ce.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ce.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return fs(this)}partial(e){let r={};for(let n of ce.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ce.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ut;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return D_(ce.objectKeys(this.shape))}};yt.create=(t,e)=>new yt({shape:()=>t,unknownKeys:"strip",catchall:er.create(),typeName:Y.ZodObject,...re(e)});yt.strictCreate=(t,e)=>new yt({shape:()=>t,unknownKeys:"strict",catchall:er.create(),typeName:Y.ZodObject,...re(e)});yt.lazycreate=(t,e)=>new yt({shape:t,unknownKeys:"strip",catchall:er.create(),typeName:Y.ZodObject,...re(e)});var ti=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let o of s)if(o.result.status==="valid")return o.result;for(let o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(o=>new bt(o.ctx.common.issues));return B(r,{code:q.invalid_union,unionErrors:a}),Q}if(r.common.async)return Promise.all(n.map(async s=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let s,a=[];for(let u of n){let c={...r,common:{...r.common,issues:[]},parent:null},l=u._parseSync({data:r.data,path:r.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(u=>new bt(u));return B(r,{code:q.invalid_union,unionErrors:o}),Q}}get options(){return this._def.options}};ti.create=(t,e)=>new ti({options:t,typeName:Y.ZodUnion,...re(e)});var Gr=t=>t instanceof ni?Gr(t.schema):t instanceof Bt?Gr(t.innerType()):t instanceof ii?[t.value]:t instanceof si?t.options:t instanceof ai?ce.objectValues(t.enum):t instanceof oi?Gr(t._def.innerType):t instanceof Zn?[void 0]:t instanceof ei?[null]:t instanceof Ut?[void 0,...Gr(t.unwrap())]:t instanceof wr?[null,...Gr(t.unwrap())]:t instanceof ja||t instanceof ci?Gr(t.unwrap()):t instanceof ui?Gr(t._def.innerType):[],ec=class t extends ie{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.object)return B(r,{code:q.invalid_type,expected:$.object,received:r.parsedType}),Q;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(B(r,{code:q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let a=Gr(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of a){if(i.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);i.set(o,s)}}return new t({typeName:Y.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...re(n)})}};function Af(t,e){let r=yr(t),n=yr(e);if(t===e)return{valid:!0,data:t};if(r===$.object&&n===$.object){let i=ce.objectKeys(e),s=ce.objectKeys(t).filter(o=>i.indexOf(o)!==-1),a={...t,...e};for(let o of s){let u=Af(t[o],e[o]);if(!u.valid)return{valid:!1};a[o]=u.data}return{valid:!0,data:a}}else if(r===$.array&&n===$.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<t.length;s++){let a=t[s],o=e[s],u=Af(a,o);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===$.date&&n===$.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ri=class extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(s,a)=>{if(Yu(s)||Yu(a))return Q;let o=Af(s.value,a.value);return o.valid?((Zu(s)||Zu(a))&&r.dirty(),{status:r.value,value:o.data}):(B(n,{code:q.invalid_intersection_types}),Q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ri.create=(t,e,r)=>new ri({left:t,right:e,typeName:Y.ZodIntersection,...re(r)});var vr=class t extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.array)return B(n,{code:q.invalid_type,expected:$.array,received:n.parsedType}),Q;if(n.data.length<this._def.items.length)return B(n,{code:q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;!this._def.rest&&n.data.length>this._def.items.length&&(B(n,{code:q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((a,o)=>{let u=this._def.items[o]||this._def.rest;return u?u._parse(new Gt(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>tt.mergeArray(r,a)):tt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};vr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new vr({items:t,typeName:Y.ZodTuple,rest:null,...re(e)})};var tc=class t extends ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.object)return B(n,{code:q.invalid_type,expected:$.object,received:n.parsedType}),Q;let i=[],s=this._def.keyType,a=this._def.valueType;for(let o in n.data)i.push({key:s._parse(new Gt(n,o,n.path,o)),value:a._parse(new Gt(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?tt.mergeObjectAsync(r,i):tt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ie?new t({keyType:e,valueType:r,typeName:Y.ZodRecord,...re(n)}):new t({keyType:un.create(),valueType:e,typeName:Y.ZodRecord,...re(r)})}},hs=class extends ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.map)return B(n,{code:q.invalid_type,expected:$.map,received:n.parsedType}),Q;let i=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([o,u],c)=>({key:i._parse(new Gt(n,o,n.path,[c,"key"])),value:s._parse(new Gt(n,u,n.path,[c,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let u of a){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return Q;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(c.value,l.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let u of a){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return Q;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(c.value,l.value)}return{status:r.value,value:o}}}};hs.create=(t,e,r)=>new hs({valueType:e,keyType:t,typeName:Y.ZodMap,...re(r)});var bs=class t extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.set)return B(n,{code:q.invalid_type,expected:$.set,received:n.parsedType}),Q;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(B(n,{code:q.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(B(n,{code:q.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function a(u){let c=new Set;for(let l of u){if(l.status==="aborted")return Q;l.status==="dirty"&&r.dirty(),c.add(l.value)}return{status:r.value,value:c}}let o=[...n.data.values()].map((u,c)=>s._parse(new Gt(n,u,n.path,c)));return n.common.async?Promise.all(o).then(u=>a(u)):a(o)}min(e,r){return new t({...this._def,minSize:{value:e,message:V.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:V.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};bs.create=(t,e)=>new bs({valueType:t,minSize:null,maxSize:null,typeName:Y.ZodSet,...re(e)});var rc=class t extends ie{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.function)return B(r,{code:q.invalid_type,expected:$.function,received:r.parsedType}),Q;function n(o,u){return Ma({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ps(),Ur].filter(c=>!!c),issueData:{code:q.invalid_arguments,argumentsError:u}})}function i(o,u){return Ma({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ps(),Ur].filter(c=>!!c),issueData:{code:q.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof ln){let o=this;return ut(async function(...u){let c=new bt([]),l=await o._def.args.parseAsync(u,s).catch(m=>{throw c.addIssue(n(u,m)),c}),p=await Reflect.apply(a,this,l);return await o._def.returns._def.type.parseAsync(p,s).catch(m=>{throw c.addIssue(i(p,m)),c})})}else{let o=this;return ut(function(...u){let c=o._def.args.safeParse(u,s);if(!c.success)throw new bt([n(u,c.error)]);let l=Reflect.apply(a,this,c.data),p=o._def.returns.safeParse(l,s);if(!p.success)throw new bt([i(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:vr.create(e).rest(Br.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||vr.create([]).rest(Br.create()),returns:r||Br.create(),typeName:Y.ZodFunction,...re(n)})}},ni=class extends ie{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ni.create=(t,e)=>new ni({getter:t,typeName:Y.ZodLazy,...re(e)});var ii=class extends ie{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return B(r,{received:r.data,code:q.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:e.data}}get value(){return this._def.value}};ii.create=(t,e)=>new ii({value:t,typeName:Y.ZodLiteral,...re(e)});function D_(t,e){return new si({values:t,typeName:Y.ZodEnum,...re(e)})}var si=class t extends ie{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return B(r,{expected:ce.joinValues(n),received:r.parsedType,code:q.invalid_type}),Q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return B(r,{received:r.data,code:q.invalid_enum_value,options:n}),Q}return ut(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};si.create=D_;var ai=class extends ie{_parse(e){let r=ce.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==$.string&&n.parsedType!==$.number){let i=ce.objectValues(r);return B(n,{expected:ce.joinValues(i),received:n.parsedType,code:q.invalid_type}),Q}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ce.objectValues(r);return B(n,{received:n.data,code:q.invalid_enum_value,options:i}),Q}return ut(e.data)}get enum(){return this._def.values}};ai.create=(t,e)=>new ai({values:t,typeName:Y.ZodNativeEnum,...re(e)});var ln=class extends ie{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.promise&&r.common.async===!1)return B(r,{code:q.invalid_type,expected:$.promise,received:r.parsedType}),Q;let n=r.parsedType===$.promise?r.data:Promise.resolve(r.data);return ut(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ln.create=(t,e)=>new ln({type:t,typeName:Y.ZodPromise,...re(e)});var Bt=class extends ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:a=>{B(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let a=i.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return Q;let u=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return u.status==="aborted"?Q:u.status==="dirty"?Jn(u.value):r.value==="dirty"?Jn(u.value):u});{if(r.value==="aborted")return Q;let o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?Q:o.status==="dirty"?Jn(o.value):r.value==="dirty"?Jn(o.value):o}}if(i.type==="refinement"){let a=o=>{let u=i.refinement(o,s);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Q:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?Q:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(i.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!on(a))return Q;let o=i.transform(a.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>on(a)?Promise.resolve(i.transform(a.value,s)).then(o=>({status:r.value,value:o})):Q);ce.assertNever(i)}};Bt.create=(t,e,r)=>new Bt({schema:t,typeName:Y.ZodEffects,effect:e,...re(r)});Bt.createWithPreprocess=(t,e,r)=>new Bt({schema:e,effect:{type:"preprocess",transform:t},typeName:Y.ZodEffects,...re(r)});var Ut=class extends ie{_parse(e){return this._getType(e)===$.undefined?ut(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ut.create=(t,e)=>new Ut({innerType:t,typeName:Y.ZodOptional,...re(e)});var wr=class extends ie{_parse(e){return this._getType(e)===$.null?ut(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};wr.create=(t,e)=>new wr({innerType:t,typeName:Y.ZodNullable,...re(e)});var oi=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===$.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};oi.create=(t,e)=>new oi({innerType:t,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});var ui=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ds(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new bt(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ui.create=(t,e)=>new ui({innerType:t,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});var ys=class extends ie{_parse(e){if(this._getType(e)!==$.nan){let n=this._getOrReturnCtx(e);return B(n,{code:q.invalid_type,expected:$.nan,received:n.parsedType}),Q}return{status:"valid",value:e.data}}};ys.create=t=>new ys({typeName:Y.ZodNaN,...re(t)});var fF=Symbol("zod_brand"),ja=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},qa=class t extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Q:s.status==="dirty"?(r.dirty(),Jn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Q:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Y.ZodPipeline})}},ci=class extends ie{_parse(e){let r=this._def.innerType._parse(e),n=i=>(on(i)&&(i.value=Object.freeze(i.value)),i);return ds(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};ci.create=(t,e)=>new ci({innerType:t,typeName:Y.ZodReadonly,...re(e)});function C_(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function N_(t,e={},r){return t?cn.create().superRefine((n,i)=>{let s=t(n);if(s instanceof Promise)return s.then(a=>{if(!a){let o=C_(e,n),u=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:u})}});if(!s){let a=C_(e,n),o=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:o})}}):cn.create()}var mF={object:yt.lazycreate},Y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Y||(Y={}));var gF=(t,e={message:`Input not instance of ${t.name}`})=>N_(r=>r instanceof t,e),F_=un.create,M_=Xn.create,hF=ys.create,bF=Kn.create,j_=Qn.create,yF=Yn.create,vF=ms.create,wF=Zn.create,xF=ei.create,_F=cn.create,EF=Br.create,TF=er.create,SF=gs.create,kF=Hr.create,RF=yt.create,AF=yt.strictCreate,PF=ti.create,CF=ec.create,OF=ri.create,IF=vr.create,LF=tc.create,DF=hs.create,NF=bs.create,FF=rc.create,MF=ni.create,jF=ii.create,qF=si.create,UF=ai.create,GF=ln.create,BF=Bt.create,HF=Ut.create,$F=wr.create,zF=Bt.createWithPreprocess,WF=qa.create,VF=()=>F_().optional(),JF=()=>M_().optional(),XF=()=>j_().optional(),KF={string:(t=>un.create({...t,coerce:!0})),number:(t=>Xn.create({...t,coerce:!0})),boolean:(t=>Qn.create({...t,coerce:!0})),bigint:(t=>Kn.create({...t,coerce:!0})),date:(t=>Yn.create({...t,coerce:!0}))};var QF=Q;var YF=b.enum(["watching","processing","done","error","archived"]),ZF=b.enum(["accept","reject","flag"]),Cf=b.enum(["pending","queued","in_progress","resolved","failed","warning","rejected","flagged"]),q_=b.object({id:b.string(),author:b.string(),body:b.string(),bodyHtml:b.string(),replyKind:b.enum(["review_thread","review","general_comment"]),sourceId:b.string(),sourceNodeId:b.string().nullable(),sourceUrl:b.string().nullable(),threadId:b.string().nullable(),threadResolved:b.boolean().nullable(),auditToken:b.string(),file:b.string().nullable(),line:b.number().nullable(),type:b.enum(["review_comment","review","general_comment"]),createdAt:b.string(),decision:ZF.nullable(),decisionReason:b.string().nullable(),action:b.string().nullable(),status:Cf,statusReason:b.string().nullable()}),eM=b.enum(["needed","not_needed","failed"]),Of=b.object({headSha:b.string(),status:eM,summary:b.string(),assessedAt:b.string()}),nc=b.object({id:b.string(),number:b.number(),title:b.string(),repo:b.string(),branch:b.string(),author:b.string(),url:b.string(),status:YF,feedbackItems:b.array(q_),accepted:b.number(),rejected:b.number(),flagged:b.number(),testsPassed:b.boolean().nullable(),lintPassed:b.boolean().nullable(),lastChecked:b.string().nullable(),watchEnabled:b.boolean().default(!0),docsAssessment:Of.nullable().optional(),addedAt:b.string()}),sre=nc.omit({id:!0,addedAt:!0}),U_=b.object({url:b.string().url()}),G_=b.object({id:b.string(),prId:b.string(),runId:b.string().nullable(),timestamp:b.string(),level:b.enum(["info","warn","error"]),phase:b.string().nullable(),message:b.string(),metadata:b.record(b.string(),b.unknown()).nullable()}),tM=b.enum(["running","completed","failed"]),rM=b.object({id:b.string(),prId:b.string(),preferredAgent:b.enum(["codex","claude"]),resolvedAgent:b.enum(["codex","claude"]).nullable(),status:tM,phase:b.string(),prompt:b.string().nullable(),initialHeadSha:b.string().nullable(),metadata:b.record(b.string(),b.unknown()).nullable(),lastError:b.string().nullable(),createdAt:b.string(),updatedAt:b.string()}),are=b.object({drainMode:b.boolean(),drainRequestedAt:b.string().nullable(),drainReason:b.string().nullable()}),B_=b.enum(["sync_watched_repos","babysit_pr","process_release_run","answer_pr_question","generate_social_changelog","heal_deployment"]),If=b.enum(["queued","leased","completed","failed","canceled"]),Lf=b.object({id:b.string(),kind:B_,targetId:b.string(),dedupeKey:b.string(),status:If,priority:b.number().int(),availableAt:b.string(),leaseOwner:b.string().nullable(),leaseToken:b.string().nullable(),leaseExpiresAt:b.string().nullable(),heartbeatAt:b.string().nullable(),attemptCount:b.number().int().nonnegative(),lastError:b.string().nullable(),payload:b.record(b.string(),b.unknown()),createdAt:b.string(),updatedAt:b.string(),completedAt:b.string().nullable()}),nM=b.enum(["in_progress","queued","failed"]),Pf=b.object({id:b.string(),kind:B_,status:nM,label:b.string(),detail:b.string().nullable(),targetId:b.string(),targetUrl:b.string().nullable(),queuedAt:b.string(),availableAt:b.string(),startedAt:b.string().nullable(),updatedAt:b.string(),attemptCount:b.number().int().nonnegative(),lastError:b.string().nullable()}),iM=b.object({id:b.string(),severity:b.enum(["warning"]),title:b.string(),message:b.string(),fixSteps:b.array(b.string()),targetId:b.string(),targetUrl:b.string().nullable(),createdAt:b.string(),updatedAt:b.string()}),ore=b.object({failed:b.array(Pf),inProgress:b.array(Pf),queued:b.array(Pf),warnings:b.array(iM),generatedAt:b.string()}),sM=b.enum(["pending","answering","answered","error"]),Df=b.object({id:b.string(),prId:b.string(),question:b.string(),answer:b.string().nullable(),status:sM,error:b.string().nullable(),createdAt:b.string(),answeredAt:b.string().nullable()}),H_=b.object({question:b.string().min(1).max(2e3)}),aM=b.enum(["generating","done","error"]),oM=b.object({number:b.number(),title:b.string(),url:b.string(),author:b.string(),repo:b.string()}),Nf=b.object({id:b.string(),date:b.string(),triggerCount:b.number(),prSummaries:b.array(oM),content:b.string().nullable(),status:aM,error:b.string().nullable(),createdAt:b.string(),completedAt:b.string().nullable()}),uM=b.enum(["idle","triaging","awaiting_repair_slot","repairing","awaiting_ci","verifying","healed","cooldown","blocked","escalated","superseded"]),cM=b.enum(["healable_in_branch","blocked_external","flaky_or_ambiguous","unknown"]),lM=b.enum(["queued","running","awaiting_ci","verified","failed","canceled"]),$_=b.object({id:b.string(),prId:b.string(),sha:b.string(),provider:b.string(),context:b.string(),status:b.string(),conclusion:b.string().nullable(),description:b.string(),targetUrl:b.string().nullable(),observedAt:b.string()}),z_=b.object({id:b.string(),sessionId:b.string(),sha:b.string(),fingerprint:b.string(),category:b.string(),classification:cM,summary:b.string(),selectedEvidence:b.array(b.string()),createdAt:b.string()}),Ff=b.object({id:b.string(),prId:b.string(),repo:b.string(),prNumber:b.number(),initialHeadSha:b.string(),currentHeadSha:b.string(),state:uM,startedAt:b.string(),updatedAt:b.string(),endedAt:b.string().nullable(),blockedReason:b.string().nullable(),escalationReason:b.string().nullable(),latestFingerprint:b.string().nullable(),attemptCount:b.number(),lastImprovementScore:b.number().nullable()}),Mf=b.object({id:b.string(),sessionId:b.string(),attemptNumber:b.number(),inputSha:b.string(),outputSha:b.string().nullable(),status:lM,startedAt:b.string(),endedAt:b.string().nullable(),agent:b.enum(["codex","claude"]),promptDigest:b.string(),targetFingerprints:b.array(b.string()),summary:b.string().nullable(),improvementScore:b.number().nullable(),error:b.string().nullable()}),pM=b.enum(["detected","evaluating","skipped","proposed","publishing","published","error"]),dM=b.enum(["automatic","manual"]),fM=b.enum(["patch","minor","major"]),mM=b.object({number:b.number(),title:b.string(),url:b.string(),author:b.string(),mergedAt:b.string(),mergeSha:b.string()}),jf=b.object({id:b.string(),repo:b.string(),baseBranch:b.string(),triggerPrNumber:b.number(),triggerPrTitle:b.string(),triggerPrUrl:b.string(),triggerMergeSha:b.string(),triggerMergedAt:b.string(),source:dM.optional(),status:pM,decisionReason:b.string().nullable(),recommendedBump:fM.nullable(),proposedVersion:b.string().nullable(),releaseTitle:b.string().nullable(),releaseNotes:b.string().nullable(),includedPrs:b.array(mM),targetSha:b.string().nullable(),githubReleaseId:b.number().nullable(),githubReleaseUrl:b.string().nullable(),error:b.string().nullable(),createdAt:b.string(),updatedAt:b.string(),completedAt:b.string().nullable()}),gM=b.enum(["vercel","railway"]),hM=b.enum(["monitoring","failed","fixing","fix_submitted","escalated"]),qf=b.object({id:b.string(),repo:b.string(),platform:gM,triggerPrNumber:b.number(),triggerPrTitle:b.string(),triggerPrUrl:b.string(),mergeSha:b.string(),deploymentId:b.string().nullable(),deploymentLog:b.string().nullable(),fixBranch:b.string().nullable(),fixPrNumber:b.number().nullable(),fixPrUrl:b.string().nullable(),state:hM,error:b.string().nullable(),createdAt:b.string(),updatedAt:b.string(),completedAt:b.string().nullable()}),ic=b.object({githubTokens:b.array(b.string()),githubToken:b.string().optional(),codingAgent:b.enum(["codex","claude"]),fallbackToNextCodingAgent:b.boolean(),maxTurns:b.number(),batchWindowMs:b.number(),pollIntervalMs:b.number(),maxChangesPerRun:b.number(),autoResolveMergeConflicts:b.boolean(),autoCreateReleases:b.boolean(),autoUpdateDocs:b.boolean(),includeRepositoryLinksInGitHubComments:b.boolean(),postGitHubProgressReplies:b.boolean(),autoHealCI:b.boolean(),maxHealingAttemptsPerSession:b.number(),maxHealingAttemptsPerFingerprint:b.number(),maxConcurrentHealingRuns:b.number(),healingCooldownMs:b.number(),autoHealDeployments:b.boolean(),deploymentCheckDelayMs:b.number(),deploymentCheckTimeoutMs:b.number(),deploymentCheckPollIntervalMs:b.number(),watchedRepos:b.array(b.string()),trustedReviewers:b.array(b.string()),ignoredBots:b.array(b.string())}),W_=b.object({repo:b.string(),autoCreateReleases:b.boolean(),ownPrsOnly:b.boolean()}),ure=b.object({currentVersion:b.string(),latestVersion:b.string().nullable(),latestReleaseUrl:b.string(),updateAvailable:b.boolean()});var YP=require("node:events");var Ht=require("crypto");function Uf(t){return nc.parse({...t,id:(0,Ht.randomUUID)(),addedAt:new Date().toISOString()})}function Gf(t,e){return nc.parse({...t,...e,id:t.id,addedAt:t.addedAt})}function Bf(t,e,r,n){return G_.parse({id:(0,Ht.randomUUID)(),prId:t,runId:n?.runId??null,timestamp:new Date().toISOString(),level:e,phase:n?.phase??null,message:r,metadata:n?.metadata??null})}function Hf(t,e){return Df.parse({id:(0,Ht.randomUUID)(),prId:t,question:e,answer:null,status:"pending",error:null,createdAt:new Date().toISOString(),answeredAt:null})}function $f(t,e){return Df.parse({...t,...e,id:t.id,prId:t.prId,createdAt:t.createdAt})}function zf(t){let e=new Date().toISOString();return Lf.parse({...t,id:(0,Ht.randomUUID)(),status:"queued",priority:t.priority??100,leaseOwner:null,leaseToken:null,leaseExpiresAt:null,heartbeatAt:null,attemptCount:0,lastError:null,createdAt:e,updatedAt:e,completedAt:null})}function vs(t,e){return Lf.parse({...t,...e,id:t.id,createdAt:t.createdAt,updatedAt:new Date().toISOString()})}function Wf(t){return Nf.parse({...t,id:(0,Ht.randomUUID)(),createdAt:new Date().toISOString()})}function Vf(t,e){return Nf.parse({...t,...e,id:t.id,createdAt:t.createdAt})}function Jf(t){let e=new Date().toISOString();return jf.parse({...t,source:t.source??"automatic",id:(0,Ht.randomUUID)(),createdAt:e,updatedAt:e})}function Xf(t,e){return jf.parse({...t,...e,source:e.source??t.source??"automatic",id:t.id,createdAt:t.createdAt,updatedAt:new Date().toISOString()})}function ws(t){return $_.parse({...t,id:(0,Ht.randomUUID)()})}function Kf(t){return z_.parse({...t,id:(0,Ht.randomUUID)(),createdAt:new Date().toISOString()})}function Qf(t){let e=new Date().toISOString();return Ff.parse({...t,id:(0,Ht.randomUUID)(),startedAt:e,updatedAt:e})}function Yf(t,e){return Ff.parse({...t,...e,id:t.id,startedAt:t.startedAt,updatedAt:new Date().toISOString()})}function Zf(t){return Mf.parse({...t,id:(0,Ht.randomUUID)(),startedAt:new Date().toISOString()})}function em(t,e){return Mf.parse({...t,...e,id:t.id,sessionId:t.sessionId,attemptNumber:t.attemptNumber,startedAt:t.startedAt})}function tm(t){let e=new Date().toISOString();return qf.parse({...t,id:(0,Ht.randomUUID)(),createdAt:e,updatedAt:e})}function rm(t,e){return qf.parse({...t,...e,id:t.id,createdAt:t.createdAt,updatedAt:new Date().toISOString()})}function nm(t,e){let n=(e.githubTokens??(e.githubToken!==void 0?[e.githubToken]:t.githubTokens)).map(i=>i.trim()).filter(Boolean);return ic.parse({...t,...e,githubTokens:n,githubToken:void 0,watchedRepos:e.watchedRepos??t.watchedRepos,trustedReviewers:e.trustedReviewers??t.trustedReviewers,ignoredBots:e.ignoredBots??t.ignoredBots})}function im(t,e){return W_.parse({...t,...e,repo:t.repo})}var rt={githubTokens:[],codingAgent:"claude",fallbackToNextCodingAgent:!1,maxTurns:15,batchWindowMs:3e5,pollIntervalMs:12e4,maxChangesPerRun:20,autoResolveMergeConflicts:!0,autoCreateReleases:!1,autoUpdateDocs:!0,includeRepositoryLinksInGitHubComments:!0,postGitHubProgressReplies:!1,autoHealCI:!1,maxHealingAttemptsPerSession:3,maxHealingAttemptsPerFingerprint:2,maxConcurrentHealingRuns:1,healingCooldownMs:3e5,autoHealDeployments:!1,deploymentCheckDelayMs:6e4,deploymentCheckTimeoutMs:6e5,deploymentCheckPollIntervalMs:15e3,watchedRepos:[],trustedReviewers:[],ignoredBots:["dependabot[bot]","codecov[bot]","github-actions[bot]"]};var am=require("fs"),K_=require("node:sqlite");var V_=qe(require("os"),1),xs=qe(require("path"),1);function Ct(t){let e=t||process.env.OH_MY_PR_HOME||process.env.CODEFACTORY_HOME||xs.default.join(V_.default.homedir(),".oh-my-pr");return{rootDir:e,stateDbPath:xs.default.join(e,"state.sqlite"),logRootDir:xs.default.join(e,"log"),repoRootDir:xs.default.join(e,"repos"),worktreeRootDir:xs.default.join(e,"worktrees")}}var sc=require("fs"),sm=qe(require("path"),1);function bM(t){return t.replace(/[^a-zA-Z0-9_.-]+/g,"__")}function yM(t){let e=[t.timestamp,t.level.toUpperCase()];return t.phase&&e.push(`[${t.phase}]`),t.runId&&e.push(`run=${t.runId}`),e.push(t.message),t.metadata&&Object.keys(t.metadata).length>0&&e.push(JSON.stringify(t.metadata)),`${e.join(" ")}
|
|
116
116
|
`}function J_(t,e,r){let n=r.timestamp.slice(0,10),i=sm.default.join(t,n);(0,sc.mkdirSync)(i,{recursive:!0});let a=`${bM(e.repo)}__${e.number}.log`,o=sm.default.join(i,a);(0,sc.appendFileSync)(o,yM(r),"utf8")}var vM="cli-managed",wM=1e3,X_=1,xM=new Set([5,6]),_M={drainMode:!1,drainRequestedAt:null,drainReason:null};function EM(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean):[]}catch{return[]}}var ac=class{db;rootDir;logRootDir;stateDbPath;constructor(e){let r=Ct(e);(0,am.mkdirSync)(r.rootDir,{recursive:!0}),(0,am.mkdirSync)(r.logRootDir,{recursive:!0}),this.rootDir=r.rootDir,this.logRootDir=r.logRootDir,this.stateDbPath=r.stateDbPath,this.db=this.createDatabaseConnection(),this.bootstrap()}createDatabaseConnection(){let e=new K_.DatabaseSync(this.stateDbPath,{timeout:wM,enableForeignKeyConstraints:!0});return e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA foreign_keys = ON"),e}isRetryableLockError(e){if(!(e instanceof Error))return!1;let r=e;return r.code==="ERR_SQLITE_ERROR"&&(typeof r.errcode=="number"&&xM.has(r.errcode)||typeof r.errstr=="string"&&r.errstr.toLowerCase().includes("locked"))}reopenDatabase(){let e=this.db;this.db=this.createDatabaseConnection();try{e.close()}catch{}}throwPersistentLockError(e){let r=new Error(`SQLite database remained locked after recovery attempts at ${this.stateDbPath}. Stop the competing oh-my-pr process or use a different OH_MY_PR_HOME.`,{cause:e});throw r.name="SqliteDatabaseLockedError",r.code=e.code,r.errcode=e.errcode,r.errstr=e.errstr,r.statusCode=503,r}withLockRecovery(e){let r;for(let n=0;n<=X_;n+=1)try{return e()}catch(i){if(!this.isRetryableLockError(i))throw i;if(r=i,this.db.isTransaction||n===X_)break;this.reopenDatabase()}this.throwPersistentLockError(r??new Error("SQLite database lock recovery failed."))}exec(e){this.withLockRecovery(()=>{this.db.exec(e)})}get(e,...r){return this.withLockRecovery(()=>this.db.prepare(e).get(...r))}all(e,...r){return this.withLockRecovery(()=>this.db.prepare(e).all(...r))}run(e,...r){return this.withLockRecovery(()=>this.db.prepare(e).run(...r))}withWriteTransaction(e){if(this.db.isTransaction)return e();this.exec("BEGIN IMMEDIATE");try{let r=e();return this.exec("COMMIT"),r}catch(r){if(this.db.isTransaction)try{this.db.exec("ROLLBACK")}catch{}throw r}}bootstrap(){this.exec(`
|
|
117
117
|
CREATE TABLE IF NOT EXISTS config (
|
|
118
118
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
@@ -126,7 +126,7 @@ and ensure you are accounting for this risk.
|
|
|
126
126
|
poll_interval_ms INTEGER NOT NULL,
|
|
127
127
|
max_changes_per_run INTEGER NOT NULL,
|
|
128
128
|
auto_resolve_merge_conflicts INTEGER NOT NULL DEFAULT 1,
|
|
129
|
-
auto_create_releases INTEGER NOT NULL DEFAULT
|
|
129
|
+
auto_create_releases INTEGER NOT NULL DEFAULT 0,
|
|
130
130
|
auto_update_docs INTEGER NOT NULL DEFAULT 1,
|
|
131
131
|
include_repository_links_in_github_comments INTEGER NOT NULL DEFAULT 1,
|
|
132
132
|
post_github_progress_replies INTEGER NOT NULL DEFAULT 0,
|
|
@@ -141,7 +141,7 @@ and ensure you are accounting for this risk.
|
|
|
141
141
|
|
|
142
142
|
CREATE TABLE IF NOT EXISTS watched_repos (
|
|
143
143
|
repo TEXT PRIMARY KEY,
|
|
144
|
-
auto_create_releases INTEGER NOT NULL DEFAULT
|
|
144
|
+
auto_create_releases INTEGER NOT NULL DEFAULT 0,
|
|
145
145
|
own_prs_only INTEGER NOT NULL DEFAULT 1
|
|
146
146
|
);
|
|
147
147
|
|
|
@@ -404,10 +404,10 @@ and ensure you are accounting for this risk.
|
|
|
404
404
|
CREATE INDEX IF NOT EXISTS idx_release_runs_created_at ON release_runs(created_at);
|
|
405
405
|
CREATE INDEX IF NOT EXISTS idx_release_runs_status_created_at ON release_runs(status, created_at);
|
|
406
406
|
CREATE INDEX IF NOT EXISTS idx_release_runs_repo_trigger_merge_sha ON release_runs(repo, trigger_merge_sha);
|
|
407
|
-
`),this.ensureColumn("feedback_items","reply_kind","TEXT NOT NULL DEFAULT 'general_comment'"),this.ensureColumn("feedback_items","source_id","TEXT NOT NULL DEFAULT ''"),this.ensureColumn("feedback_items","source_node_id","TEXT"),this.ensureColumn("feedback_items","source_url","TEXT"),this.ensureColumn("feedback_items","thread_id","TEXT"),this.ensureColumn("feedback_items","thread_resolved","INTEGER"),this.ensureColumn("feedback_items","audit_token","TEXT NOT NULL DEFAULT ''"),this.ensureColumn("feedback_items","status","TEXT NOT NULL DEFAULT 'pending'"),this.ensureColumn("feedback_items","status_reason","TEXT"),this.ensureColumn("config","github_tokens_json","TEXT NOT NULL DEFAULT '[]'"),this.ensureColumn("config","fallback_to_next_coding_agent","INTEGER NOT NULL DEFAULT 0"),this.ensureColumn("config","auto_resolve_merge_conflicts","INTEGER NOT NULL DEFAULT 1"),this.ensureColumn("config","auto_create_releases","INTEGER NOT NULL DEFAULT
|
|
407
|
+
`),this.ensureColumn("feedback_items","reply_kind","TEXT NOT NULL DEFAULT 'general_comment'"),this.ensureColumn("feedback_items","source_id","TEXT NOT NULL DEFAULT ''"),this.ensureColumn("feedback_items","source_node_id","TEXT"),this.ensureColumn("feedback_items","source_url","TEXT"),this.ensureColumn("feedback_items","thread_id","TEXT"),this.ensureColumn("feedback_items","thread_resolved","INTEGER"),this.ensureColumn("feedback_items","audit_token","TEXT NOT NULL DEFAULT ''"),this.ensureColumn("feedback_items","status","TEXT NOT NULL DEFAULT 'pending'"),this.ensureColumn("feedback_items","status_reason","TEXT"),this.ensureColumn("config","github_tokens_json","TEXT NOT NULL DEFAULT '[]'"),this.ensureColumn("config","fallback_to_next_coding_agent","INTEGER NOT NULL DEFAULT 0"),this.ensureColumn("config","auto_resolve_merge_conflicts","INTEGER NOT NULL DEFAULT 1"),this.ensureColumn("config","auto_create_releases","INTEGER NOT NULL DEFAULT 0"),this.ensureColumn("config","auto_update_docs","INTEGER NOT NULL DEFAULT 1"),this.ensureColumn("config","include_repository_links_in_github_comments","INTEGER NOT NULL DEFAULT 1"),this.ensureColumn("config","post_github_progress_replies","INTEGER NOT NULL DEFAULT 0"),this.ensureColumn("config","auto_heal_ci","INTEGER NOT NULL DEFAULT 0"),this.ensureColumn("config","max_healing_attempts_per_session","INTEGER NOT NULL DEFAULT 3"),this.ensureColumn("config","max_healing_attempts_per_fingerprint","INTEGER NOT NULL DEFAULT 2"),this.ensureColumn("config","max_concurrent_healing_runs","INTEGER NOT NULL DEFAULT 1"),this.ensureColumn("config","healing_cooldown_ms","INTEGER NOT NULL DEFAULT 300000"),this.ensureColumn("config","auto_heal_deployments","INTEGER NOT NULL DEFAULT 0"),this.ensureColumn("config","deployment_check_delay_ms","INTEGER NOT NULL DEFAULT 60000"),this.ensureColumn("config","deployment_check_timeout_ms","INTEGER NOT NULL DEFAULT 600000"),this.ensureColumn("config","deployment_check_poll_interval_ms","INTEGER NOT NULL DEFAULT 15000"),this.ensureColumn("watched_repos","auto_create_releases","INTEGER NOT NULL DEFAULT 0"),this.ensureColumn("watched_repos","own_prs_only","INTEGER NOT NULL DEFAULT 1"),this.ensureColumn("release_runs","source","TEXT NOT NULL DEFAULT 'automatic'"),this.ensureColumn("prs","watch_enabled","INTEGER NOT NULL DEFAULT 1"),this.ensureColumn("prs","docs_assessment_json","TEXT"),this.get("SELECT 1 AS present FROM config WHERE id = 1")||this.writeConfig(rt),this.get("SELECT 1 AS present FROM runtime_state WHERE id = 1")||this.run(`
|
|
408
408
|
INSERT INTO runtime_state (id, drain_mode, drain_requested_at, drain_reason)
|
|
409
409
|
VALUES (1, 0, NULL, NULL)
|
|
410
|
-
`)}ensureColumn(e,r,n){this.all(`PRAGMA table_info(${e})`).some(s=>s.name===r)||this.exec(`ALTER TABLE ${e} ADD COLUMN ${r} ${n}`)}parseConfigRow(e,r){if(!e)return{...
|
|
410
|
+
`)}ensureColumn(e,r,n){this.all(`PRAGMA table_info(${e})`).some(s=>s.name===r)||this.exec(`ALTER TABLE ${e} ADD COLUMN ${r} ${n}`)}parseConfigRow(e,r){if(!e)return{...rt,watchedRepos:r};let n=EM(e.github_tokens_json),i=e.github_token.trim();return{githubTokens:n.length>0?n:i?[i]:[],codingAgent:e.coding_agent,fallbackToNextCodingAgent:!!(e.fallback_to_next_coding_agent??Number(rt.fallbackToNextCodingAgent)),maxTurns:e.max_turns,batchWindowMs:e.batch_window_ms,pollIntervalMs:e.poll_interval_ms,maxChangesPerRun:e.max_changes_per_run,autoResolveMergeConflicts:!!e.auto_resolve_merge_conflicts,autoCreateReleases:!!(e.auto_create_releases??Number(rt.autoCreateReleases)),autoUpdateDocs:!!(e.auto_update_docs??1),includeRepositoryLinksInGitHubComments:!!(e.include_repository_links_in_github_comments??Number(rt.includeRepositoryLinksInGitHubComments)),postGitHubProgressReplies:!!(e.post_github_progress_replies??Number(rt.postGitHubProgressReplies)),autoHealCI:!!(e.auto_heal_ci??Number(rt.autoHealCI)),maxHealingAttemptsPerSession:e.max_healing_attempts_per_session??rt.maxHealingAttemptsPerSession,maxHealingAttemptsPerFingerprint:e.max_healing_attempts_per_fingerprint??rt.maxHealingAttemptsPerFingerprint,maxConcurrentHealingRuns:e.max_concurrent_healing_runs??rt.maxConcurrentHealingRuns,healingCooldownMs:e.healing_cooldown_ms??rt.healingCooldownMs,autoHealDeployments:!!(e.auto_heal_deployments??rt.autoHealDeployments),deploymentCheckDelayMs:e.deployment_check_delay_ms??rt.deploymentCheckDelayMs,deploymentCheckTimeoutMs:e.deployment_check_timeout_ms??rt.deploymentCheckTimeoutMs,deploymentCheckPollIntervalMs:e.deployment_check_poll_interval_ms??rt.deploymentCheckPollIntervalMs,watchedRepos:r,trustedReviewers:JSON.parse(e.trusted_reviewers_json),ignoredBots:JSON.parse(e.ignored_bots_json)}}writeConfig(e){this.withWriteTransaction(()=>{let r=new Map(this.getWatchedRepoRows().map(i=>[i.repo,i])),n=this.get("SELECT model FROM config WHERE id = 1")?.model??vM;this.run(`
|
|
411
411
|
INSERT INTO config (
|
|
412
412
|
id,
|
|
413
413
|
github_token,
|
|
@@ -462,7 +462,7 @@ and ensure you are accounting for this risk.
|
|
|
462
462
|
deployment_check_poll_interval_ms = excluded.deployment_check_poll_interval_ms,
|
|
463
463
|
trusted_reviewers_json = excluded.trusted_reviewers_json,
|
|
464
464
|
ignored_bots_json = excluded.ignored_bots_json
|
|
465
|
-
`,1,e.githubTokens[0]??"",JSON.stringify(e.githubTokens),e.codingAgent,Number(e.fallbackToNextCodingAgent),n,e.maxTurns,e.batchWindowMs,e.pollIntervalMs,e.maxChangesPerRun,Number(e.autoResolveMergeConflicts),Number(e.autoCreateReleases),Number(e.autoUpdateDocs),Number(e.includeRepositoryLinksInGitHubComments),Number(e.postGitHubProgressReplies),Number(e.autoHealCI),e.maxHealingAttemptsPerSession,e.maxHealingAttemptsPerFingerprint,e.maxConcurrentHealingRuns,e.healingCooldownMs,Number(e.autoHealDeployments),e.deploymentCheckDelayMs,e.deploymentCheckTimeoutMs,e.deploymentCheckPollIntervalMs,JSON.stringify(e.trustedReviewers),JSON.stringify(e.ignoredBots)),this.exec("DELETE FROM watched_repos");for(let i of e.watchedRepos){let s=r.get(i);this.run("INSERT INTO watched_repos (repo, auto_create_releases, own_prs_only) VALUES (?, ?, ?)",i,s?.auto_create_releases??
|
|
465
|
+
`,1,e.githubTokens[0]??"",JSON.stringify(e.githubTokens),e.codingAgent,Number(e.fallbackToNextCodingAgent),n,e.maxTurns,e.batchWindowMs,e.pollIntervalMs,e.maxChangesPerRun,Number(e.autoResolveMergeConflicts),Number(e.autoCreateReleases),Number(e.autoUpdateDocs),Number(e.includeRepositoryLinksInGitHubComments),Number(e.postGitHubProgressReplies),Number(e.autoHealCI),e.maxHealingAttemptsPerSession,e.maxHealingAttemptsPerFingerprint,e.maxConcurrentHealingRuns,e.healingCooldownMs,Number(e.autoHealDeployments),e.deploymentCheckDelayMs,e.deploymentCheckTimeoutMs,e.deploymentCheckPollIntervalMs,JSON.stringify(e.trustedReviewers),JSON.stringify(e.ignoredBots)),this.exec("DELETE FROM watched_repos");for(let i of e.watchedRepos){let s=r.get(i);this.run("INSERT INTO watched_repos (repo, auto_create_releases, own_prs_only) VALUES (?, ?, ?)",i,s?.auto_create_releases??0,s?.own_prs_only??1)}})}parseWatchedRepoRow(e){return{repo:e.repo,autoCreateReleases:!!e.auto_create_releases,ownPrsOnly:!!(e.own_prs_only??1)}}getWatchedRepoRows(){return this.all("SELECT repo, auto_create_releases, own_prs_only FROM watched_repos ORDER BY repo ASC")}getWatchedRepos(){return this.getWatchedRepoRows().map(e=>e.repo)}parsePRRow(e,r){return{id:e.id,number:e.number,title:e.title,repo:e.repo,branch:e.branch,author:e.author,url:e.url,status:e.status,feedbackItems:r,accepted:e.accepted,rejected:e.rejected,flagged:e.flagged,testsPassed:e.tests_passed===null?null:!!e.tests_passed,lintPassed:e.lint_passed===null?null:!!e.lint_passed,lastChecked:e.last_checked,watchEnabled:!!e.watch_enabled,docsAssessment:this.parseDocsAssessment(e.docs_assessment_json),addedAt:e.added_at}}parseDocsAssessment(e){if(!e)return null;try{return Of.parse(JSON.parse(e))}catch{return null}}parseRuntimeStateRow(e){return e?{drainMode:!!e.drain_mode,drainRequestedAt:e.drain_requested_at,drainReason:e.drain_reason}:{..._M}}parseAgentRunRow(e){return{id:e.id,prId:e.pr_id,preferredAgent:e.preferred_agent,resolvedAgent:e.resolved_agent,status:e.status,phase:e.phase,prompt:e.prompt,initialHeadSha:e.initial_head_sha,metadata:e.metadata_json?JSON.parse(e.metadata_json):null,lastError:e.last_error,createdAt:e.created_at,updatedAt:e.updated_at}}parseBackgroundJobRow(e){return{id:e.id,kind:e.kind,targetId:e.target_id,dedupeKey:e.dedupe_key,status:If.parse(e.status),priority:e.priority,availableAt:e.available_at,leaseOwner:e.lease_owner,leaseToken:e.lease_token,leaseExpiresAt:e.lease_expires_at,heartbeatAt:e.heartbeat_at,attemptCount:e.attempt_count,lastError:e.last_error,payload:JSON.parse(e.payload_json),createdAt:e.created_at,updatedAt:e.updated_at,completedAt:e.completed_at}}finalizeBackgroundJob(e,r,n,i,s){return this.withWriteTransaction(()=>{let a=this.get(`
|
|
466
466
|
SELECT id, kind, target_id, dedupe_key, status, priority, available_at,
|
|
467
467
|
lease_owner, lease_token, lease_expires_at, heartbeat_at, attempt_count,
|
|
468
468
|
last_error, payload_json, created_at, updated_at, completed_at
|
|
@@ -554,7 +554,7 @@ and ensure you are accounting for this risk.
|
|
|
554
554
|
deployment_check_poll_interval_ms, trusted_reviewers_json, ignored_bots_json
|
|
555
555
|
FROM config
|
|
556
556
|
WHERE id = 1
|
|
557
|
-
`);return this.parseConfigRow(e,this.getWatchedRepos())}async updateConfig(e){let r=await this.getConfig(),n=nm(r,e);return this.writeConfig(n),n}async listRepoSettings(){return this.getWatchedRepoRows().map(e=>this.parseWatchedRepoRow(e))}async getRepoSettings(e){let r=this.get("SELECT repo, auto_create_releases, own_prs_only FROM watched_repos WHERE repo = ?",e);return r?this.parseWatchedRepoRow(r):void 0}async updateRepoSettings(e,r){let n=await this.getRepoSettings(e)??{repo:e,autoCreateReleases:!
|
|
557
|
+
`);return this.parseConfigRow(e,this.getWatchedRepos())}async updateConfig(e){let r=await this.getConfig(),n=nm(r,e);return this.writeConfig(n),n}async listRepoSettings(){return this.getWatchedRepoRows().map(e=>this.parseWatchedRepoRow(e))}async getRepoSettings(e){let r=this.get("SELECT repo, auto_create_releases, own_prs_only FROM watched_repos WHERE repo = ?",e);return r?this.parseWatchedRepoRow(r):void 0}async updateRepoSettings(e,r){let n=await this.getRepoSettings(e)??{repo:e,autoCreateReleases:!1,ownPrsOnly:!0},i=im(n,r);return this.withWriteTransaction(()=>{this.run(`
|
|
558
558
|
INSERT INTO watched_repos (repo, auto_create_releases, own_prs_only)
|
|
559
559
|
VALUES (?, ?, ?)
|
|
560
560
|
ON CONFLICT(repo) DO UPDATE SET
|
|
@@ -1067,8 +1067,8 @@ ${In}`:i}function OP(t){let e=t.trimEnd();if(e===In)return{bodyWithoutFooter:"",
|
|
|
1067
1067
|
|
|
1068
1068
|
`+In;return e.endsWith(r)?{bodyWithoutFooter:e.slice(0,-r.length),hadFooter:!0}:{bodyWithoutFooter:t,hadFooter:!1}}function bY(t,e){if(!e)return t;let{bodyWithoutFooter:r}=OP(t);return r?`${r}
|
|
1069
1069
|
|
|
1070
|
-
${In}`:In}function Yl(t,e){return[t,...e].join(" ")}function qi(t){return t.stderr.trim()||t.stdout.trim()||"no output"}function yY(t){return/\b(Could not resolve host|ENOTFOUND|EAI_AGAIN|ECONNRESET|network error|Failed to connect|Connection timed out)\b/i.test(t)}function Mi(t,e){let r=qi(e);return yY(r)?`Infrastructure Git failure while ${t}: ${r}`:`${t} failed: ${r}`}function St(t){return t instanceof Error?t.message:String(t)}function vY(t){return t==="claude"?"codex":"claude"}function _P(t){let n=(t.replace(/^(?:claude|codex|agent) apply failed \(\d+\):\s*/i,"").replace(/^Agent failed to resolve merge conflicts \(\d+\):\s*/i,"").replace(/^Error:\s*/i,"").split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)??"No failure details were reported").replace(/\s+/g," "),i=n.length>180?`${n.slice(0,177).trimEnd()}...`:n;return/[.!?]$/.test(i)?i:`${i}.`}function wY(t,e){let n=`${t}${e}`.split(/\r?\n/);return{lines:n.slice(0,-1),buffer:n.at(-1)??""}}async function xY(t,e){let r=await e("git",["config","--get","user.name"],{cwd:t,timeoutMs:3e3});(r.code!==0||!r.stdout.trim())&&await e("git",["config","user.name",GQ],{cwd:t,timeoutMs:3e3});let n=await e("git",["config","--get","user.email"],{cwd:t,timeoutMs:3e3});(n.code!==0||!n.stdout.trim())&&await e("git",["config","user.email",BQ],{cwd:t,timeoutMs:3e3})}async function ia(t){try{return await(0,SP.access)(t),!0}catch(e){if(e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR"))return!1;throw e}}async function IP(t){if(!t.requiresVerification)return{ok:!0};let e=ji.default.join(t.cwd,"package.json");if(!await ia(e))return{ok:!0};let r={packageLock:await ia(ji.default.join(t.cwd,"package-lock.json")),npmShrinkwrap:await ia(ji.default.join(t.cwd,"npm-shrinkwrap.json")),pnpmLock:await ia(ji.default.join(t.cwd,"pnpm-lock.yaml")),yarnLock:await ia(ji.default.join(t.cwd,"yarn.lock"))};if(!r.packageLock&&!r.npmShrinkwrap&&!r.pnpmLock&&!r.yarnLock)return{ok:!0};if(!await ia(ji.default.join(t.cwd,"node_modules"))){if((await t.runCommand("git",["check-ignore","-q","node_modules/"],{cwd:t.cwd,timeoutMs:5e3})).code!==0)return{ok:!1,reason:"Node dependency cache is missing, but node_modules is not ignored by git; refusing to install dependencies automatically"};let i=r.pnpmLock?{command:"pnpm",args:["install","--frozen-lockfile"]}:r.yarnLock?{command:"yarn",args:["install","--frozen-lockfile"]}:{command:"npm",args:["ci"]},s=await t.runCommand(i.command,i.args,{cwd:t.cwd,timeoutMs:3e5});if(s.code!==0)return{ok:!1,reason:pn(s,`Dependency install failed while running ${i.command} ${i.args.join(" ")}`)}}return{ok:!0}}function EP(t){return new Promise(e=>setTimeout(e,t))}var Zl=class{storage;inProgress=new Set;feedbackMutationLocks=new Map;github;runtime;releaseManager;deploymentHealingManager;scheduleBackgroundJob;clock;agentHealthCache=new Map;constructor(e,r=WQ,n=VQ,i,s,a){this.storage=e,this.github=r,this.runtime=n,this.releaseManager=i,this.deploymentHealingManager=a,this.scheduleBackgroundJob=s,this.clock=n.now??(()=>new Date)}now(){return this.clock()}async readAgentHealth(e){let r=this.now().getTime(),n=this.agentHealthCache.get(e);if(n&&r-n.checkedAtMs<HQ)return n.result;let i=this.runtime.checkAgentHealth?await this.runtime.checkAgentHealth(e):{ok:!0};return this.agentHealthCache.set(e,{checkedAtMs:r,result:i}),i}async pauseAutomationForAgentFailure(e,r,n){let i=`Agent health check failed for ${e}: ${r}`;await this.storage.updateRuntimeState({drainMode:!0,drainRequestedAt:this.now().toISOString(),drainReason:i}),await Promise.all(n.map(async s=>{let a=await this.storage.getPR(s);if(a){let o=a.feedbackItems.map(u=>u.decision==="accept"&&(u.status==="queued"||u.status==="in_progress")?I0(u,i):u);if(o.some((u,c)=>u!==a.feedbackItems[c])){let u=Fi(o);await this.storage.updatePR(a.id,{feedbackItems:o,accepted:u.accepted,rejected:u.rejected,flagged:u.flagged})}}await this.storage.addLog(s,"error",`Automation paused: ${i}`,{phase:"agent.health"})}))}async ensureAgentHealthy(e,r){let n=await this.readAgentHealth(e);if(!n.ok)throw await this.pauseAutomationForAgentFailure(e,n.reason,r),new Error(`Agent health check failed for ${e}: ${n.reason}`)}async supersedeActiveHealingSessionsForArchivedPr(e){let r=await this.storage.listHealingSessions({prId:e}),n=this.now().toISOString();for(let i of r)ea(i.state)||await this.storage.updateHealingSession(i.id,{state:"superseded",endedAt:n,escalationReason:"PR archived on GitHub"})}getActiveRunCount(){return this.inProgress.size}async waitForIdle(e=12e4){let r=Date.now();for(;this.inProgress.size>0;){if(Date.now()-r>=e)return!1;await EP(100)}return!0}async runQueuedBabysitPR(e,r){let n=(await this.storage.listAgentRuns({status:"running",prId:e})).slice().sort((s,a)=>Date.parse(a.updatedAt)-Date.parse(s.updatedAt))[0];if(!n){await this.babysitPR(e,r,{allowDuringDrain:!0,rethrowOnFailure:!0});return}if(!!!(n.prompt&&n.resolvedAgent&&n.initialHeadSha)){let s=new Date().toISOString();await this.storage.upsertAgentRun({...n,status:"failed",phase:"run.failed",lastError:"Interrupted run missing replay context",updatedAt:s}),await this.babysitPR(e,r,{allowDuringDrain:!0,rethrowOnFailure:!0});return}await this.babysitPR(e,n.preferredAgent,{runId:n.id,recoveryMode:!0,forceAgentPrompt:n.prompt,forceResolvedAgent:n.resolvedAgent,replayInitialHeadSha:n.initialHeadSha,allowDuringDrain:!0,rethrowOnFailure:!0})}async resumeInterruptedRuns(){let e=await this.storage.listAgentRuns({status:"running"});if(e.length!==0){if(this.scheduleBackgroundJob){let r=new Set;for(let n of e)r.has(n.prId)||(r.add(n.prId),await this.scheduleBackgroundJob("babysit_pr",n.prId,Or("babysit_pr",n.prId),{preferredAgent:n.preferredAgent}));return}for(let r of e){if(!!!(r.prompt&&r.resolvedAgent&&r.initialHeadSha)){let i=new Date().toISOString();await this.storage.upsertAgentRun({...r,status:"failed",phase:"run.failed",lastError:"Interrupted run missing replay context",updatedAt:i}),await this.babysitPR(r.prId,r.preferredAgent,{allowDuringDrain:!0});continue}await this.babysitPR(r.prId,r.preferredAgent,{runId:r.id,recoveryMode:!0,forceAgentPrompt:r.prompt,forceResolvedAgent:r.resolvedAgent,replayInitialHeadSha:r.initialHeadSha,allowDuringDrain:!0})}}}async withFeedbackMutationLock(e,r){let n=this.feedbackMutationLocks.get(e)??Promise.resolve(),i,s=new Promise(o=>{i=()=>o()}),a=n.then(()=>s);this.feedbackMutationLocks.set(e,a),await n;try{return await r()}finally{i?.(),this.feedbackMutationLocks.get(e)===a&&this.feedbackMutationLocks.delete(e)}}async retryFeedbackItem(e,r){return this.withFeedbackMutationLock(e,async()=>{let n=await this.storage.getPR(e);if(!n)return{kind:"pr_not_found"};let i=n.feedbackItems.find(u=>u.id===r);if(!i)return{kind:"feedback_not_found"};if(i.status!=="failed"&&i.status!=="warning")return{kind:"feedback_not_retryable"};let s=n.feedbackItems.map(u=>u.id===r?mP(u):u),a=Fi(s),o=await this.storage.updatePR(n.id,{feedbackItems:s,accepted:a.accepted,rejected:a.rejected,flagged:a.flagged});if(!o)throw new Error(`Failed to queue retry for feedback item ${r} on PR ${e}`);return{kind:"ok",updated:o}})}async syncFeedbackForPR(e,r){let n=await this.storage.getPR(e);if(!n)throw new Error("PR not found");let i=dt(n.repo);if(!i)throw new Error(`Invalid repository slug: ${n.repo}`);let s={owner:i.owner,repo:i.repo,number:n.number},a=await this.storage.getConfig(),o=await this.github.buildOctokit(a),u=r?.phase??"sync";r?.logStart&&await this.storage.addLog(n.id,"info","Syncing GitHub comments/reviews...",{runId:r.runId??null,phase:u});let c=await this.github.fetchFeedbackItemsForPR(o,s,a),{merged:l,newCount:p}=JQ(n.feedbackItems,c),d=Fi(l),m=await this.storage.updatePR(n.id,{title:n.title,status:n.status,lastChecked:new Date().toISOString(),feedbackItems:l,accepted:d.accepted,rejected:d.rejected,flagged:d.flagged});if(!m)throw new Error("Failed to update PR after feedback sync");return await this.storage.addLog(n.id,"info",KQ(c.length,p),{runId:r?.runId??null,phase:u,metadata:{total:c.length,newCount:p}}),m}async syncAndBabysitTrackedRepos(){if((await this.storage.getRuntimeState()).drainMode)return;let r=[...await this.storage.getPRs(),...await this.storage.getArchivedPRs()].filter(XQ);for(let f of r)try{await this.syncFeedbackForPR(f.id,{phase:"repair"})}catch(g){await this.storage.addLog(f.id,"warn",`Could not repair missing GitHub review-thread metadata: ${St(g)}`,{phase:"repair"})}let n=await this.storage.getConfig(),i=await this.storage.getPRs(),s=new Set([...i.map(f=>f.repo),...n.watchedRepos]),a=n.codingAgent,o=i.filter(f=>f.watchEnabled!==!1&&f.status!=="archived").map(f=>f.id);if(s.size>0)try{await this.ensureAgentHealthy(a,o)}catch{return}let u=new Map((await this.storage.listRepoSettings()).map(f=>[f.repo,f])),c=await this.github.buildOctokit(n),l=Array.from(s).some(f=>u.get(f)?.ownPrsOnly??!0),p=null,d=async()=>l?(p||(p=(this.github.getAuthenticatedLogin?.(c)??Promise.resolve(null)).catch(f=>(Go.warn({err:f instanceof Error?f.message:String(f)},"Failed to determine authenticated GitHub login for watcher filtering"),null))),p):null,m=Array.from(s).map(f=>dt(f)).filter(f=>!!f);for(let f of m){let g=Pn(f),h;try{h=await this.github.listOpenPullsForRepo(c,f)}catch(I){Go.warn({err:I instanceof Error?I.message:String(I),repo:g},"Failed to list open PRs");continue}let T=new Set(h.map(I=>I.number)),R=u.get(g)?.ownPrsOnly??!0,S=R?await d():null,P=new Set(h.filter(I=>!R||S!==null&&I.author.trim().toLowerCase()===S).map(I=>I.number)),F=i.filter(I=>I.repo===g);for(let I of F)if(!T.has(I.number)&&I.status!=="archived"){let A;if(this.github.fetchPullCloseState)try{A=await this.github.fetchPullCloseState(c,{owner:f.owner,repo:f.repo,number:I.number})}catch(v){await this.storage.addLog(I.id,"warn",`Could not confirm merge state before archival: ${St(v)}`,{phase:"watcher"})}await this.storage.updatePR(I.id,{status:"archived"}),await this.supersedeActiveHealingSessionsForArchivedPr(I.id),await this.storage.addLog(I.id,"info",`PR #${I.number} is no longer open on GitHub \u2014 archived`,{phase:"watcher"});let j=u.get(g)?.autoCreateReleases??!0;if(A?.merged&&this.releaseManager&&n.autoCreateReleases)if(!j)await this.storage.addLog(I.id,"info",`PR #${I.number} was merged, but auto-release is disabled for ${g}`,{phase:"watcher"});else{let v=A.baseRef.trim(),L=A.mergeCommitSha||A.headSha,w=A.mergedAt||A.closedAt;if(!v||!L||!w){let k=[v?null:"a base branch",L?null:"a commit SHA",w?null:"a merge timestamp"].filter(x=>!!x);await this.storage.addLog(I.id,"warn",`PR #${I.number} was merged, but release evaluation was not queued because GitHub did not return ${k.join(" and ")}.`,{phase:"watcher",metadata:{baseBranch:v,headSha:A.headSha,mergeCommitSha:A.mergeCommitSha,mergedAt:A.mergedAt,closedAt:A.closedAt}})}else try{await this.releaseManager.enqueueMergedPullReleaseEvaluation({repo:g,baseBranch:v,triggerPrNumber:A.number,triggerPrTitle:A.title,triggerPrUrl:A.url,triggerMergeSha:L,triggerMergedAt:w}),await this.storage.addLog(I.id,"info",`PR #${I.number} was merged \u2014 queued release evaluation`,{phase:"watcher",metadata:{baseBranch:v,triggerMergeSha:L}})}catch(k){await this.storage.addLog(I.id,"warn",`PR #${I.number} was merged, but release evaluation could not be queued: ${St(k)}`,{phase:"watcher"})}}else A&&!A.merged&&await this.storage.addLog(I.id,"info",`PR #${I.number} closed without merge`,{phase:"watcher"});if(A?.merged&&this.deploymentHealingManager&&this.scheduleBackgroundJob&&n.autoHealDeployments){let v=A.baseRef.trim(),L=A.mergeCommitSha||A.headSha;if(v&&L)try{let w=await this.github.resolveGitHubAuthToken(n),k=ql(g,w),{repoCacheDir:x}=await Wl({repoFullName:g,repoCloneUrl:k,runCommand:this.runtime.runCommand}),C=await uP(x);C&&(await this.scheduleBackgroundJob("heal_deployment",`${g}:${L}`,Or("heal_deployment",`${g}:${L}`),{repo:g,platform:C.platform,mergeSha:L,triggerPrNumber:I.number,triggerPrTitle:I.title,triggerPrUrl:I.url,baseBranch:v,...On({label:`Healing ${C.platform} deployment`,detail:`${g} PR #${I.number} - ${I.title}`,targetUrl:I.url})}),await this.storage.addLog(I.id,"info",`PR #${I.number} merged \u2014 queued deployment healing (${C.platform})`,{phase:"watcher",metadata:{platform:C.platform,mergeSha:L}}))}catch(w){await this.storage.addLog(I.id,"warn",`Failed to queue deployment healing: ${St(w)}`,{phase:"watcher"})}}}for(let I of h){let A=await this.storage.getPRByRepoAndNumber(g,I.number);if(!A){if(!P.has(I.number))continue;A=await this.storage.addPR({number:I.number,title:I.title,repo:g,branch:I.branch,author:I.author,url:I.url,status:"watching",feedbackItems:[],accepted:0,rejected:0,flagged:0,testsPassed:null,lintPassed:null,lastChecked:null}),await this.storage.addLog(A.id,"info",`Auto-registered open PR #${I.number} from ${g}`)}P.has(I.number)&&A.watchEnabled&&(await this.storage.addLog(A.id,"info","Watcher queued autonomous babysitter run",{phase:"watcher",metadata:{repo:g}}),this.scheduleBackgroundJob?await this.scheduleBackgroundJob("babysit_pr",A.id,Or("babysit_pr",A.id),{preferredAgent:n.codingAgent,...On({label:`Babysitting PR #${A.number}`,detail:`${A.repo} - ${A.title}`,targetUrl:A.url})}):await this.babysitPR(A.id,n.codingAgent))}}}async pollForCICompletion(e,r,n,i,s,a){let u=this.runtime.ciPollIntervalMs??3e4;for(let c=1;c<=10;c++){await EP(u);try{let l=await this.github.checkCISettled(e,r,i),p=await this.github.listFailingStatuses(e,r,i);if(await a(s,"info",`CI poll attempt ${c}/10: ${p.length} failure(s), settled=${l}`,{phase:"verify.ci",metadata:{attempt:c,failures:p.length,settled:l}}),l)return p.length>0?{status:"failure",failures:p}:{status:"success",failures:[]}}catch(l){await a(s,"warn",`CI poll attempt ${c} failed: ${St(l)}`,{phase:"verify.ci",metadata:{attempt:c}})}}try{let c=await this.github.listFailingStatuses(e,r,i);if(c.length>0)return{status:"failure",failures:c}}catch(c){await a(s,"warn",`Final CI status check after timeout failed: ${St(c)}`,{phase:"verify.ci"})}return{status:"timeout",failures:[]}}async babysitPR(e,r,n){if((await this.storage.getRuntimeState()).drainMode&&!n?.allowDuringDrain){let A=await this.storage.getPR(e);A&&await this.storage.addLog(A.id,"warn","Babysitter run skipped because drain mode is enabled",{phase:"run"});return}if(this.inProgress.has(e)){let A=await this.storage.getPR(e);A&&await this.storage.addLog(A.id,"warn","Babysitter run skipped because another run is already in progress",{phase:"run"});return}this.inProgress.add(e);let s=n?.runId||(0,TP.randomUUID)(),a=Math.floor(Date.now()/1e3)*1e3-1e3,o=Promise.resolve(),u=new Date().toISOString(),c=await this.storage.getAgentRun(s)||{id:s,prId:e,preferredAgent:r,resolvedAgent:n?.forceResolvedAgent??null,status:"running",phase:"run.started",prompt:n?.forceAgentPrompt??null,initialHeadSha:n?.replayInitialHeadSha??null,metadata:{recoveryMode:!!n?.recoveryMode},lastError:null,createdAt:u,updatedAt:u};await this.storage.upsertAgentRun(c);let l=async A=>{c={...c,...A,updatedAt:new Date().toISOString()},await this.storage.upsertAgentRun(c)},p=(A,j,v,L)=>(o=o.then(async()=>{await this.storage.addLog(A,j,v,{runId:s,phase:L?.phase??null,metadata:L?.metadata??null})}).catch(w=>{Go.warn({err:w instanceof Error?w.message:String(w)},"Babysitter log write failed")}),o),d=async(A,j,v,L)=>{await p(A,"warn",v,{phase:j,metadata:L??null})},m=(A,j,v,L,w)=>{let k="",x=0,C=!1,_=D=>w!==void 0&&x>=w?C?o:(C=!0,p(A,L,`[${v}] output truncated after ${w} line(s)`,{phase:j,metadata:{stream:v,truncated:!0,maxLines:w}})):(x+=1,p(A,L,`[${v}] ${D}`,{phase:j,metadata:{stream:v}}));return{onChunk:D=>{let E=wY(k,D);k=E.buffer;for(let U of E.lines){let Z=U.trim();Z&&_(Z)}},flush:async()=>{let D=k.trim();if(k="",D){await _(D);return}await o}}},f=async A=>{let{currentPrId:j,command:v,args:L,cwd:w,timeoutMs:k,phase:x,successMessage:C,maxOutputLogLines:_}=A;await p(j,"info",`Running ${Yl(v,L)}`,{phase:x});let D=m(j,x,"stdout","info",_),E=m(j,x,"stderr","warn",_),U=await this.runtime.runCommand(v,L,{cwd:w,timeoutMs:k,onStdoutChunk:D.onChunk,onStderrChunk:E.onChunk});return await D.flush(),await E.flush(),U.code===0?await p(j,"info",C,{phase:x,metadata:{command:Yl(v,L),code:U.code}}):await p(j,"error",`${Yl(v,L)} failed (${U.code})`,{phase:x,metadata:{command:Yl(v,L),code:U.code,summary:qi(U)}}),U},g=async A=>{let j=await f({currentPrId:A.currentPrId,command:"git",args:["status","--porcelain"],cwd:A.cwd,timeoutMs:5e3,phase:A.phase,successMessage:"Collected worktree git status"});if(j.code!==0)throw new Error(Mi("checking worktree status",j));if(!j.stdout.trim())return await p(A.currentPrId,"info",`No worktree changes to commit after ${A.context}`,{phase:A.phase}),!1;let v=await f({currentPrId:A.currentPrId,command:"git",args:["add","-A"],cwd:A.cwd,timeoutMs:3e4,phase:A.phase,successMessage:"Staged worktree changes"});if(v.code!==0)throw new Error(Mi("staging worktree changes",v));let L=await f({currentPrId:A.currentPrId,command:"git",args:A.commitArgs,cwd:A.cwd,timeoutMs:6e4,phase:A.phase,successMessage:"Committed worktree changes"});if(L.code!==0)throw new Error(Mi("committing worktree changes",L));return!0},h=[],T=n?.forceAgentPrompt??null,R=n?.forceResolvedAgent??null,S=n?.replayInitialHeadSha??null,P=!!n?.recoveryMode,F=!1,I=!1;try{await l({status:"running",phase:"run.started",metadata:{...c.metadata??{},recoveryMode:P},lastError:null}),await this.storage.updatePR(e,{status:"processing",lastChecked:new Date().toISOString()}),await p(e,"info",`Babysitter run started using preferred agent ${r}${P?" (recovery)":""}`,{phase:"run",metadata:{preferredAgent:r,recoveryMode:P}});let A=await this.storage.getConfig(),j=R||r;await this.ensureAgentHealthy(j,[e]),await l({phase:"run.sync"});let v=await this.syncFeedbackForPR(e,{runId:s,logStart:!0,phase:"sync"}),L=R||await this.runtime.resolveAgent(r,{allowFallback:A.fallbackToNextCodingAgent});L!==j&&await this.ensureAgentHealthy(L,[v.id]),await l({resolvedAgent:L});let w=dt(v.repo);if(!w)throw new Error(`Invalid repository slug: ${v.repo}`);await p(v.id,"info",`Resolved coding agent to ${L}`,{phase:"run"});let k=!1;if(!R&&A.fallbackToNextCodingAgent&&L!==r){k=!0;let O=`Configured coding agent ${r} CLI is not installed`;await p(v.id,"warn",`Falling back from ${r} to ${L} because ${r} is not working: ${O}`,{phase:"run",metadata:{failedAgent:r,fallbackAgent:L}}),await l({metadata:{...c.metadata??{},fallbackFromAgent:r,fallbackReason:O}})}let x=async(O,J)=>{if(!A.fallbackToNextCodingAgent||R||k||!nE(O))return!1;let H=L,me=vY(H),K;try{K=await this.runtime.resolveAgent(me,{allowFallback:!1})}catch{return!1}k=!0,L=K;let Te=St(O);return await p(v.id,"warn",`Falling back from ${H} to ${L} because ${H} is not working: ${Te}`,{phase:J,metadata:{failedAgent:H,fallbackAgent:L}}),await l({resolvedAgent:L,metadata:{...c.metadata??{},fallbackFromAgent:H,fallbackReason:Te}}),!0},C=async O=>{try{return await this.runtime.evaluateFixNecessityWithAgent({agent:L,cwd:O.cwd,prompt:O.prompt})}catch(J){if(await x(J,O.phase))return this.runtime.evaluateFixNecessityWithAgent({agent:L,cwd:O.cwd,prompt:O.prompt});throw J}},_=await this.github.buildOctokit(A),D={owner:w.owner,repo:w.repo,number:v.number},E=await this.github.fetchPullSummary(_,D);T&&S&&E.headSha!==S&&(F=!0,await p(v.id,"warn",`Skipping forced prompt replay because PR head moved (${S.slice(0,7)} -> ${E.headSha.slice(0,7)})`,{phase:"run.replay",metadata:{replayInitialHeadSha:S,currentHeadSha:E.headSha}}));let U=await this.github.listFailingStatuses(_,w,E.headSha),Z=this.now().toISOString(),Ee=(this.github.fetchCheckSnapshotsForRef?await this.github.fetchCheckSnapshotsForRef(_,w,v.id,E.headSha):U.map(O=>({id:`${O.context}:${O.description}:${E.headSha}`,prId:v.id,sha:E.headSha,provider:"github.commit_status",context:O.context,status:"failure",conclusion:null,description:O.description,targetUrl:O.targetUrl,observedAt:Z}))).filter(O=>Sm(O)),fe=k0(Ee),oe=fe.filter(O=>O.classification==="healable_in_branch"),pe=fe.filter(O=>O.classification==="blocked_external"),Ie=new Bl(this.storage,()=>this.now()),G=null;if(Ee.length>0)G=await Ie.ensureSessionForHead({prId:v.id,repo:v.repo,prNumber:v.number,headSha:E.headSha}),await vP(this.storage,Ee),await wP(this.storage,G.id,E.headSha,fe),ea(G.state)?await p(v.id,"info",`CI healing session ${G.id} is already ${G.state}; skipping repair transition`,{phase:"healing.state",metadata:{healingSessionId:G.id,healingState:G.state,headSha:E.headSha}}):pe.length>0?G=await Ie.markBlocked(G.id,pe[0]?.summary??"CI failure classified as blocked_external",{latestFingerprint:pe[0]?.fingerprint??null,currentHeadSha:E.headSha}):oe.length>0?G=await Ie.markAwaitingRepairSlot(G.id,{latestFingerprint:oe[0]?.fingerprint??null,currentHeadSha:E.headSha}):G=await Ie.markEscalated(G.id,"CI failure could not be classified as healable in branch",{latestFingerprint:fe[0]?.fingerprint??null,currentHeadSha:E.headSha});else{let O=await Ie.getSessionByPrAndHead(v.id,E.headSha);O&&["triaging","awaiting_repair_slot","repairing","awaiting_ci","verifying","cooldown"].includes(O.state)?(G=await Ie.markVerifying(O.id,{currentHeadSha:E.headSha}),G=await Ie.markHealed(G.id,{currentHeadSha:E.headSha,lastImprovementScore:G.lastImprovementScore??0})):G=O??null}let le=A.includeRepositoryLinksInGitHubComments,Ir=A.postGitHubProgressReplies,mt=new Map(Object.entries(hP(c.metadata))),it=async(O,J)=>{let H={...hP(c.metadata),[O]:J};await l({metadata:{...c.metadata??{},statusReplyRefs:H}})},sp=async O=>{let J=mt.get(O);if(J)return J;let H=v.feedbackItems.find(K=>K.id===O);if(!H)return null;let me=bP(H,v.feedbackItems);return me?(mt.set(O,me),await it(O,me),me):null},Zr=async(O,J)=>{let H=await sp(O);if(H)try{let me=xP(H.body,J);await this.github.updateStatusReply(_,D,H,me),await it(O,H)}catch(me){let K=v.feedbackItems.find(je=>je.id===O),Te=K?bP(K,v.feedbackItems):null;if(Te&&Te.commentDatabaseId!==H.commentDatabaseId)try{let je=xP(Te.body,J);await this.github.updateStatusReply(_,D,Te,je),mt.set(O,Te),await it(O,Te);return}catch(je){await d(v.id,"github.status",`Failed to update recovered status reply for ${O}: ${St(je)}`,{feedbackId:O});return}await d(v.id,"github.status",`Failed to update status reply for ${O}: ${St(me)}`,{feedbackId:O})}},aa=async(O,J)=>{try{await this.github.postPRComment(_,D,hY(O,J,le))}catch(H){await d(v.id,"github.agent-command",`Failed to post agent command comment: ${St(H)}`)}},U0=async O=>{let{phase:J,onFallback:H,...me}=O,K=await this.runtime.applyFixesWithAgent({agent:L,...me});if(K.code===0)return K;let Te=new Error(`${L} apply failed (${K.code}): ${K.stderr||K.stdout}`);return await x(Te,J)?(await H?.(L),await p(v.id,"info",`Launching ${L} after fallback`,{phase:J,metadata:{agent:L,prompt:O.prompt}}),await aa(L,O.prompt),this.runtime.applyFixesWithAgent({agent:L,...me})):K},G0=v.feedbackItems.filter(O=>O.status==="pending");await p(v.id,"info",`Evaluating ${G0.length} pending feedback item(s)`,{phase:"evaluate.comments"});let oa=new Map;for(let O of G0){if(await p(v.id,"info",`Inspecting feedback from ${O.author}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,file:O.file,line:O.line}}),gY(O.body)){oa.set(O.id,Ni(O,!1,"oh-my-pr-authored agent command comment; no code change required")),await p(v.id,"info",`Ignored self-authored agent command comment ${O.id}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,decision:"reject"}});continue}if(oY(O,v.feedbackItems)){oa.set(O.id,Ni(O,!1,"Automation audit trail follow-up; no code change required")),await p(v.id,"info",`Ignored audit-trail follow-up comment ${O.id}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,decision:"reject"}});continue}let J=QQ({pr:v,item:O});await p(v.id,"info",`Evaluating feedback ${O.id} with ${L}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,agent:L,prompt:J}});let H=await C({cwd:process.cwd(),prompt:J,phase:"evaluate.comments"}),me=Ni(O,H.needsFix,H.reason);if(oa.set(O.id,me),H.needsFix){await p(v.id,"info",`Accepted feedback ${O.id}: ${H.reason}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,decision:"accept"}});try{await this.github.addReactionToComment(_,D,O,"eyes")}catch(K){await d(v.id,"github.reaction",`Failed to add reaction for ${O.id}: ${St(K)}`,{feedbackId:O.id})}if(Ir)try{let K=await this.github.postStatusReplyForFeedbackItem(_,D,O,bY(na.accepted,le));K&&(mt.set(O.id,K),await it(O.id,K))}catch(K){await d(v.id,"github.status",`Failed to post status reply for ${O.id}: ${St(K)}`,{feedbackId:O.id})}}else await p(v.id,"info",`Rejected feedback ${O.id}: ${H.reason}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,decision:"reject"}})}let Dn=[];if(A.autoHealCI&&G)await p(v.id,"info",`Skipping legacy status-task evaluation because CI healing session ${G.id} is active`,{phase:"evaluate.status",metadata:{healingSessionId:G.id,healingState:G.state}});else{await p(v.id,"info",`Evaluating ${U.length} failing status check(s)`,{phase:"evaluate.status"});for(let O of U){let J=YQ({pr:v,context:O.context,description:O.description,targetUrl:O.targetUrl});await p(v.id,"info",`Evaluating failing status ${O.context} with ${L}`,{phase:"evaluate.status",metadata:{context:O.context,agent:L,prompt:J}});let H=await C({cwd:process.cwd(),prompt:J,phase:"evaluate.status"});H.needsFix?(Dn.push(O),await p(v.id,"info",`Accepted failing status ${O.context}: ${H.reason}`,{phase:"evaluate.status",metadata:{context:O.context,decision:"accept"}})):await p(v.id,"info",`Rejected failing status ${O.context}: ${H.reason}`,{phase:"evaluate.status",metadata:{context:O.context,decision:"reject"}})}}if(oa.size>0){let O=v.feedbackItems.map(me=>oa.get(me.id)??me),J=Fi(O),H=await this.storage.updatePR(v.id,{feedbackItems:O,accepted:J.accepted,rejected:J.rejected,flagged:J.flagged});H&&(v=H)}let mC=v.feedbackItems.filter(O=>O.status==="queued"&&O.decision==="accept"),B0=T?v.feedbackItems.filter(O=>(O.status==="queued"||O.status==="in_progress")&&O.decision==="accept"):[],Jt=B0.length>0?B0:mC;h=pY(v);let H0=E.mergeable===!1,pr=H0&&A.autoResolveMergeConflicts;H0&&!A.autoResolveMergeConflicts&&await p(v.id,"warn",`PR #${v.number} has merge conflicts but auto-resolve is disabled in settings`,{phase:"conflict",metadata:{baseRef:E.baseRef,mergeable:E.mergeable}});let Bi=!!(T&&!F),ap=!!(T&&F),op=!ap&&(Jt.length>0||Dn.length>0||Bi),ua=AP(v,E.headSha),Nn=!ap&&!Bi&&eY(v,E.headSha,A.autoUpdateDocs),Bo=A.autoUpdateDocs&&ua?.status==="needed"?ua.summary:null,Xt=!!Bo,$0=op||pr||Nn||Xt,Ho=null,z0=!!(A.autoHealCI&&G&&G.state==="awaiting_repair_slot"&&!ap&&!op&&!pr&&!Nn&&!Xt);if(z0&&G){let O=oe[0]?.fingerprint??G.latestFingerprint??void 0,J=await Ie.canRetry(G.id,O);J.canRetry||(Ho=J.reason??"retry budget rejected the healing attempt",G=await Ie.markEscalated(G.id,Ho,{currentHeadSha:E.headSha,latestFingerprint:O??G.latestFingerprint}),await p(v.id,"warn",`CI healing retry skipped: ${Ho}`,{phase:"healing.retry",metadata:{healingSessionId:G.id,fingerprint:O??null,sessionAttempts:J.sessionAttempts,fingerprintAttempts:J.fingerprintAttempts,maxSessionAttempts:J.maxSessionAttempts,maxFingerprintAttempts:J.maxFingerprintAttempts}}))}let W0=!!(z0&&G?.state==="awaiting_repair_slot"&&!Ho);if(A.autoUpdateDocs&&ua&&!Nn&&await p(v.id,"info",`Documentation assessment already recorded for ${E.headSha.slice(0,7)} (${ua.status})`,{phase:"evaluate.docs",metadata:{headSha:E.headSha,status:ua.status}}),!$0&&!W0&&h.length===0&&!pr&&Ee.length===0){await p(v.id,"info",`Babysitter checked PR #${v.number}; no necessary fixes identified`,{phase:"run"}),await this.storage.updatePR(v.id,{status:"watching",lastChecked:new Date().toISOString()}),await l({status:"completed",phase:"run.completed",lastError:null});return}let Le=E.headSha;I=!1;let $o=null,up=new Map,Kt=null,cp=!1,ca=null,Pe=null;if(pr&&await p(v.id,"info",`PR #${v.number} has merge conflicts with base branch ${E.baseRef}`,{phase:"conflict",metadata:{baseRef:E.baseRef,mergeable:E.mergeable}}),$0||pr){await p(v.id,"info",`Babysitter preparing fix run with ${Jt.length} comment task(s), ${Dn.length} status task(s), ${Xt?1:0} documentation task(s), and ${h.length} GitHub follow-up task(s)${Nn?", with documentation assessment":""}${pr?", plus merge conflict resolution":""}${Bi?", with forced prompt replay":""} using ${L}`,{phase:"run",metadata:{commentTasks:Jt.length,statusTasks:Dn.length,docsTasks:Xt?1:0,docsAssessmentNeeded:Nn,followUpTasks:h.length,hasConflicts:pr,shouldRunForcedReplay:Bi,agent:L}});let O=Ct();await p(v.id,"info",`Preparing worktree in ${O.rootDir}`,{phase:"worktree"});let{repoCacheDir:J,worktreePath:H,healed:me,remoteName:K}=await Vl({rootDir:O.rootDir,repoFullName:E.repoFullName,repoCloneUrl:E.repoCloneUrl,headRepoFullName:E.headRepoFullName,headRepoCloneUrl:E.headRepoCloneUrl,headRef:E.headRef,prNumber:v.number,runId:s,runCommand:this.runtime.runCommand});$o=K;try{await p(v.id,"info",`Worktree ready at ${H}`,{phase:"worktree",metadata:{remoteName:K,healed:me}}),me&&await p(v.id,"info","Repo cache required auto-heal before the worktree was created",{phase:"worktree",metadata:{repoCacheDir:J}}),await p(v.id,"info",`Prepared PR head from remote ${K}`,{phase:"worktree",metadata:{remoteName:K,headRef:E.headRef}}),await p(v.id,"info","Ensuring git identity",{phase:"git.identity"}),await xY(H,this.runtime.runCommand),await p(v.id,"info","Git identity ready",{phase:"git.identity"});let Te=await(this.runtime.checkDependencyPreflight??IP)({cwd:H,pr:v,pullSummary:E,requiresVerification:op||pr||Nn||Xt,runCommand:this.runtime.runCommand});if(!Te.ok)throw await p(v.id,"error",`Dependency preflight failed: ${Te.reason}`,{phase:"preflight.dependencies",metadata:{headSha:E.headSha,reason:Te.reason}}),new Error(`Dependency preflight failed: ${Te.reason}`);if(await p(v.id,"info","Dependency preflight passed",{phase:"preflight.dependencies"}),Nn){await p(v.id,"info","Documentation assessment started",{phase:"evaluate.docs",metadata:{headSha:E.headSha}});try{let ze=await f({currentPrId:v.id,command:"git",args:["fetch","origin",E.baseRef],cwd:H,timeoutMs:12e4,phase:"evaluate.docs",successMessage:`Fetched origin/${E.baseRef} for docs assessment`});if(ze.code!==0)throw new Error(`Failed to fetch origin/${E.baseRef} for docs assessment: ${qi(ze)}`);let Ue=await f({currentPrId:v.id,command:"git",args:["diff","--name-only",`origin/${E.baseRef}...HEAD`],cwd:H,timeoutMs:1e4,phase:"evaluate.docs",successMessage:"Collected changed files for docs assessment"});if(Ue.code!==0)throw new Error(`Failed to collect changed files for docs assessment: ${qi(Ue)}`);let Ge=await f({currentPrId:v.id,command:"git",args:["diff","--stat",`origin/${E.baseRef}...HEAD`],cwd:H,timeoutMs:1e4,phase:"evaluate.docs",successMessage:"Collected diff stat for docs assessment"});if(Ge.code!==0)throw new Error(`Failed to collect diff stat for docs assessment: ${qi(Ge)}`);let st=await f({currentPrId:v.id,command:"git",args:["diff","--no-color","--unified=0",`origin/${E.baseRef}...HEAD`],cwd:H,timeoutMs:1e4,phase:"evaluate.docs",successMessage:"Collected diff preview for docs assessment",maxOutputLogLines:20});if(st.code!==0)throw new Error(`Failed to collect diff preview for docs assessment: ${qi(st)}`);let at=ZQ({pr:v,pullSummary:E,changedFiles:Ue.stdout.trim(),diffStat:Ge.stdout.trim(),diffPreview:st.stdout.trim()});await p(v.id,"info",`Evaluating documentation needs with ${L}`,{phase:"evaluate.docs",metadata:{agent:L,prompt:at}});let gt=await C({cwd:H,prompt:at,phase:"evaluate.docs"}),kt={headSha:E.headSha,status:gt.needsFix?"needed":"not_needed",summary:gt.reason,assessedAt:new Date().toISOString()},Rt=await this.storage.updatePR(v.id,{docsAssessment:kt});Rt&&(v=Rt),Xt=gt.needsFix,Bo=gt.needsFix?gt.reason:null,await p(v.id,"info",gt.needsFix?`Documentation updates required: ${gt.reason}`:`Documentation updates not required: ${gt.reason}`,{phase:"evaluate.docs",metadata:{decision:gt.needsFix?"needed":"not_needed",headSha:E.headSha}})}catch(ze){let Ue=St(ze),Ge={headSha:E.headSha,status:"failed",summary:Ue,assessedAt:new Date().toISOString()},st=await this.storage.updatePR(v.id,{docsAssessment:Ge});st&&(v=st),Xt=!1,Bo=null,await p(v.id,"warn",`Documentation assessment failed: ${Ue}`,{phase:"evaluate.docs",metadata:{headSha:E.headSha}})}}if(pr){await p(v.id,"info",`Fetching base branch origin/${E.baseRef} for merge`,{phase:"conflict"});let ze=await f({currentPrId:v.id,command:"git",args:["fetch","origin",E.baseRef],cwd:H,timeoutMs:12e4,phase:"conflict",successMessage:`Fetched origin/${E.baseRef}`});if(ze.code!==0)throw new Error(`Failed to fetch base branch origin/${E.baseRef}: ${qi(ze)}`);await p(v.id,"info",`Attempting merge of origin/${E.baseRef} into ${E.headRef}`,{phase:"conflict"});let Ue=await this.runtime.runCommand("git",["merge","FETCH_HEAD","--no-edit"],{cwd:H,timeoutMs:6e4});if(Ue.code!==0){await p(v.id,"info","Merge produced conflicts; invoking agent to resolve them",{phase:"conflict"});let st=(await this.runtime.runCommand("git",["diff","--name-only","--diff-filter=U"],{cwd:H,timeoutMs:1e4})).stdout.trim().split(`
|
|
1071
|
-
`).filter(pp=>pp.trim().length>0);if(st.length===0)throw new Error(`Merge failed but no conflict files detected: ${Ue.stderr||Ue.stdout}`);await p(v.id,"info",`Found ${st.length} file(s) with merge conflicts`,{phase:"conflict",metadata:{conflictFiles:st}});let at=m(v.id,"conflict.agent","stdout","info"),gt=m(v.id,"conflict.agent","stderr","warn"),kt=await this.github.resolveGitHubAuthToken(A),Rt=kt?{...process.env,GITHUB_TOKEN:kt,GH_TOKEN:kt}:void 0,Fn=tY({pr:v,pullSummary:E,remoteName:K,conflictFiles:st});await p(v.id,"info",`Launching ${L} to resolve merge conflicts`,{phase:"conflict.agent",metadata:{agent:L,prompt:Fn}}),await aa(L,Fn);let Mn=await U0({cwd:H,prompt:Fn,env:Rt,onStdoutChunk:at.onChunk,onStderrChunk:gt.onChunk,phase:"conflict.agent"});if(await at.flush(),await gt.flush(),Mn.code!==0){let pp=_P(Mn.stderr||Mn.stdout);throw new Error(`Agent failed to resolve merge conflicts (${Mn.code}): ${pp}`)}await p(v.id,"info","Agent completed merge conflict resolution",{phase:"conflict.agent",metadata:{code:Mn.code}});let Wo=await this.runtime.runCommand("git",["diff","--name-only","--diff-filter=U"],{cwd:H,timeoutMs:5e3});if(Wo.code!==0)throw new Error(Mi("checking unresolved merge conflicts",Wo));if(Wo.stdout.trim())throw new Error(`Agent left unresolved merge conflicts: ${Wo.stdout.trim()}`);await g({currentPrId:v.id,cwd:H,commitArgs:["commit","--no-verify","--no-edit"],phase:"conflict",context:"merge conflict resolution"}),await p(v.id,"info","Merge conflicts resolved and committed by babysitter",{phase:"conflict"})}else await p(v.id,"info","Merge completed without conflicts (GitHub mergeability may have been stale)",{phase:"conflict"})}if(Jt.length>0){let ze=new Set(Jt.map(at=>at.id)),Ue=v.feedbackItems.map(at=>ze.has(at.id)?dP(at):at),Ge=Fi(Ue),st=await this.storage.updatePR(v.id,{feedbackItems:Ue,accepted:Ge.accepted,rejected:Ge.rejected,flagged:Ge.flagged});st&&(v=st)}if(Bi||Jt.length>0||Dn.length>0||Xt){let ze=m(v.id,"agent","stdout","info"),Ue=m(v.id,"agent","stderr","warn"),Ge=await this.github.resolveGitHubAuthToken(A),st=Ge?{...process.env,GITHUB_TOKEN:Ge,GH_TOKEN:Ge}:void 0,at=Bi&&T?T:rY({pr:v,pullSummary:E,remoteName:K,commentTasks:Jt,statusTasks:Dn,docsTaskSummary:Bo});await l({phase:"run.prompt-prepared",prompt:at,initialHeadSha:S||E.headSha}),await p(v.id,"info",`Launching ${L} in autonomous mode`,{phase:"agent",metadata:{githubAuth:!!Ge,prompt:at}}),await l({phase:"run.agent-running"}),await aa(L,at);let gt=na.agentRunning(L);await Promise.all(Jt.map(Rt=>Zr(Rt.id,gt)));let kt=await U0({cwd:H,prompt:at,env:st,onStdoutChunk:ze.onChunk,onStderrChunk:Ue.onChunk,phase:"agent",onFallback:async Rt=>{let Fn=na.agentRunning(Rt);await Promise.all(Jt.map(Mn=>Zr(Mn.id,Fn)))}});if(await ze.flush(),await Ue.flush(),kt.code!==0){let Rt=_P(kt.stderr||kt.stdout);throw await Promise.all(Jt.map(Fn=>Zr(Fn.id,na.agentFailed(L,Rt)))),new Error(`${L} apply failed (${kt.code}): ${Rt}`)}await Promise.all(Jt.map(Rt=>Zr(Rt.id,na.agentCompleted))),up=sY(kt.stdout),Kt=aY(kt.stdout),await p(v.id,"info",`${L} completed successfully`,{phase:"agent",metadata:{code:kt.code,extractedSummaries:up.size,docsTaskOutcome:Kt?.outcome??null}}),await l({phase:"run.agent-finished"})}await g({currentPrId:v.id,cwd:H,commitArgs:["commit","--no-verify","-m",`Apply babysitter fixes for PR #${v.number}`],phase:"verify.git.status",context:"agent run"}),await p(v.id,"info","Worktree is clean after babysitter finalization",{phase:"verify.git.status"});let je=await f({currentPrId:v.id,command:"git",args:["rev-parse","HEAD"],cwd:H,timeoutMs:5e3,phase:"verify.git.local-head",successMessage:"Collected worktree HEAD"});if(je.code!==0)throw new Error(`git rev-parse HEAD failed: ${je.stderr||je.stdout}`);let Qt=await f({currentPrId:v.id,command:"git",args:["-C",J,"fetch",K,E.headRef],timeoutMs:12e4,phase:"verify.git.fetch-head",successMessage:`Fetched ${K}/${E.headRef} for verification`});if(Qt.code!==0)throw new Error(`git fetch ${K} ${E.headRef} failed: ${Qt.stderr||Qt.stdout}`);let zo=await f({currentPrId:v.id,command:"git",args:["-C",J,"rev-parse","FETCH_HEAD"],timeoutMs:5e3,phase:"verify.git.remote-head",successMessage:"Collected remote PR head SHA"});if(zo.code!==0)throw new Error(`git rev-parse FETCH_HEAD failed: ${zo.stderr||zo.stdout}`);let la=je.stdout.trim(),pa=zo.stdout.trim(),lp=la!==E.headSha;if(lp&&pa!==la){let ze=await f({currentPrId:v.id,command:"git",args:["push",K,`HEAD:${E.headRef}`],cwd:H,timeoutMs:12e4,phase:"verify.git.push",successMessage:`Pushed babysitter commit to ${K}/${E.headRef}`});if(ze.code!==0)throw new Error(Mi(`pushing ${K}/${E.headRef}`,ze));let Ue=await f({currentPrId:v.id,command:"git",args:["-C",J,"fetch",K,E.headRef],timeoutMs:12e4,phase:"verify.git.fetch-head",successMessage:`Fetched ${K}/${E.headRef} after babysitter push`});if(Ue.code!==0)throw new Error(Mi(`fetching ${K}/${E.headRef} after push`,Ue));let Ge=await f({currentPrId:v.id,command:"git",args:["-C",J,"rev-parse","FETCH_HEAD"],timeoutMs:5e3,phase:"verify.git.remote-head",successMessage:"Collected remote PR head SHA after babysitter push"});if(Ge.code!==0)throw new Error(Mi("reading remote PR head after push",Ge));pa=Ge.stdout.trim()}if(lp&&pa!==la)throw new Error("Babysitter created a local commit but could not verify it on the PR head branch");if(I=pa!==E.headSha,Dn.length>0&&!I)throw new Error("Agent did not update the PR head branch for accepted failing status tasks");if(Xt&&!Kt)throw new Error("Agent did not report documentation task outcome");if(Xt&&!I&&Kt?.outcome!=="no_change")throw new Error("Agent did not update the PR head branch for required documentation tasks");if(pr&&!I)throw new Error("Conflict resolution was not pushed to the PR head branch");if(Xt&&Kt?.outcome==="no_change"){let ze=await this.storage.updatePR(v.id,{docsAssessment:{headSha:E.headSha,status:"not_needed",summary:Kt.summary,assessedAt:new Date().toISOString()}});ze&&(v=ze)}Le=la,await p(v.id,"info","Verified git branch state after agent run",{phase:"verify.git",metadata:{initialHeadSha:E.headSha,localHeadSha:la,remoteHeadSha:pa,branchMoved:I,localCommitCreated:lp,remoteName:K,docsTaskOutcome:Kt?.outcome??null}}),Kt&&await p(v.id,"info",`Documentation task outcome: ${Kt.outcome} - ${Kt.summary}`,{phase:"verify.docs",metadata:{outcome:Kt.outcome,branchMoved:I}})}finally{try{await p(v.id,"info","Cleaning up worktree",{phase:"cleanup"}),await Jl({repoCacheDir:J,worktreePath:H,runCommand:this.runtime.runCommand}),await p(v.id,"info","Worktree cleanup complete",{phase:"cleanup"})}catch(Te){let je=Te instanceof Error?Te.message:String(Te);await p(v.id,"error",`Worktree cleanup failed: ${je}`,{phase:"cleanup"})}}}else await p(v.id,"info",`Babysitter found ${h.length} accepted feedback item(s) awaiting GitHub follow-up`,{phase:"run",metadata:{followUpTasks:h.length,agent:L}});if(W0&&G){let O=oe.map(K=>K.fingerprint);await p(v.id,"info",`Launching dedicated CI healing attempt for ${O.length} fingerprint(s)`,{phase:"healing.run",metadata:{healingSessionId:G.id,targetFingerprints:O}}),G=await Ie.markRepairing(G.id,{currentHeadSha:E.headSha,latestFingerprint:O[0]??G.latestFingerprint});let J=await this.github.resolveGitHubAuthToken(A),H=J?{...process.env,GITHUB_TOKEN:J,GH_TOKEN:J}:void 0;if(Pe=await this.runtime.runCIHealingRepairAttempt?.({prNumber:v.number,repoFullName:E.repoFullName,repoCloneUrl:E.repoCloneUrl,headRepoFullName:E.headRepoFullName,headRepoCloneUrl:E.headRepoCloneUrl,headRef:E.headRef,baseRef:E.baseRef,headSha:E.headSha,title:E.title,url:E.url,author:E.author,branch:v.branch,agent:L,failures:oe,runId:`${s}-ci-healing`,rootDir:Ct().rootDir,env:H})??null,!Pe)throw new Error("CI healing runtime is unavailable");ca=(await this.storage.createHealingAttempt({sessionId:G.id,attemptNumber:G.attemptCount,inputSha:E.headSha,outputSha:Pe.accepted?Pe.verification.remoteHeadSha:null,status:Pe.accepted?"awaiting_ci":"failed",endedAt:Pe.accepted?null:new Date().toISOString(),agent:L,promptDigest:Pe.promptDigest,targetFingerprints:Pe.targetFingerprints,summary:Pe.summary,improvementScore:null,error:Pe.rejectionReason})).id,cp=!0,Pe.accepted?(G=await Ie.markAwaitingCi(G.id,{currentHeadSha:Pe.verification.remoteHeadSha,latestFingerprint:Pe.targetFingerprints[0]??G.latestFingerprint}),I=Pe.verification.pushedNewSha,Le=Pe.verification.remoteHeadSha,$o=Pe.remoteName):G=await Ie.markEscalated(G.id,Pe.rejectionReason??"CI healing attempt failed",{currentHeadSha:E.headSha,latestFingerprint:Pe.targetFingerprints[0]??G.latestFingerprint})}await l({phase:"run.reconcile"});for(let O of h){let J=!D0(O,v.feedbackItems),H=Uo(Ql(O));if(J){await p(v.id,"info",`Posting GitHub follow-up for ${O.id}${H?" and resolving conversation":""}`,{phase:"github.followup",metadata:{feedbackId:O.id,replyKind:O.replyKind,resolve:H}});let me=fY(Le,O,le,up.get(O.auditToken));await this.github.postFollowUpForFeedbackItem(_,D,O,me,{resolve:H})}else if(H){if(!O.threadId){await p(v.id,"warn",`Cannot resolve review thread for ${O.id}: thread ID unavailable (skipping)`,{phase:"github.followup",metadata:{feedbackId:O.id}});continue}await this.github.resolveReviewThread(_,D,O.threadId)}await p(v.id,"info",`GitHub follow-up complete for ${O.id}`,{phase:"github.followup",metadata:{feedbackId:O.id,replyKind:O.replyKind,posted:J,resolved:H}}),await Zr(O.id,na.resolved(Le))}v=await this.syncFeedbackForPR(v.id,{runId:s,logStart:!0,phase:"verify.sync"});let V0=cY({pr:v,followUpTasks:h,runStartedAtMs:a});if(V0.length>0)throw new Me(`GitHub audit trail verification failed: ${V0.join("; ")}`,502);if(await p(v.id,"info","GitHub audit trail verified",{phase:"verify.github",metadata:{verifiedComments:h.length,remoteName:$o,branchMoved:I}}),h.length>0){let O=new Set(h.map(K=>K.id)),J=v.feedbackItems.map(K=>O.has(K.id)?Ql(K):K),H=Fi(J),me=await this.storage.updatePR(v.id,{feedbackItems:J,accepted:H.accepted,rejected:H.rejected,flagged:H.flagged});me&&(v=me)}if(I&&Le){await p(v.id,"info","Waiting for CI/CD checks on new commit...",{phase:"verify.ci",metadata:{headSha:Le}});let O=await this.pollForCICompletion(_,w,D,Le,v.id,p);if(O.status==="failure"){let J=O.failures.map(H=>`${H.context}: ${H.description}`).join("; ");await p(v.id,"warn",`CI/CD still failing after agent fix: ${J}`,{phase:"verify.ci",metadata:{failures:O.failures}});try{let H=[`## \u26A0\uFE0F ${PP(le)} CI Alert`,"",`The babysitter pushed changes (commit \`${Le.slice(0,7)}\`), but CI/CD checks are still failing:`,"",...O.failures.map(me=>`- **${me.context}**: ${me.description}${me.targetUrl?` ([details](${me.targetUrl}))`:""}`),"","Manual investigation may be required.",...le?["",In]:[]].join(`
|
|
1070
|
+
${In}`:In}function Yl(t,e){return[t,...e].join(" ")}function qi(t){return t.stderr.trim()||t.stdout.trim()||"no output"}function yY(t){return/\b(Could not resolve host|ENOTFOUND|EAI_AGAIN|ECONNRESET|network error|Failed to connect|Connection timed out)\b/i.test(t)}function Mi(t,e){let r=qi(e);return yY(r)?`Infrastructure Git failure while ${t}: ${r}`:`${t} failed: ${r}`}function St(t){return t instanceof Error?t.message:String(t)}function vY(t){return t==="claude"?"codex":"claude"}function _P(t){let n=(t.replace(/^(?:claude|codex|agent) apply failed \(\d+\):\s*/i,"").replace(/^Agent failed to resolve merge conflicts \(\d+\):\s*/i,"").replace(/^Error:\s*/i,"").split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)??"No failure details were reported").replace(/\s+/g," "),i=n.length>180?`${n.slice(0,177).trimEnd()}...`:n;return/[.!?]$/.test(i)?i:`${i}.`}function wY(t,e){let n=`${t}${e}`.split(/\r?\n/);return{lines:n.slice(0,-1),buffer:n.at(-1)??""}}async function xY(t,e){let r=await e("git",["config","--get","user.name"],{cwd:t,timeoutMs:3e3});(r.code!==0||!r.stdout.trim())&&await e("git",["config","user.name",GQ],{cwd:t,timeoutMs:3e3});let n=await e("git",["config","--get","user.email"],{cwd:t,timeoutMs:3e3});(n.code!==0||!n.stdout.trim())&&await e("git",["config","user.email",BQ],{cwd:t,timeoutMs:3e3})}async function ia(t){try{return await(0,SP.access)(t),!0}catch(e){if(e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR"))return!1;throw e}}async function IP(t){if(!t.requiresVerification)return{ok:!0};let e=ji.default.join(t.cwd,"package.json");if(!await ia(e))return{ok:!0};let r={packageLock:await ia(ji.default.join(t.cwd,"package-lock.json")),npmShrinkwrap:await ia(ji.default.join(t.cwd,"npm-shrinkwrap.json")),pnpmLock:await ia(ji.default.join(t.cwd,"pnpm-lock.yaml")),yarnLock:await ia(ji.default.join(t.cwd,"yarn.lock"))};if(!r.packageLock&&!r.npmShrinkwrap&&!r.pnpmLock&&!r.yarnLock)return{ok:!0};if(!await ia(ji.default.join(t.cwd,"node_modules"))){if((await t.runCommand("git",["check-ignore","-q","node_modules/"],{cwd:t.cwd,timeoutMs:5e3})).code!==0)return{ok:!1,reason:"Node dependency cache is missing, but node_modules is not ignored by git; refusing to install dependencies automatically"};let i=r.pnpmLock?{command:"pnpm",args:["install","--frozen-lockfile"]}:r.yarnLock?{command:"yarn",args:["install","--frozen-lockfile"]}:{command:"npm",args:["ci"]},s=await t.runCommand(i.command,i.args,{cwd:t.cwd,timeoutMs:3e5});if(s.code!==0)return{ok:!1,reason:pn(s,`Dependency install failed while running ${i.command} ${i.args.join(" ")}`)}}return{ok:!0}}function EP(t){return new Promise(e=>setTimeout(e,t))}var Zl=class{storage;inProgress=new Set;feedbackMutationLocks=new Map;github;runtime;releaseManager;deploymentHealingManager;scheduleBackgroundJob;clock;agentHealthCache=new Map;constructor(e,r=WQ,n=VQ,i,s,a){this.storage=e,this.github=r,this.runtime=n,this.releaseManager=i,this.deploymentHealingManager=a,this.scheduleBackgroundJob=s,this.clock=n.now??(()=>new Date)}now(){return this.clock()}async readAgentHealth(e){let r=this.now().getTime(),n=this.agentHealthCache.get(e);if(n&&r-n.checkedAtMs<HQ)return n.result;let i=this.runtime.checkAgentHealth?await this.runtime.checkAgentHealth(e):{ok:!0};return this.agentHealthCache.set(e,{checkedAtMs:r,result:i}),i}async pauseAutomationForAgentFailure(e,r,n){let i=`Agent health check failed for ${e}: ${r}`;await this.storage.updateRuntimeState({drainMode:!0,drainRequestedAt:this.now().toISOString(),drainReason:i}),await Promise.all(n.map(async s=>{let a=await this.storage.getPR(s);if(a){let o=a.feedbackItems.map(u=>u.decision==="accept"&&(u.status==="queued"||u.status==="in_progress")?I0(u,i):u);if(o.some((u,c)=>u!==a.feedbackItems[c])){let u=Fi(o);await this.storage.updatePR(a.id,{feedbackItems:o,accepted:u.accepted,rejected:u.rejected,flagged:u.flagged})}}await this.storage.addLog(s,"error",`Automation paused: ${i}`,{phase:"agent.health"})}))}async ensureAgentHealthy(e,r){let n=await this.readAgentHealth(e);if(!n.ok)throw await this.pauseAutomationForAgentFailure(e,n.reason,r),new Error(`Agent health check failed for ${e}: ${n.reason}`)}async supersedeActiveHealingSessionsForArchivedPr(e){let r=await this.storage.listHealingSessions({prId:e}),n=this.now().toISOString();for(let i of r)ea(i.state)||await this.storage.updateHealingSession(i.id,{state:"superseded",endedAt:n,escalationReason:"PR archived on GitHub"})}getActiveRunCount(){return this.inProgress.size}async waitForIdle(e=12e4){let r=Date.now();for(;this.inProgress.size>0;){if(Date.now()-r>=e)return!1;await EP(100)}return!0}async runQueuedBabysitPR(e,r){let n=(await this.storage.listAgentRuns({status:"running",prId:e})).slice().sort((s,a)=>Date.parse(a.updatedAt)-Date.parse(s.updatedAt))[0];if(!n){await this.babysitPR(e,r,{allowDuringDrain:!0,rethrowOnFailure:!0});return}if(!!!(n.prompt&&n.resolvedAgent&&n.initialHeadSha)){let s=new Date().toISOString();await this.storage.upsertAgentRun({...n,status:"failed",phase:"run.failed",lastError:"Interrupted run missing replay context",updatedAt:s}),await this.babysitPR(e,r,{allowDuringDrain:!0,rethrowOnFailure:!0});return}await this.babysitPR(e,n.preferredAgent,{runId:n.id,recoveryMode:!0,forceAgentPrompt:n.prompt,forceResolvedAgent:n.resolvedAgent,replayInitialHeadSha:n.initialHeadSha,allowDuringDrain:!0,rethrowOnFailure:!0})}async resumeInterruptedRuns(){let e=await this.storage.listAgentRuns({status:"running"});if(e.length!==0){if(this.scheduleBackgroundJob){let r=new Set;for(let n of e)r.has(n.prId)||(r.add(n.prId),await this.scheduleBackgroundJob("babysit_pr",n.prId,Or("babysit_pr",n.prId),{preferredAgent:n.preferredAgent}));return}for(let r of e){if(!!!(r.prompt&&r.resolvedAgent&&r.initialHeadSha)){let i=new Date().toISOString();await this.storage.upsertAgentRun({...r,status:"failed",phase:"run.failed",lastError:"Interrupted run missing replay context",updatedAt:i}),await this.babysitPR(r.prId,r.preferredAgent,{allowDuringDrain:!0});continue}await this.babysitPR(r.prId,r.preferredAgent,{runId:r.id,recoveryMode:!0,forceAgentPrompt:r.prompt,forceResolvedAgent:r.resolvedAgent,replayInitialHeadSha:r.initialHeadSha,allowDuringDrain:!0})}}}async withFeedbackMutationLock(e,r){let n=this.feedbackMutationLocks.get(e)??Promise.resolve(),i,s=new Promise(o=>{i=()=>o()}),a=n.then(()=>s);this.feedbackMutationLocks.set(e,a),await n;try{return await r()}finally{i?.(),this.feedbackMutationLocks.get(e)===a&&this.feedbackMutationLocks.delete(e)}}async retryFeedbackItem(e,r){return this.withFeedbackMutationLock(e,async()=>{let n=await this.storage.getPR(e);if(!n)return{kind:"pr_not_found"};let i=n.feedbackItems.find(u=>u.id===r);if(!i)return{kind:"feedback_not_found"};if(i.status!=="failed"&&i.status!=="warning")return{kind:"feedback_not_retryable"};let s=n.feedbackItems.map(u=>u.id===r?mP(u):u),a=Fi(s),o=await this.storage.updatePR(n.id,{feedbackItems:s,accepted:a.accepted,rejected:a.rejected,flagged:a.flagged});if(!o)throw new Error(`Failed to queue retry for feedback item ${r} on PR ${e}`);return{kind:"ok",updated:o}})}async syncFeedbackForPR(e,r){let n=await this.storage.getPR(e);if(!n)throw new Error("PR not found");let i=dt(n.repo);if(!i)throw new Error(`Invalid repository slug: ${n.repo}`);let s={owner:i.owner,repo:i.repo,number:n.number},a=await this.storage.getConfig(),o=await this.github.buildOctokit(a),u=r?.phase??"sync";r?.logStart&&await this.storage.addLog(n.id,"info","Syncing GitHub comments/reviews...",{runId:r.runId??null,phase:u});let c=await this.github.fetchFeedbackItemsForPR(o,s,a),{merged:l,newCount:p}=JQ(n.feedbackItems,c),d=Fi(l),m=await this.storage.updatePR(n.id,{title:n.title,status:n.status,lastChecked:new Date().toISOString(),feedbackItems:l,accepted:d.accepted,rejected:d.rejected,flagged:d.flagged});if(!m)throw new Error("Failed to update PR after feedback sync");return await this.storage.addLog(n.id,"info",KQ(c.length,p),{runId:r?.runId??null,phase:u,metadata:{total:c.length,newCount:p}}),m}async syncAndBabysitTrackedRepos(){if((await this.storage.getRuntimeState()).drainMode)return;let r=[...await this.storage.getPRs(),...await this.storage.getArchivedPRs()].filter(XQ);for(let f of r)try{await this.syncFeedbackForPR(f.id,{phase:"repair"})}catch(g){await this.storage.addLog(f.id,"warn",`Could not repair missing GitHub review-thread metadata: ${St(g)}`,{phase:"repair"})}let n=await this.storage.getConfig(),i=await this.storage.getPRs(),s=new Set([...i.map(f=>f.repo),...n.watchedRepos]),a=n.codingAgent,o=i.filter(f=>f.watchEnabled!==!1&&f.status!=="archived").map(f=>f.id);if(s.size>0)try{await this.ensureAgentHealthy(a,o)}catch{return}let u=new Map((await this.storage.listRepoSettings()).map(f=>[f.repo,f])),c=await this.github.buildOctokit(n),l=Array.from(s).some(f=>u.get(f)?.ownPrsOnly??!0),p=null,d=async()=>l?(p||(p=(this.github.getAuthenticatedLogin?.(c)??Promise.resolve(null)).catch(f=>(Go.warn({err:f instanceof Error?f.message:String(f)},"Failed to determine authenticated GitHub login for watcher filtering"),null))),p):null,m=Array.from(s).map(f=>dt(f)).filter(f=>!!f);for(let f of m){let g=Pn(f),h;try{h=await this.github.listOpenPullsForRepo(c,f)}catch(I){Go.warn({err:I instanceof Error?I.message:String(I),repo:g},"Failed to list open PRs");continue}let T=new Set(h.map(I=>I.number)),R=u.get(g)?.ownPrsOnly??!0,S=R?await d():null,P=new Set(h.filter(I=>!R||S!==null&&I.author.trim().toLowerCase()===S).map(I=>I.number)),F=i.filter(I=>I.repo===g);for(let I of F)if(!T.has(I.number)&&I.status!=="archived"){let A;if(this.github.fetchPullCloseState)try{A=await this.github.fetchPullCloseState(c,{owner:f.owner,repo:f.repo,number:I.number})}catch(v){await this.storage.addLog(I.id,"warn",`Could not confirm merge state before archival: ${St(v)}`,{phase:"watcher"})}await this.storage.updatePR(I.id,{status:"archived"}),await this.supersedeActiveHealingSessionsForArchivedPr(I.id),await this.storage.addLog(I.id,"info",`PR #${I.number} is no longer open on GitHub \u2014 archived`,{phase:"watcher"});let j=u.get(g)?.autoCreateReleases??!1;if(A?.merged&&this.releaseManager&&n.autoCreateReleases)if(!j)await this.storage.addLog(I.id,"info",`PR #${I.number} was merged, but auto-release is disabled for ${g}`,{phase:"watcher"});else{let v=A.baseRef.trim(),L=A.mergeCommitSha||A.headSha,w=A.mergedAt||A.closedAt;if(!v||!L||!w){let k=[v?null:"a base branch",L?null:"a commit SHA",w?null:"a merge timestamp"].filter(x=>!!x);await this.storage.addLog(I.id,"warn",`PR #${I.number} was merged, but release evaluation was not queued because GitHub did not return ${k.join(" and ")}.`,{phase:"watcher",metadata:{baseBranch:v,headSha:A.headSha,mergeCommitSha:A.mergeCommitSha,mergedAt:A.mergedAt,closedAt:A.closedAt}})}else try{await this.releaseManager.enqueueMergedPullReleaseEvaluation({repo:g,baseBranch:v,triggerPrNumber:A.number,triggerPrTitle:A.title,triggerPrUrl:A.url,triggerMergeSha:L,triggerMergedAt:w}),await this.storage.addLog(I.id,"info",`PR #${I.number} was merged \u2014 queued release evaluation`,{phase:"watcher",metadata:{baseBranch:v,triggerMergeSha:L}})}catch(k){await this.storage.addLog(I.id,"warn",`PR #${I.number} was merged, but release evaluation could not be queued: ${St(k)}`,{phase:"watcher"})}}else A&&!A.merged&&await this.storage.addLog(I.id,"info",`PR #${I.number} closed without merge`,{phase:"watcher"});if(A?.merged&&this.deploymentHealingManager&&this.scheduleBackgroundJob&&n.autoHealDeployments){let v=A.baseRef.trim(),L=A.mergeCommitSha||A.headSha;if(v&&L)try{let w=await this.github.resolveGitHubAuthToken(n),k=ql(g,w),{repoCacheDir:x}=await Wl({repoFullName:g,repoCloneUrl:k,runCommand:this.runtime.runCommand}),C=await uP(x);C&&(await this.scheduleBackgroundJob("heal_deployment",`${g}:${L}`,Or("heal_deployment",`${g}:${L}`),{repo:g,platform:C.platform,mergeSha:L,triggerPrNumber:I.number,triggerPrTitle:I.title,triggerPrUrl:I.url,baseBranch:v,...On({label:`Healing ${C.platform} deployment`,detail:`${g} PR #${I.number} - ${I.title}`,targetUrl:I.url})}),await this.storage.addLog(I.id,"info",`PR #${I.number} merged \u2014 queued deployment healing (${C.platform})`,{phase:"watcher",metadata:{platform:C.platform,mergeSha:L}}))}catch(w){await this.storage.addLog(I.id,"warn",`Failed to queue deployment healing: ${St(w)}`,{phase:"watcher"})}}}for(let I of h){let A=await this.storage.getPRByRepoAndNumber(g,I.number);if(!A){if(!P.has(I.number))continue;A=await this.storage.addPR({number:I.number,title:I.title,repo:g,branch:I.branch,author:I.author,url:I.url,status:"watching",feedbackItems:[],accepted:0,rejected:0,flagged:0,testsPassed:null,lintPassed:null,lastChecked:null}),await this.storage.addLog(A.id,"info",`Auto-registered open PR #${I.number} from ${g}`)}P.has(I.number)&&A.watchEnabled&&(await this.storage.addLog(A.id,"info","Watcher queued autonomous babysitter run",{phase:"watcher",metadata:{repo:g}}),this.scheduleBackgroundJob?await this.scheduleBackgroundJob("babysit_pr",A.id,Or("babysit_pr",A.id),{preferredAgent:n.codingAgent,...On({label:`Babysitting PR #${A.number}`,detail:`${A.repo} - ${A.title}`,targetUrl:A.url})}):await this.babysitPR(A.id,n.codingAgent))}}}async pollForCICompletion(e,r,n,i,s,a){let u=this.runtime.ciPollIntervalMs??3e4;for(let c=1;c<=10;c++){await EP(u);try{let l=await this.github.checkCISettled(e,r,i),p=await this.github.listFailingStatuses(e,r,i);if(await a(s,"info",`CI poll attempt ${c}/10: ${p.length} failure(s), settled=${l}`,{phase:"verify.ci",metadata:{attempt:c,failures:p.length,settled:l}}),l)return p.length>0?{status:"failure",failures:p}:{status:"success",failures:[]}}catch(l){await a(s,"warn",`CI poll attempt ${c} failed: ${St(l)}`,{phase:"verify.ci",metadata:{attempt:c}})}}try{let c=await this.github.listFailingStatuses(e,r,i);if(c.length>0)return{status:"failure",failures:c}}catch(c){await a(s,"warn",`Final CI status check after timeout failed: ${St(c)}`,{phase:"verify.ci"})}return{status:"timeout",failures:[]}}async babysitPR(e,r,n){if((await this.storage.getRuntimeState()).drainMode&&!n?.allowDuringDrain){let A=await this.storage.getPR(e);A&&await this.storage.addLog(A.id,"warn","Babysitter run skipped because drain mode is enabled",{phase:"run"});return}if(this.inProgress.has(e)){let A=await this.storage.getPR(e);A&&await this.storage.addLog(A.id,"warn","Babysitter run skipped because another run is already in progress",{phase:"run"});return}this.inProgress.add(e);let s=n?.runId||(0,TP.randomUUID)(),a=Math.floor(Date.now()/1e3)*1e3-1e3,o=Promise.resolve(),u=new Date().toISOString(),c=await this.storage.getAgentRun(s)||{id:s,prId:e,preferredAgent:r,resolvedAgent:n?.forceResolvedAgent??null,status:"running",phase:"run.started",prompt:n?.forceAgentPrompt??null,initialHeadSha:n?.replayInitialHeadSha??null,metadata:{recoveryMode:!!n?.recoveryMode},lastError:null,createdAt:u,updatedAt:u};await this.storage.upsertAgentRun(c);let l=async A=>{c={...c,...A,updatedAt:new Date().toISOString()},await this.storage.upsertAgentRun(c)},p=(A,j,v,L)=>(o=o.then(async()=>{await this.storage.addLog(A,j,v,{runId:s,phase:L?.phase??null,metadata:L?.metadata??null})}).catch(w=>{Go.warn({err:w instanceof Error?w.message:String(w)},"Babysitter log write failed")}),o),d=async(A,j,v,L)=>{await p(A,"warn",v,{phase:j,metadata:L??null})},m=(A,j,v,L,w)=>{let k="",x=0,C=!1,_=D=>w!==void 0&&x>=w?C?o:(C=!0,p(A,L,`[${v}] output truncated after ${w} line(s)`,{phase:j,metadata:{stream:v,truncated:!0,maxLines:w}})):(x+=1,p(A,L,`[${v}] ${D}`,{phase:j,metadata:{stream:v}}));return{onChunk:D=>{let E=wY(k,D);k=E.buffer;for(let U of E.lines){let Z=U.trim();Z&&_(Z)}},flush:async()=>{let D=k.trim();if(k="",D){await _(D);return}await o}}},f=async A=>{let{currentPrId:j,command:v,args:L,cwd:w,timeoutMs:k,phase:x,successMessage:C,maxOutputLogLines:_}=A;await p(j,"info",`Running ${Yl(v,L)}`,{phase:x});let D=m(j,x,"stdout","info",_),E=m(j,x,"stderr","warn",_),U=await this.runtime.runCommand(v,L,{cwd:w,timeoutMs:k,onStdoutChunk:D.onChunk,onStderrChunk:E.onChunk});return await D.flush(),await E.flush(),U.code===0?await p(j,"info",C,{phase:x,metadata:{command:Yl(v,L),code:U.code}}):await p(j,"error",`${Yl(v,L)} failed (${U.code})`,{phase:x,metadata:{command:Yl(v,L),code:U.code,summary:qi(U)}}),U},g=async A=>{let j=await f({currentPrId:A.currentPrId,command:"git",args:["status","--porcelain"],cwd:A.cwd,timeoutMs:5e3,phase:A.phase,successMessage:"Collected worktree git status"});if(j.code!==0)throw new Error(Mi("checking worktree status",j));if(!j.stdout.trim())return await p(A.currentPrId,"info",`No worktree changes to commit after ${A.context}`,{phase:A.phase}),!1;let v=await f({currentPrId:A.currentPrId,command:"git",args:["add","-A"],cwd:A.cwd,timeoutMs:3e4,phase:A.phase,successMessage:"Staged worktree changes"});if(v.code!==0)throw new Error(Mi("staging worktree changes",v));let L=await f({currentPrId:A.currentPrId,command:"git",args:A.commitArgs,cwd:A.cwd,timeoutMs:6e4,phase:A.phase,successMessage:"Committed worktree changes"});if(L.code!==0)throw new Error(Mi("committing worktree changes",L));return!0},h=[],T=n?.forceAgentPrompt??null,R=n?.forceResolvedAgent??null,S=n?.replayInitialHeadSha??null,P=!!n?.recoveryMode,F=!1,I=!1;try{await l({status:"running",phase:"run.started",metadata:{...c.metadata??{},recoveryMode:P},lastError:null}),await this.storage.updatePR(e,{status:"processing",lastChecked:new Date().toISOString()}),await p(e,"info",`Babysitter run started using preferred agent ${r}${P?" (recovery)":""}`,{phase:"run",metadata:{preferredAgent:r,recoveryMode:P}});let A=await this.storage.getConfig(),j=R||r;await this.ensureAgentHealthy(j,[e]),await l({phase:"run.sync"});let v=await this.syncFeedbackForPR(e,{runId:s,logStart:!0,phase:"sync"}),L=R||await this.runtime.resolveAgent(r,{allowFallback:A.fallbackToNextCodingAgent});L!==j&&await this.ensureAgentHealthy(L,[v.id]),await l({resolvedAgent:L});let w=dt(v.repo);if(!w)throw new Error(`Invalid repository slug: ${v.repo}`);await p(v.id,"info",`Resolved coding agent to ${L}`,{phase:"run"});let k=!1;if(!R&&A.fallbackToNextCodingAgent&&L!==r){k=!0;let O=`Configured coding agent ${r} CLI is not installed`;await p(v.id,"warn",`Falling back from ${r} to ${L} because ${r} is not working: ${O}`,{phase:"run",metadata:{failedAgent:r,fallbackAgent:L}}),await l({metadata:{...c.metadata??{},fallbackFromAgent:r,fallbackReason:O}})}let x=async(O,J)=>{if(!A.fallbackToNextCodingAgent||R||k||!nE(O))return!1;let H=L,me=vY(H),K;try{K=await this.runtime.resolveAgent(me,{allowFallback:!1})}catch{return!1}k=!0,L=K;let Te=St(O);return await p(v.id,"warn",`Falling back from ${H} to ${L} because ${H} is not working: ${Te}`,{phase:J,metadata:{failedAgent:H,fallbackAgent:L}}),await l({resolvedAgent:L,metadata:{...c.metadata??{},fallbackFromAgent:H,fallbackReason:Te}}),!0},C=async O=>{try{return await this.runtime.evaluateFixNecessityWithAgent({agent:L,cwd:O.cwd,prompt:O.prompt})}catch(J){if(await x(J,O.phase))return this.runtime.evaluateFixNecessityWithAgent({agent:L,cwd:O.cwd,prompt:O.prompt});throw J}},_=await this.github.buildOctokit(A),D={owner:w.owner,repo:w.repo,number:v.number},E=await this.github.fetchPullSummary(_,D);T&&S&&E.headSha!==S&&(F=!0,await p(v.id,"warn",`Skipping forced prompt replay because PR head moved (${S.slice(0,7)} -> ${E.headSha.slice(0,7)})`,{phase:"run.replay",metadata:{replayInitialHeadSha:S,currentHeadSha:E.headSha}}));let U=await this.github.listFailingStatuses(_,w,E.headSha),Z=this.now().toISOString(),Ee=(this.github.fetchCheckSnapshotsForRef?await this.github.fetchCheckSnapshotsForRef(_,w,v.id,E.headSha):U.map(O=>({id:`${O.context}:${O.description}:${E.headSha}`,prId:v.id,sha:E.headSha,provider:"github.commit_status",context:O.context,status:"failure",conclusion:null,description:O.description,targetUrl:O.targetUrl,observedAt:Z}))).filter(O=>Sm(O)),fe=k0(Ee),oe=fe.filter(O=>O.classification==="healable_in_branch"),pe=fe.filter(O=>O.classification==="blocked_external"),Ie=new Bl(this.storage,()=>this.now()),G=null;if(Ee.length>0)G=await Ie.ensureSessionForHead({prId:v.id,repo:v.repo,prNumber:v.number,headSha:E.headSha}),await vP(this.storage,Ee),await wP(this.storage,G.id,E.headSha,fe),ea(G.state)?await p(v.id,"info",`CI healing session ${G.id} is already ${G.state}; skipping repair transition`,{phase:"healing.state",metadata:{healingSessionId:G.id,healingState:G.state,headSha:E.headSha}}):pe.length>0?G=await Ie.markBlocked(G.id,pe[0]?.summary??"CI failure classified as blocked_external",{latestFingerprint:pe[0]?.fingerprint??null,currentHeadSha:E.headSha}):oe.length>0?G=await Ie.markAwaitingRepairSlot(G.id,{latestFingerprint:oe[0]?.fingerprint??null,currentHeadSha:E.headSha}):G=await Ie.markEscalated(G.id,"CI failure could not be classified as healable in branch",{latestFingerprint:fe[0]?.fingerprint??null,currentHeadSha:E.headSha});else{let O=await Ie.getSessionByPrAndHead(v.id,E.headSha);O&&["triaging","awaiting_repair_slot","repairing","awaiting_ci","verifying","cooldown"].includes(O.state)?(G=await Ie.markVerifying(O.id,{currentHeadSha:E.headSha}),G=await Ie.markHealed(G.id,{currentHeadSha:E.headSha,lastImprovementScore:G.lastImprovementScore??0})):G=O??null}let le=A.includeRepositoryLinksInGitHubComments,Ir=A.postGitHubProgressReplies,mt=new Map(Object.entries(hP(c.metadata))),st=async(O,J)=>{let H={...hP(c.metadata),[O]:J};await l({metadata:{...c.metadata??{},statusReplyRefs:H}})},sp=async O=>{let J=mt.get(O);if(J)return J;let H=v.feedbackItems.find(K=>K.id===O);if(!H)return null;let me=bP(H,v.feedbackItems);return me?(mt.set(O,me),await st(O,me),me):null},Zr=async(O,J)=>{let H=await sp(O);if(H)try{let me=xP(H.body,J);await this.github.updateStatusReply(_,D,H,me),await st(O,H)}catch(me){let K=v.feedbackItems.find(je=>je.id===O),Te=K?bP(K,v.feedbackItems):null;if(Te&&Te.commentDatabaseId!==H.commentDatabaseId)try{let je=xP(Te.body,J);await this.github.updateStatusReply(_,D,Te,je),mt.set(O,Te),await st(O,Te);return}catch(je){await d(v.id,"github.status",`Failed to update recovered status reply for ${O}: ${St(je)}`,{feedbackId:O});return}await d(v.id,"github.status",`Failed to update status reply for ${O}: ${St(me)}`,{feedbackId:O})}},aa=async(O,J)=>{try{await this.github.postPRComment(_,D,hY(O,J,le))}catch(H){await d(v.id,"github.agent-command",`Failed to post agent command comment: ${St(H)}`)}},U0=async O=>{let{phase:J,onFallback:H,...me}=O,K=await this.runtime.applyFixesWithAgent({agent:L,...me});if(K.code===0)return K;let Te=new Error(`${L} apply failed (${K.code}): ${K.stderr||K.stdout}`);return await x(Te,J)?(await H?.(L),await p(v.id,"info",`Launching ${L} after fallback`,{phase:J,metadata:{agent:L,prompt:O.prompt}}),await aa(L,O.prompt),this.runtime.applyFixesWithAgent({agent:L,...me})):K},G0=v.feedbackItems.filter(O=>O.status==="pending");await p(v.id,"info",`Evaluating ${G0.length} pending feedback item(s)`,{phase:"evaluate.comments"});let oa=new Map;for(let O of G0){if(await p(v.id,"info",`Inspecting feedback from ${O.author}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,file:O.file,line:O.line}}),gY(O.body)){oa.set(O.id,Ni(O,!1,"oh-my-pr-authored agent command comment; no code change required")),await p(v.id,"info",`Ignored self-authored agent command comment ${O.id}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,decision:"reject"}});continue}if(oY(O,v.feedbackItems)){oa.set(O.id,Ni(O,!1,"Automation audit trail follow-up; no code change required")),await p(v.id,"info",`Ignored audit-trail follow-up comment ${O.id}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,decision:"reject"}});continue}let J=QQ({pr:v,item:O});await p(v.id,"info",`Evaluating feedback ${O.id} with ${L}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,agent:L,prompt:J}});let H=await C({cwd:process.cwd(),prompt:J,phase:"evaluate.comments"}),me=Ni(O,H.needsFix,H.reason);if(oa.set(O.id,me),H.needsFix){await p(v.id,"info",`Accepted feedback ${O.id}: ${H.reason}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,decision:"accept"}});try{await this.github.addReactionToComment(_,D,O,"eyes")}catch(K){await d(v.id,"github.reaction",`Failed to add reaction for ${O.id}: ${St(K)}`,{feedbackId:O.id})}if(Ir)try{let K=await this.github.postStatusReplyForFeedbackItem(_,D,O,bY(na.accepted,le));K&&(mt.set(O.id,K),await st(O.id,K))}catch(K){await d(v.id,"github.status",`Failed to post status reply for ${O.id}: ${St(K)}`,{feedbackId:O.id})}}else await p(v.id,"info",`Rejected feedback ${O.id}: ${H.reason}`,{phase:"evaluate.comments",metadata:{feedbackId:O.id,decision:"reject"}})}let Dn=[];if(A.autoHealCI&&G)await p(v.id,"info",`Skipping legacy status-task evaluation because CI healing session ${G.id} is active`,{phase:"evaluate.status",metadata:{healingSessionId:G.id,healingState:G.state}});else{await p(v.id,"info",`Evaluating ${U.length} failing status check(s)`,{phase:"evaluate.status"});for(let O of U){let J=YQ({pr:v,context:O.context,description:O.description,targetUrl:O.targetUrl});await p(v.id,"info",`Evaluating failing status ${O.context} with ${L}`,{phase:"evaluate.status",metadata:{context:O.context,agent:L,prompt:J}});let H=await C({cwd:process.cwd(),prompt:J,phase:"evaluate.status"});H.needsFix?(Dn.push(O),await p(v.id,"info",`Accepted failing status ${O.context}: ${H.reason}`,{phase:"evaluate.status",metadata:{context:O.context,decision:"accept"}})):await p(v.id,"info",`Rejected failing status ${O.context}: ${H.reason}`,{phase:"evaluate.status",metadata:{context:O.context,decision:"reject"}})}}if(oa.size>0){let O=v.feedbackItems.map(me=>oa.get(me.id)??me),J=Fi(O),H=await this.storage.updatePR(v.id,{feedbackItems:O,accepted:J.accepted,rejected:J.rejected,flagged:J.flagged});H&&(v=H)}let mC=v.feedbackItems.filter(O=>O.status==="queued"&&O.decision==="accept"),B0=T?v.feedbackItems.filter(O=>(O.status==="queued"||O.status==="in_progress")&&O.decision==="accept"):[],Jt=B0.length>0?B0:mC;h=pY(v);let H0=E.mergeable===!1,pr=H0&&A.autoResolveMergeConflicts;H0&&!A.autoResolveMergeConflicts&&await p(v.id,"warn",`PR #${v.number} has merge conflicts but auto-resolve is disabled in settings`,{phase:"conflict",metadata:{baseRef:E.baseRef,mergeable:E.mergeable}});let Bi=!!(T&&!F),ap=!!(T&&F),op=!ap&&(Jt.length>0||Dn.length>0||Bi),ua=AP(v,E.headSha),Nn=!ap&&!Bi&&eY(v,E.headSha,A.autoUpdateDocs),Bo=A.autoUpdateDocs&&ua?.status==="needed"?ua.summary:null,Xt=!!Bo,$0=op||pr||Nn||Xt,Ho=null,z0=!!(A.autoHealCI&&G&&G.state==="awaiting_repair_slot"&&!ap&&!op&&!pr&&!Nn&&!Xt);if(z0&&G){let O=oe[0]?.fingerprint??G.latestFingerprint??void 0,J=await Ie.canRetry(G.id,O);J.canRetry||(Ho=J.reason??"retry budget rejected the healing attempt",G=await Ie.markEscalated(G.id,Ho,{currentHeadSha:E.headSha,latestFingerprint:O??G.latestFingerprint}),await p(v.id,"warn",`CI healing retry skipped: ${Ho}`,{phase:"healing.retry",metadata:{healingSessionId:G.id,fingerprint:O??null,sessionAttempts:J.sessionAttempts,fingerprintAttempts:J.fingerprintAttempts,maxSessionAttempts:J.maxSessionAttempts,maxFingerprintAttempts:J.maxFingerprintAttempts}}))}let W0=!!(z0&&G?.state==="awaiting_repair_slot"&&!Ho);if(A.autoUpdateDocs&&ua&&!Nn&&await p(v.id,"info",`Documentation assessment already recorded for ${E.headSha.slice(0,7)} (${ua.status})`,{phase:"evaluate.docs",metadata:{headSha:E.headSha,status:ua.status}}),!$0&&!W0&&h.length===0&&!pr&&Ee.length===0){await p(v.id,"info",`Babysitter checked PR #${v.number}; no necessary fixes identified`,{phase:"run"}),await this.storage.updatePR(v.id,{status:"watching",lastChecked:new Date().toISOString()}),await l({status:"completed",phase:"run.completed",lastError:null});return}let Le=E.headSha;I=!1;let $o=null,up=new Map,Kt=null,cp=!1,ca=null,Pe=null;if(pr&&await p(v.id,"info",`PR #${v.number} has merge conflicts with base branch ${E.baseRef}`,{phase:"conflict",metadata:{baseRef:E.baseRef,mergeable:E.mergeable}}),$0||pr){await p(v.id,"info",`Babysitter preparing fix run with ${Jt.length} comment task(s), ${Dn.length} status task(s), ${Xt?1:0} documentation task(s), and ${h.length} GitHub follow-up task(s)${Nn?", with documentation assessment":""}${pr?", plus merge conflict resolution":""}${Bi?", with forced prompt replay":""} using ${L}`,{phase:"run",metadata:{commentTasks:Jt.length,statusTasks:Dn.length,docsTasks:Xt?1:0,docsAssessmentNeeded:Nn,followUpTasks:h.length,hasConflicts:pr,shouldRunForcedReplay:Bi,agent:L}});let O=Ct();await p(v.id,"info",`Preparing worktree in ${O.rootDir}`,{phase:"worktree"});let{repoCacheDir:J,worktreePath:H,healed:me,remoteName:K}=await Vl({rootDir:O.rootDir,repoFullName:E.repoFullName,repoCloneUrl:E.repoCloneUrl,headRepoFullName:E.headRepoFullName,headRepoCloneUrl:E.headRepoCloneUrl,headRef:E.headRef,prNumber:v.number,runId:s,runCommand:this.runtime.runCommand});$o=K;try{await p(v.id,"info",`Worktree ready at ${H}`,{phase:"worktree",metadata:{remoteName:K,healed:me}}),me&&await p(v.id,"info","Repo cache required auto-heal before the worktree was created",{phase:"worktree",metadata:{repoCacheDir:J}}),await p(v.id,"info",`Prepared PR head from remote ${K}`,{phase:"worktree",metadata:{remoteName:K,headRef:E.headRef}}),await p(v.id,"info","Ensuring git identity",{phase:"git.identity"}),await xY(H,this.runtime.runCommand),await p(v.id,"info","Git identity ready",{phase:"git.identity"});let Te=await(this.runtime.checkDependencyPreflight??IP)({cwd:H,pr:v,pullSummary:E,requiresVerification:op||pr||Nn||Xt,runCommand:this.runtime.runCommand});if(!Te.ok)throw await p(v.id,"error",`Dependency preflight failed: ${Te.reason}`,{phase:"preflight.dependencies",metadata:{headSha:E.headSha,reason:Te.reason}}),new Error(`Dependency preflight failed: ${Te.reason}`);if(await p(v.id,"info","Dependency preflight passed",{phase:"preflight.dependencies"}),Nn){await p(v.id,"info","Documentation assessment started",{phase:"evaluate.docs",metadata:{headSha:E.headSha}});try{let ze=await f({currentPrId:v.id,command:"git",args:["fetch","origin",E.baseRef],cwd:H,timeoutMs:12e4,phase:"evaluate.docs",successMessage:`Fetched origin/${E.baseRef} for docs assessment`});if(ze.code!==0)throw new Error(`Failed to fetch origin/${E.baseRef} for docs assessment: ${qi(ze)}`);let Ue=await f({currentPrId:v.id,command:"git",args:["diff","--name-only",`origin/${E.baseRef}...HEAD`],cwd:H,timeoutMs:1e4,phase:"evaluate.docs",successMessage:"Collected changed files for docs assessment"});if(Ue.code!==0)throw new Error(`Failed to collect changed files for docs assessment: ${qi(Ue)}`);let Ge=await f({currentPrId:v.id,command:"git",args:["diff","--stat",`origin/${E.baseRef}...HEAD`],cwd:H,timeoutMs:1e4,phase:"evaluate.docs",successMessage:"Collected diff stat for docs assessment"});if(Ge.code!==0)throw new Error(`Failed to collect diff stat for docs assessment: ${qi(Ge)}`);let at=await f({currentPrId:v.id,command:"git",args:["diff","--no-color","--unified=0",`origin/${E.baseRef}...HEAD`],cwd:H,timeoutMs:1e4,phase:"evaluate.docs",successMessage:"Collected diff preview for docs assessment",maxOutputLogLines:20});if(at.code!==0)throw new Error(`Failed to collect diff preview for docs assessment: ${qi(at)}`);let ot=ZQ({pr:v,pullSummary:E,changedFiles:Ue.stdout.trim(),diffStat:Ge.stdout.trim(),diffPreview:at.stdout.trim()});await p(v.id,"info",`Evaluating documentation needs with ${L}`,{phase:"evaluate.docs",metadata:{agent:L,prompt:ot}});let gt=await C({cwd:H,prompt:ot,phase:"evaluate.docs"}),kt={headSha:E.headSha,status:gt.needsFix?"needed":"not_needed",summary:gt.reason,assessedAt:new Date().toISOString()},Rt=await this.storage.updatePR(v.id,{docsAssessment:kt});Rt&&(v=Rt),Xt=gt.needsFix,Bo=gt.needsFix?gt.reason:null,await p(v.id,"info",gt.needsFix?`Documentation updates required: ${gt.reason}`:`Documentation updates not required: ${gt.reason}`,{phase:"evaluate.docs",metadata:{decision:gt.needsFix?"needed":"not_needed",headSha:E.headSha}})}catch(ze){let Ue=St(ze),Ge={headSha:E.headSha,status:"failed",summary:Ue,assessedAt:new Date().toISOString()},at=await this.storage.updatePR(v.id,{docsAssessment:Ge});at&&(v=at),Xt=!1,Bo=null,await p(v.id,"warn",`Documentation assessment failed: ${Ue}`,{phase:"evaluate.docs",metadata:{headSha:E.headSha}})}}if(pr){await p(v.id,"info",`Fetching base branch origin/${E.baseRef} for merge`,{phase:"conflict"});let ze=await f({currentPrId:v.id,command:"git",args:["fetch","origin",E.baseRef],cwd:H,timeoutMs:12e4,phase:"conflict",successMessage:`Fetched origin/${E.baseRef}`});if(ze.code!==0)throw new Error(`Failed to fetch base branch origin/${E.baseRef}: ${qi(ze)}`);await p(v.id,"info",`Attempting merge of origin/${E.baseRef} into ${E.headRef}`,{phase:"conflict"});let Ue=await this.runtime.runCommand("git",["merge","FETCH_HEAD","--no-edit"],{cwd:H,timeoutMs:6e4});if(Ue.code!==0){await p(v.id,"info","Merge produced conflicts; invoking agent to resolve them",{phase:"conflict"});let at=(await this.runtime.runCommand("git",["diff","--name-only","--diff-filter=U"],{cwd:H,timeoutMs:1e4})).stdout.trim().split(`
|
|
1071
|
+
`).filter(pp=>pp.trim().length>0);if(at.length===0)throw new Error(`Merge failed but no conflict files detected: ${Ue.stderr||Ue.stdout}`);await p(v.id,"info",`Found ${at.length} file(s) with merge conflicts`,{phase:"conflict",metadata:{conflictFiles:at}});let ot=m(v.id,"conflict.agent","stdout","info"),gt=m(v.id,"conflict.agent","stderr","warn"),kt=await this.github.resolveGitHubAuthToken(A),Rt=kt?{...process.env,GITHUB_TOKEN:kt,GH_TOKEN:kt}:void 0,Fn=tY({pr:v,pullSummary:E,remoteName:K,conflictFiles:at});await p(v.id,"info",`Launching ${L} to resolve merge conflicts`,{phase:"conflict.agent",metadata:{agent:L,prompt:Fn}}),await aa(L,Fn);let Mn=await U0({cwd:H,prompt:Fn,env:Rt,onStdoutChunk:ot.onChunk,onStderrChunk:gt.onChunk,phase:"conflict.agent"});if(await ot.flush(),await gt.flush(),Mn.code!==0){let pp=_P(Mn.stderr||Mn.stdout);throw new Error(`Agent failed to resolve merge conflicts (${Mn.code}): ${pp}`)}await p(v.id,"info","Agent completed merge conflict resolution",{phase:"conflict.agent",metadata:{code:Mn.code}});let Wo=await this.runtime.runCommand("git",["diff","--name-only","--diff-filter=U"],{cwd:H,timeoutMs:5e3});if(Wo.code!==0)throw new Error(Mi("checking unresolved merge conflicts",Wo));if(Wo.stdout.trim())throw new Error(`Agent left unresolved merge conflicts: ${Wo.stdout.trim()}`);await g({currentPrId:v.id,cwd:H,commitArgs:["commit","--no-verify","--no-edit"],phase:"conflict",context:"merge conflict resolution"}),await p(v.id,"info","Merge conflicts resolved and committed by babysitter",{phase:"conflict"})}else await p(v.id,"info","Merge completed without conflicts (GitHub mergeability may have been stale)",{phase:"conflict"})}if(Jt.length>0){let ze=new Set(Jt.map(ot=>ot.id)),Ue=v.feedbackItems.map(ot=>ze.has(ot.id)?dP(ot):ot),Ge=Fi(Ue),at=await this.storage.updatePR(v.id,{feedbackItems:Ue,accepted:Ge.accepted,rejected:Ge.rejected,flagged:Ge.flagged});at&&(v=at)}if(Bi||Jt.length>0||Dn.length>0||Xt){let ze=m(v.id,"agent","stdout","info"),Ue=m(v.id,"agent","stderr","warn"),Ge=await this.github.resolveGitHubAuthToken(A),at=Ge?{...process.env,GITHUB_TOKEN:Ge,GH_TOKEN:Ge}:void 0,ot=Bi&&T?T:rY({pr:v,pullSummary:E,remoteName:K,commentTasks:Jt,statusTasks:Dn,docsTaskSummary:Bo});await l({phase:"run.prompt-prepared",prompt:ot,initialHeadSha:S||E.headSha}),await p(v.id,"info",`Launching ${L} in autonomous mode`,{phase:"agent",metadata:{githubAuth:!!Ge,prompt:ot}}),await l({phase:"run.agent-running"}),await aa(L,ot);let gt=na.agentRunning(L);await Promise.all(Jt.map(Rt=>Zr(Rt.id,gt)));let kt=await U0({cwd:H,prompt:ot,env:at,onStdoutChunk:ze.onChunk,onStderrChunk:Ue.onChunk,phase:"agent",onFallback:async Rt=>{let Fn=na.agentRunning(Rt);await Promise.all(Jt.map(Mn=>Zr(Mn.id,Fn)))}});if(await ze.flush(),await Ue.flush(),kt.code!==0){let Rt=_P(kt.stderr||kt.stdout);throw await Promise.all(Jt.map(Fn=>Zr(Fn.id,na.agentFailed(L,Rt)))),new Error(`${L} apply failed (${kt.code}): ${Rt}`)}await Promise.all(Jt.map(Rt=>Zr(Rt.id,na.agentCompleted))),up=sY(kt.stdout),Kt=aY(kt.stdout),await p(v.id,"info",`${L} completed successfully`,{phase:"agent",metadata:{code:kt.code,extractedSummaries:up.size,docsTaskOutcome:Kt?.outcome??null}}),await l({phase:"run.agent-finished"})}await g({currentPrId:v.id,cwd:H,commitArgs:["commit","--no-verify","-m",`Apply babysitter fixes for PR #${v.number}`],phase:"verify.git.status",context:"agent run"}),await p(v.id,"info","Worktree is clean after babysitter finalization",{phase:"verify.git.status"});let je=await f({currentPrId:v.id,command:"git",args:["rev-parse","HEAD"],cwd:H,timeoutMs:5e3,phase:"verify.git.local-head",successMessage:"Collected worktree HEAD"});if(je.code!==0)throw new Error(`git rev-parse HEAD failed: ${je.stderr||je.stdout}`);let Qt=await f({currentPrId:v.id,command:"git",args:["-C",J,"fetch",K,E.headRef],timeoutMs:12e4,phase:"verify.git.fetch-head",successMessage:`Fetched ${K}/${E.headRef} for verification`});if(Qt.code!==0)throw new Error(`git fetch ${K} ${E.headRef} failed: ${Qt.stderr||Qt.stdout}`);let zo=await f({currentPrId:v.id,command:"git",args:["-C",J,"rev-parse","FETCH_HEAD"],timeoutMs:5e3,phase:"verify.git.remote-head",successMessage:"Collected remote PR head SHA"});if(zo.code!==0)throw new Error(`git rev-parse FETCH_HEAD failed: ${zo.stderr||zo.stdout}`);let la=je.stdout.trim(),pa=zo.stdout.trim(),lp=la!==E.headSha;if(lp&&pa!==la){let ze=await f({currentPrId:v.id,command:"git",args:["push",K,`HEAD:${E.headRef}`],cwd:H,timeoutMs:12e4,phase:"verify.git.push",successMessage:`Pushed babysitter commit to ${K}/${E.headRef}`});if(ze.code!==0)throw new Error(Mi(`pushing ${K}/${E.headRef}`,ze));let Ue=await f({currentPrId:v.id,command:"git",args:["-C",J,"fetch",K,E.headRef],timeoutMs:12e4,phase:"verify.git.fetch-head",successMessage:`Fetched ${K}/${E.headRef} after babysitter push`});if(Ue.code!==0)throw new Error(Mi(`fetching ${K}/${E.headRef} after push`,Ue));let Ge=await f({currentPrId:v.id,command:"git",args:["-C",J,"rev-parse","FETCH_HEAD"],timeoutMs:5e3,phase:"verify.git.remote-head",successMessage:"Collected remote PR head SHA after babysitter push"});if(Ge.code!==0)throw new Error(Mi("reading remote PR head after push",Ge));pa=Ge.stdout.trim()}if(lp&&pa!==la)throw new Error("Babysitter created a local commit but could not verify it on the PR head branch");if(I=pa!==E.headSha,Dn.length>0&&!I)throw new Error("Agent did not update the PR head branch for accepted failing status tasks");if(Xt&&!Kt)throw new Error("Agent did not report documentation task outcome");if(Xt&&!I&&Kt?.outcome!=="no_change")throw new Error("Agent did not update the PR head branch for required documentation tasks");if(pr&&!I)throw new Error("Conflict resolution was not pushed to the PR head branch");if(Xt&&Kt?.outcome==="no_change"){let ze=await this.storage.updatePR(v.id,{docsAssessment:{headSha:E.headSha,status:"not_needed",summary:Kt.summary,assessedAt:new Date().toISOString()}});ze&&(v=ze)}Le=la,await p(v.id,"info","Verified git branch state after agent run",{phase:"verify.git",metadata:{initialHeadSha:E.headSha,localHeadSha:la,remoteHeadSha:pa,branchMoved:I,localCommitCreated:lp,remoteName:K,docsTaskOutcome:Kt?.outcome??null}}),Kt&&await p(v.id,"info",`Documentation task outcome: ${Kt.outcome} - ${Kt.summary}`,{phase:"verify.docs",metadata:{outcome:Kt.outcome,branchMoved:I}})}finally{try{await p(v.id,"info","Cleaning up worktree",{phase:"cleanup"}),await Jl({repoCacheDir:J,worktreePath:H,runCommand:this.runtime.runCommand}),await p(v.id,"info","Worktree cleanup complete",{phase:"cleanup"})}catch(Te){let je=Te instanceof Error?Te.message:String(Te);await p(v.id,"error",`Worktree cleanup failed: ${je}`,{phase:"cleanup"})}}}else await p(v.id,"info",`Babysitter found ${h.length} accepted feedback item(s) awaiting GitHub follow-up`,{phase:"run",metadata:{followUpTasks:h.length,agent:L}});if(W0&&G){let O=oe.map(K=>K.fingerprint);await p(v.id,"info",`Launching dedicated CI healing attempt for ${O.length} fingerprint(s)`,{phase:"healing.run",metadata:{healingSessionId:G.id,targetFingerprints:O}}),G=await Ie.markRepairing(G.id,{currentHeadSha:E.headSha,latestFingerprint:O[0]??G.latestFingerprint});let J=await this.github.resolveGitHubAuthToken(A),H=J?{...process.env,GITHUB_TOKEN:J,GH_TOKEN:J}:void 0;if(Pe=await this.runtime.runCIHealingRepairAttempt?.({prNumber:v.number,repoFullName:E.repoFullName,repoCloneUrl:E.repoCloneUrl,headRepoFullName:E.headRepoFullName,headRepoCloneUrl:E.headRepoCloneUrl,headRef:E.headRef,baseRef:E.baseRef,headSha:E.headSha,title:E.title,url:E.url,author:E.author,branch:v.branch,agent:L,failures:oe,runId:`${s}-ci-healing`,rootDir:Ct().rootDir,env:H})??null,!Pe)throw new Error("CI healing runtime is unavailable");ca=(await this.storage.createHealingAttempt({sessionId:G.id,attemptNumber:G.attemptCount,inputSha:E.headSha,outputSha:Pe.accepted?Pe.verification.remoteHeadSha:null,status:Pe.accepted?"awaiting_ci":"failed",endedAt:Pe.accepted?null:new Date().toISOString(),agent:L,promptDigest:Pe.promptDigest,targetFingerprints:Pe.targetFingerprints,summary:Pe.summary,improvementScore:null,error:Pe.rejectionReason})).id,cp=!0,Pe.accepted?(G=await Ie.markAwaitingCi(G.id,{currentHeadSha:Pe.verification.remoteHeadSha,latestFingerprint:Pe.targetFingerprints[0]??G.latestFingerprint}),I=Pe.verification.pushedNewSha,Le=Pe.verification.remoteHeadSha,$o=Pe.remoteName):G=await Ie.markEscalated(G.id,Pe.rejectionReason??"CI healing attempt failed",{currentHeadSha:E.headSha,latestFingerprint:Pe.targetFingerprints[0]??G.latestFingerprint})}await l({phase:"run.reconcile"});for(let O of h){let J=!D0(O,v.feedbackItems),H=Uo(Ql(O));if(J){await p(v.id,"info",`Posting GitHub follow-up for ${O.id}${H?" and resolving conversation":""}`,{phase:"github.followup",metadata:{feedbackId:O.id,replyKind:O.replyKind,resolve:H}});let me=fY(Le,O,le,up.get(O.auditToken));await this.github.postFollowUpForFeedbackItem(_,D,O,me,{resolve:H})}else if(H){if(!O.threadId){await p(v.id,"warn",`Cannot resolve review thread for ${O.id}: thread ID unavailable (skipping)`,{phase:"github.followup",metadata:{feedbackId:O.id}});continue}await this.github.resolveReviewThread(_,D,O.threadId)}await p(v.id,"info",`GitHub follow-up complete for ${O.id}`,{phase:"github.followup",metadata:{feedbackId:O.id,replyKind:O.replyKind,posted:J,resolved:H}}),await Zr(O.id,na.resolved(Le))}v=await this.syncFeedbackForPR(v.id,{runId:s,logStart:!0,phase:"verify.sync"});let V0=cY({pr:v,followUpTasks:h,runStartedAtMs:a});if(V0.length>0)throw new Me(`GitHub audit trail verification failed: ${V0.join("; ")}`,502);if(await p(v.id,"info","GitHub audit trail verified",{phase:"verify.github",metadata:{verifiedComments:h.length,remoteName:$o,branchMoved:I}}),h.length>0){let O=new Set(h.map(K=>K.id)),J=v.feedbackItems.map(K=>O.has(K.id)?Ql(K):K),H=Fi(J),me=await this.storage.updatePR(v.id,{feedbackItems:J,accepted:H.accepted,rejected:H.rejected,flagged:H.flagged});me&&(v=me)}if(I&&Le){await p(v.id,"info","Waiting for CI/CD checks on new commit...",{phase:"verify.ci",metadata:{headSha:Le}});let O=await this.pollForCICompletion(_,w,D,Le,v.id,p);if(O.status==="failure"){let J=O.failures.map(H=>`${H.context}: ${H.description}`).join("; ");await p(v.id,"warn",`CI/CD still failing after agent fix: ${J}`,{phase:"verify.ci",metadata:{failures:O.failures}});try{let H=[`## \u26A0\uFE0F ${PP(le)} CI Alert`,"",`The babysitter pushed changes (commit \`${Le.slice(0,7)}\`), but CI/CD checks are still failing:`,"",...O.failures.map(me=>`- **${me.context}**: ${me.description}${me.targetUrl?` ([details](${me.targetUrl}))`:""}`),"","Manual investigation may be required.",...le?["",In]:[]].join(`
|
|
1072
1072
|
`);await this.github.postPRComment(_,D,H)}catch(H){await d(v.id,"verify.ci",`Failed to post CI failure alert comment: ${St(H)}`)}if(await this.storage.updatePR(v.id,{testsPassed:!1,lastChecked:new Date().toISOString()}),cp&&Pe&&ca&&G){G=await Ie.markVerifying(G.id,{currentHeadSha:Le});let H=this.now().toISOString(),K=(this.github.fetchCheckSnapshotsForRef?await this.github.fetchCheckSnapshotsForRef(_,w,v.id,Le):O.failures.map(Qt=>({id:`${Qt.context}:${Qt.description}:${Le}`,prId:v.id,sha:Le,provider:"github.commit_status",context:Qt.context,status:"failure",conclusion:null,description:Qt.description,targetUrl:Qt.targetUrl,observedAt:H}))).filter(Qt=>Sm(Qt)),Te=k0(K);await vP(this.storage,K),await wP(this.storage,G.id,Le,Te);let je=dY(Pe.targetFingerprints,Te);await this.storage.updateHealingAttempt(ca,{outputSha:Le,status:"verified",endedAt:new Date().toISOString(),improvementScore:je.improvementScore,error:je.improvementScore>0?null:`CI failures remained unchanged or worsened after repair: ${J}`}),je.improvementScore>0?G=await Ie.markAwaitingRepairSlot(G.id,{currentHeadSha:Le,latestFingerprint:je.remainingTargetFingerprints[0]??Te[0]?.fingerprint??null,lastImprovementScore:je.improvementScore}):G=await Ie.markEscalated(G.id,`CI failures remained unchanged or worsened after repair: ${J}`,{currentHeadSha:Le,latestFingerprint:je.remainingTargetFingerprints[0]??Te[0]?.fingerprint??null,lastImprovementScore:je.improvementScore})}}else O.status==="success"?(await p(v.id,"info","All CI/CD checks passed on new commit",{phase:"verify.ci",metadata:{headSha:Le}}),await this.storage.updatePR(v.id,{testsPassed:!0,lastChecked:new Date().toISOString()}),cp&&Pe&&ca&&G&&(G=await Ie.markVerifying(G.id,{currentHeadSha:Le}),await this.storage.updateHealingAttempt(ca,{outputSha:Le,status:"verified",endedAt:new Date().toISOString(),improvementScore:Math.max(2,Pe.targetFingerprints.length*2),error:null}),G=await Ie.markHealed(G.id,{currentHeadSha:Le,latestFingerprint:null,lastImprovementScore:Math.max(2,Pe.targetFingerprints.length*2)}))):await p(v.id,"info","CI/CD checks did not complete within polling window; will re-check on next cycle",{phase:"verify.ci",metadata:{headSha:Le}})}await this.storage.updatePR(v.id,{status:"watching",lastChecked:new Date().toISOString()}),await p(v.id,"info","Babysitter run complete",{phase:"run",metadata:{remoteName:$o,branchMoved:I}}),await l({status:"completed",phase:"run.completed",lastError:null});return}catch(A){let j=A instanceof Error?A.message:String(A);await l({status:"failed",phase:"run.failed",lastError:j});let v=await this.storage.getPR(e);if(v){let k=A instanceof Me&&I,x=k?"warn":"error",C=k?"Babysitter warning":"Babysitter error";if(await p(v.id,x,`${C}: ${j}`,{phase:"run"}),h.length>0){let _=new Set(h.map(U=>U.id)),D=v.feedbackItems.map(U=>_.has(U.id)?k?fP(U,`GitHub comment could not be posted: ${j}`):I0(U,j):U),E=Fi(D);await this.storage.updatePR(v.id,{feedbackItems:D,accepted:E.accepted,rejected:E.rejected,flagged:E.flagged,status:k?"watching":"error",lastChecked:new Date().toISOString()})}else await this.storage.updatePR(v.id,{status:k?"watching":"error",lastChecked:new Date().toISOString()})}let L=A instanceof Error?A.message:String(A);if(Go.warn({err:L,prId:e},"Babysitter failure"),A instanceof Error&&A.stack&&Go.debug({stack:A.stack,prId:e},"Babysitter failure stack"),n?.rethrowOnFailure)throw A}finally{await o,this.inProgress.delete(e)}}};var _Y={buildOctokit:lr,resolveReviewThread:qo};function EY(t){return{accepted:t.filter(e=>e.decision==="accept").length,rejected:t.filter(e=>e.decision==="reject").length,flagged:t.filter(e=>e.decision==="flag").length}}async function LP(t){let{storage:e,pr:r,feedbackId:n,decision:i,github:s=_Y}=t,a=r.feedbackItems.map(c=>c.id===n?lP(c,i):c),o=a.find(c=>c.id===n);if(o?.threadId&&Uo(o)){let c=jl(r.url);if(!c)throw new Me(`Invalid PR URL: ${r.url}`,500);let l=await e.getConfig(),p=await s.buildOctokit(l);await s.resolveReviewThread(p,c,o.threadId),a=a.map(d=>d.id===n?cP(d):d)}let u=EY(a);return e.updatePR(r.id,{feedbackItems:a,accepted:u.accepted,rejected:u.rejected,flagged:u.flagged})}var NP=require("crypto");var TY=zt("jobs"),Vt=class extends Error{constructor(e){super(e),this.name="CancelBackgroundJobError"}},ep=class{storage;queue;handlers;handledKinds;workerId;pollIntervalMs;leaseMs;heartbeatIntervalMs;maxAttempts;retryBackoffMs;now;onError;onReclaimedJobs;activeJobs=new Map;running=!1;polling=!1;pollTimer=null;constructor(e){this.storage=e.storage,this.queue=e.queue,this.handlers=e.handlers,this.handledKinds=Object.keys(e.handlers),this.workerId=e.workerId??(0,NP.randomUUID)(),this.pollIntervalMs=e.pollIntervalMs??1e3,this.leaseMs=e.leaseMs??3e4,this.heartbeatIntervalMs=e.heartbeatIntervalMs??1e4,this.maxAttempts=Math.max(1,e.maxAttempts??3),this.retryBackoffMs=Math.max(0,e.retryBackoffMs??3e4),this.now=e.now??(()=>new Date),this.onError=e.onError??(r=>{TY.warn({err:r instanceof Error?r.message:String(r)},"Background job dispatcher error")}),this.onReclaimedJobs=e.onReclaimedJobs??(()=>{})}async start(){this.running||(this.running=!0,await this.requeueExpiredAndNotify(),this.wake())}stop(){this.running=!1,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null)}wake(){this.running&&this.schedulePoll(0)}getActiveRunCount(){return this.activeJobs.size}async waitForIdle(e=12e4){let r=Date.now();for(;this.activeJobs.size>0;){if(Date.now()-r>=e)return!1;await SY(25)}return!0}schedulePoll(e){this.running&&(this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(()=>{this.pollTimer=null,this.pollOnce()},e))}async pollOnce(){if(!(!this.running||this.polling)){this.polling=!0;try{if(this.handledKinds.length===0||(await this.storage.getRuntimeState()).drainMode)return;await this.requeueExpiredAndNotify();let r=await this.queue.claimNext({workerId:this.workerId,leaseMs:this.leaseMs,now:this.now(),kinds:this.handledKinds});if(!r)return;this.runJob(r),this.schedulePoll(0)}catch(e){this.onError(e)}finally{this.polling=!1,this.running&&!this.pollTimer&&this.schedulePoll(this.pollIntervalMs)}}}runJob(e){let r=e.leaseToken,n=this.handlers[e.kind],i=(async()=>{if(!r)throw new Error(`Claimed background job ${e.id} is missing a lease token`);let s=this.heartbeatIntervalMs>0?setInterval(()=>{this.queue.heartbeat({jobId:e.id,leaseToken:r,leaseMs:this.leaseMs,now:this.now()}).catch(a=>{this.onError(a)})},this.heartbeatIntervalMs):null;try{if(!n)throw new Error(`No background job handler registered for ${e.kind}`);await n(e),await this.queue.complete({jobId:e.id,leaseToken:r,now:this.now()})}catch(a){await this.finalizeFailedJob(e,r,a)}finally{s&&clearInterval(s),this.activeJobs.delete(e.id)}})().catch(s=>{this.onError(s)}).finally(()=>{this.running&&this.schedulePoll(0)});this.activeJobs.set(e.id,i)}async requeueExpiredAndNotify(){let e=await this.queue.requeueExpiredWithDetails(this.now());e.length>0&&this.onReclaimedJobs(e)}async finalizeFailedJob(e,r,n){let i=this.now(),s=this.resolveFailureAction(e,n);try{switch(s){case"cancel":await this.queue.cancel({jobId:e.id,leaseToken:r,error:n instanceof Vt&&n.message||null,now:i});return;case"retry":await this.queue.retry({jobId:e.id,leaseToken:r,error:DP(n),now:i,availableAt:new Date(i.getTime()+this.retryBackoffMs)});return;case"fail":await this.queue.fail({jobId:e.id,leaseToken:r,error:DP(n),now:i});return}}catch(a){this.onError(new Error(`Failed to ${s} background job ${e.id} (kind=${e.kind}, attempt=${e.attemptCount}): ${a instanceof Error?a.message:String(a)}`,{cause:a}))}}resolveFailureAction(e,r){return r instanceof Vt?"cancel":e.attemptCount<this.maxAttempts?"retry":"fail"}};function DP(t){return(t instanceof Error?t.message:String(t)).trim().slice(0,2e3)}function SY(t){return new Promise(e=>setTimeout(e,t))}var MP=qe(require("path"),1);function kY(t){switch(t.toUpperCase()){case"READY":return"ready";case"BUILDING":return"building";case"DEPLOYING":case"QUEUED":case"INITIALIZING":return"deploying";case"ERROR":case"CANCELED":return"error";default:return"error"}}function RY(t){switch(t.toUpperCase()){case"SUCCESS":return"ready";case"BUILDING":return"building";case"DEPLOYING":return"deploying";case"INITIALIZING":case"QUEUED":return"deploying";case"FAILED":case"CRASHED":case"REMOVED":return"error";default:return"error"}}function FP(t){return MP.default.join(Ct().repoRootDir,zl(t))}var N0=class{platform="vercel";run;constructor(e){this.run=e??vt}async getDeploymentStatus(e){let{sha:r}=e,n=await this.run("vercel",["list","--meta",`githubCommitSha=${r}`,"--json"]);if(n.code!==0)return{state:"error",deploymentId:null,url:null,error:n.stderr||"vercel list failed"};let i;try{i=JSON.parse(n.stdout)}catch{return{state:"error",deploymentId:null,url:null,error:"Failed to parse vercel list output"}}let s=i.deployments??[];if(s.length===0)return{state:"not_found",deploymentId:null,url:null,error:null};let a=s[0],o=a.state.toUpperCase();return{state:kY(a.state),deploymentId:a.uid,url:a.url??null,error:o==="ERROR"?a.errorMessage??"Deployment failed":null}}async getDeploymentLogs(e){let{deploymentId:r}=e,n=await this.run("vercel",["inspect",r,"--json"]),i=r;if(n.code===0)try{let a=JSON.parse(n.stdout);a.url&&(i=a.url)}catch{}let s=await this.run("vercel",["logs",i]);return s.stdout||s.stderr}},F0=class{platform="railway";run;constructor(e){this.run=e??vt}async getDeploymentStatus(e){let r=await this.run("railway",["status","--json"],{cwd:FP(e.repo)});if(r.code!==0)return{state:"error",deploymentId:null,url:null,error:r.stderr||"railway status failed"};let n;try{n=JSON.parse(r.stdout)}catch{return{state:"error",deploymentId:null,url:null,error:"Failed to parse railway status output"}}return{state:RY(n.status??""),deploymentId:n.deploymentId??null,url:n.url??null,error:null}}async getDeploymentLogs(e){let{repo:r,deploymentId:n}=e,i=await this.run("railway",["logs","--deployment",n],{cwd:FP(r)});return i.stdout||i.stderr}};function jP(t,e){switch(t.toLowerCase()){case"vercel":return new N0(e);case"railway":return new F0(e);default:throw new Error(`Unsupported deployment platform: ${t}`)}}function AY(t){return{ensureRepoCache:t?.ensureRepoCache??Wl,applyFixesWithAgent:t?.applyFixesWithAgent??Ts,runCommand:t?.runCommand??vt}}function PY(t){return["You are fixing a failed deployment for a repository.","A pull request was merged but the deployment to the platform failed.","Your task is to diagnose the deployment failure and apply the minimal fix.","Create a new branch named deploy-fix/<platform>-<timestamp> from the merge SHA.","Leave any file edits unstaged and uncommitted. The app will stage, commit, push, and create the PR.","At the end of your response, include exactly one line in this format:","DEPLOYMENT_FIX_SUMMARY: <one short sentence describing what was fixed>","",`Repository: ${t.repo}`,`Platform: ${t.platform}`,`Merge SHA: ${t.mergeSha}`,`Base branch: ${t.baseBranch}`,`Trigger PR: #${t.triggerPrNumber}`,`Trigger PR title: ${t.triggerPrTitle}`,`Trigger PR URL: ${t.triggerPrUrl}`,"","Deployment failure log:","```",t.deploymentLog,"```","","Instructions:","1. Analyze the deployment log to identify the root cause of the failure.","2. Apply the minimal code change needed to fix the deployment error.","3. Do not run git commit or git push.","4. Leave the fix branch checked out with your file edits in the worktree.","5. Do not merge the branch \u2014 a PR will be created automatically.","6. Include the DEPLOYMENT_FIX_SUMMARY line at the end of your output."].join(`
|
|
1073
1073
|
`)}function Ui(t){let e=t.match(/^DEPLOYMENT_FIX_SUMMARY:\s*(.+)$/m);if(e?.[1])return e[1].trim();let r=t.trim();if(!r)return"No agent summary provided";let n=r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);return n[n.length-1]??"No agent summary provided"}async function qP(t){let e=AY(t.dependencies),r=`deploy-fix/${t.platform}-${Math.floor(Date.now()/1e3)}`,n=PY(t),{repoCacheDir:i}=await e.ensureRepoCache({rootDir:t.rootDir,repoFullName:t.repo,repoCloneUrl:t.repoCloneUrl,runCommand:e.runCommand}),s=await e.runCommand("git",["-C",i,"checkout","-b",r,t.mergeSha],{timeoutMs:3e4});if(s.code!==0)return{accepted:!1,rejectionReason:`branch creation failed: ${s.stderr||s.stdout}`,summary:"No agent summary provided",fixBranch:r,agentResult:s};try{let a=await e.applyFixesWithAgent({agent:t.agent,cwd:i,prompt:n,env:t.env});if(a.code!==0)return{accepted:!1,rejectionReason:pn(a,`agent failed (${a.code})`),summary:Ui(a.stdout),fixBranch:r,agentResult:a};let o=await e.runCommand("git",["-C",i,"status","--porcelain"],{timeoutMs:1e4});if(o.code!==0)return{accepted:!1,rejectionReason:`git status failed: ${o.stderr||o.stdout}`,summary:Ui(a.stdout),fixBranch:r,agentResult:a};if(o.stdout.trim()){let p=await e.runCommand("git",["-C",i,"add","-A"],{timeoutMs:3e4});if(p.code!==0)return{accepted:!1,rejectionReason:`git add failed: ${p.stderr||p.stdout}`,summary:Ui(a.stdout),fixBranch:r,agentResult:a};let d=await e.runCommand("git",["-C",i,"commit","-m",`Fix ${t.platform} deployment`],{timeoutMs:6e4});if(d.code!==0)return{accepted:!1,rejectionReason:`git commit failed: ${d.stderr||d.stdout}`,summary:Ui(a.stdout),fixBranch:r,agentResult:a}}let u=await e.runCommand("git",["-C",i,"log",`${t.mergeSha}..HEAD`,"--oneline"],{timeoutMs:1e4});if(!(u.code===0&&u.stdout.trim().length>0))return{accepted:!1,rejectionReason:"agent did not produce any new commits",summary:Ui(a.stdout),fixBranch:r,agentResult:a};let l=await e.runCommand("git",["-C",i,"push","origin",r],{timeoutMs:6e4});return l.code!==0?{accepted:!1,rejectionReason:`push failed: ${l.stderr||l.stdout}`,summary:Ui(a.stdout),fixBranch:r,agentResult:a}:{accepted:!0,rejectionReason:null,summary:Ui(a.stdout),fixBranch:r,agentResult:a}}finally{await e.runCommand("git",["-C",i,"checkout","--detach"],{timeoutMs:15e3})}}async function UP(t){let{storage:e,prId:r,questionId:n,question:i,preferredAgent:s}=t;await e.updateQuestion(n,{status:"answering"});try{let a=await CY(e,r),o=await Es(s),u=OY(a,i),c=await tr(o,o==="claude"?["-p","--output-format","text",u]:["exec","--skip-git-repo-check","--sandbox","read-only",u],{timeoutMs:18e4});if(c.code!==0){let p=pn(c,`Agent exited with code ${c.code}`);await e.updateQuestion(n,{status:"error",error:p.slice(0,2e3)});return}let l=c.stdout.trim();if(!l){await e.updateQuestion(n,{status:"error",error:"Agent returned an empty response",answer:null});return}await e.updateQuestion(n,{status:"answered",answer:l,answeredAt:new Date().toISOString()})}catch(a){let o=a instanceof Error?a.message:String(a);await e.updateQuestion(n,{status:"error",error:o.slice(0,2e3)})}}async function CY(t,e){let r=await t.getPR(e);if(!r)throw new Error("PR not found");let i=(await t.getLogs(e)).slice(-50).map(a=>`[${a.timestamp}] ${a.level.toUpperCase()} ${a.phase?`[${a.phase}]`:""} ${a.message}`).join(`
|
|
1074
1074
|
`),s=r.feedbackItems.map(a=>[`- [${a.status}]`,a.decision?`decision=${a.decision}`:"",`by ${a.author}`,a.file?`on ${a.file}${a.line?`:${a.line}`:""}`:"",`:: ${a.body.slice(0,200)}`].filter(Boolean).join(" "));return{title:r.title,number:r.number,repo:r.repo,branch:r.branch,author:r.author,url:r.url,status:r.status,testsPassed:r.testsPassed,lintPassed:r.lintPassed,lastChecked:r.lastChecked,feedbackSummary:s.length>0?s.join(`
|
|
@@ -1079,8 +1079,8 @@ ${In}`:In}function Yl(t,e){return[t,...e].join(" ")}function qi(t){return t.stde
|
|
|
1079
1079
|
`);return["Respond with ONLY valid JSON and nothing else.","Schema:",'{"shouldRelease":boolean,"reason":string,"bump":"patch"|"minor"|"major"|null,"title":string|null,"notes":string|null}',"","You are deciding whether a merged set of pull requests should be published as a GitHub release.","Be conservative. Release only when the merged changes are meaningful enough for users or operators to care about.","",`Repository: ${t.repo}`,`Release branch: ${t.baseBranch}`,`Latest release tag: ${t.latestTag??"none"}`,"",`Trigger PR: #${t.triggerPr.number} "${t.triggerPr.title}"`,`Trigger merged at: ${t.triggerPr.mergedAt}`,`Trigger merge SHA: ${t.triggerPr.mergeSha}`,"","Merged PRs included in this candidate release:",e||"(none)","","Decision rules:","- shouldRelease=true only when the merged changes are worth announcing as a GitHub release.","- bump must be null when shouldRelease=false.","- bump must be one of patch, minor, or major when shouldRelease=true.","- Use patch for fixes or small improvements, minor for additive user-facing features, and major for breaking changes.","- title should be short and release-note ready when shouldRelease=true, else null.","- notes should be GitHub-release Markdown focused on user-visible/operator-visible impact when shouldRelease=true, else null.","- notes must have exactly TWO sections in this order:"," 1. '## Why This Matters' \u2014 a user-friendly, value-driven summary at the top that explains how the release makes users' lives better."," 2. '## Detailed Changes' \u2014 a line-by-line changelog of the included changes in plain English, more detailed than a headline but not deeply technical.","- notes should mention the key merged PRs in plain language, not internal process commentary.","- Prefer user outcomes, workflow improvements, and visible behavior over implementation details."].join(`
|
|
1080
1080
|
`)}function $P(t){let e=NY(t.trim());if(!e||typeof e!="object")throw new Error(`Could not parse release evaluation JSON: ${t.slice(0,500)}`);let r=e;if(typeof r.shouldRelease!="boolean")throw new Error("Release evaluation missing boolean 'shouldRelease'");if(typeof r.reason!="string"||r.reason.trim().length===0)throw new Error("Release evaluation missing string 'reason'");if(!r.shouldRelease)return{shouldRelease:!1,reason:r.reason.trim(),bump:null,title:null,notes:null};if(r.bump!=="patch"&&r.bump!=="minor"&&r.bump!=="major")throw new Error("Release evaluation returned invalid 'bump'");if(typeof r.title!="string"||r.title.trim().length===0)throw new Error("Release evaluation missing non-empty 'title'");if(typeof r.notes!="string"||r.notes.trim().length===0)throw new Error("Release evaluation missing non-empty 'notes'");return{shouldRelease:!0,reason:r.reason.trim(),bump:r.bump,title:r.title.trim(),notes:r.notes.trim()}}function NY(t){try{return JSON.parse(t)}catch{}let e=t.indexOf("{"),r=t.lastIndexOf("}");if(e===-1||r===-1||r<=e)return null;try{return JSON.parse(t.slice(e,r+1))}catch{return null}}var FY=zt("release"),tp=class{storage;github;evaluateRelease;scheduleBackgroundJob;inProgress=new Set;repoLocks=new Map;constructor(e,r){this.storage=e,this.github=r.github,this.evaluateRelease=r.evaluateRelease??WP,this.scheduleBackgroundJob=r.scheduleBackgroundJob}getActiveRunCount(){return this.inProgress.size}async waitForIdle(e=12e4){let r=Date.now();for(;this.inProgress.size>0;){if(Date.now()-r>=e)return!1;await HY(50)}return!0}async enqueueMergedPullReleaseEvaluation(e){let r=await this.storage.getReleaseRunByTrigger(e.repo,e.triggerPrNumber,e.triggerMergeSha);if(r)return VP(r.status)||this.scheduleProcessing(r),r;let n=await this.storage.createReleaseRun({repo:e.repo,baseBranch:e.baseBranch,triggerPrNumber:e.triggerPrNumber,triggerPrTitle:e.triggerPrTitle,triggerPrUrl:e.triggerPrUrl,triggerMergeSha:e.triggerMergeSha,triggerMergedAt:e.triggerMergedAt,status:"detected",decisionReason:null,recommendedBump:null,proposedVersion:null,releaseTitle:null,releaseNotes:null,includedPrs:[],targetSha:e.triggerMergeSha,githubReleaseId:null,githubReleaseUrl:null,error:null,completedAt:null});return this.scheduleProcessing(n),n}async enqueueManualRepoRelease(e){let r=dt(e);if(!r)throw new Error(`Invalid repository slug: ${e}`);let n=`${r.owner}/${r.repo}`,i=await this.storage.getConfig(),s=await this.github.buildOctokit(i),a=await this.github.getDefaultBranch(s,r),u=[...await this.github.listUnreleasedMergedPulls(s,r,{baseBranch:a})].sort((p,d)=>Date.parse(p.mergedAt)-Date.parse(d.mergedAt)).at(-1);if(!u)return null;let c=await this.storage.getReleaseRunByTrigger(n,u.number,u.mergeSha);if(c){let p=c.status==="skipped"||c.status==="error",m=await this.storage.updateReleaseRun(c.id,{source:"manual",...p?{status:"detected",decisionReason:null,recommendedBump:null,proposedVersion:null,releaseTitle:null,releaseNotes:null,includedPrs:[],targetSha:u.mergeSha,githubReleaseId:null,githubReleaseUrl:null,error:null,completedAt:null}:{}})??c;return VP(m.status)||this.scheduleProcessing(m),m}let l=await this.storage.createReleaseRun({repo:n,baseBranch:a,triggerPrNumber:u.number,triggerPrTitle:u.title,triggerPrUrl:u.url,triggerMergeSha:u.mergeSha,triggerMergedAt:u.mergedAt,source:"manual",status:"detected",decisionReason:null,recommendedBump:null,proposedVersion:null,releaseTitle:null,releaseNotes:null,includedPrs:[],targetSha:u.mergeSha,githubReleaseId:null,githubReleaseUrl:null,error:null,completedAt:null});return this.scheduleProcessing(l),l}async retryReleaseRun(e){if(!await this.storage.getReleaseRun(e))return;let n=await this.storage.updateReleaseRun(e,{status:"detected",error:null,completedAt:null});if(n)return this.scheduleProcessing(n),n}async processReleaseRun(e){let r=await this.storage.getReleaseRun(e);if(r)return this.withRepoLock(r.repo,async()=>{if(this.inProgress.has(e))return this.storage.getReleaseRun(e);this.inProgress.add(e);try{let n=await this.storage.getReleaseRun(e);if(!n)return;if(n.status==="published"||n.status==="skipped")return n;let i=dt(n.repo);if(!i)return this.failRun(e,`Invalid repository slug: ${n.repo}`);let s=await this.storage.getConfig(),a=n.source==="manual";if(!a&&!s.autoCreateReleases)return await this.storage.updateReleaseRun(e,{status:"skipped",decisionReason:"Automatic release creation is disabled in settings",completedAt:new Date().toISOString()})??void 0;let o=await this.storage.getRepoSettings(n.repo);if(!a&&o&&!o.autoCreateReleases)return await this.storage.updateReleaseRun(e,{status:"skipped",decisionReason:`Automatic release creation is disabled for ${n.repo}`,completedAt:new Date().toISOString()})??void 0;await this.storage.updateReleaseRun(e,{status:"evaluating",error:null,completedAt:null});let u=await this.github.buildOctokit(s),c=await this.github.findLatestSemverReleaseTag(u,i),l=MY(n),p=await this.loadIncludedPulls(u,i,n,l),d=p.map(jY),m=await this.evaluateRelease({preferredAgent:s.codingAgent,repo:n.repo,baseBranch:n.baseBranch,latestTag:c,triggerPr:l,includedPulls:p}),f=m.shouldRelease||!a?m:UY(m,p);if(!f.shouldRelease)return await this.storage.updateReleaseRun(e,{status:"skipped",decisionReason:f.reason,recommendedBump:null,proposedVersion:null,releaseTitle:null,releaseNotes:null,includedPrs:d,targetSha:n.triggerMergeSha,completedAt:new Date().toISOString()})??void 0;if(!f.bump)throw new Error("Release evaluation approved publishing but did not provide a semver bump");let g=this.github.bumpReleaseTag(c,f.bump),h=qY(f,g),T=f.notes??`Release ${g}`;await this.storage.updateReleaseRun(e,{status:"proposed",decisionReason:f.reason,recommendedBump:f.bump,proposedVersion:g,releaseTitle:h,releaseNotes:T,includedPrs:d,targetSha:n.triggerMergeSha});let R=this.github.findReleaseByTag?await this.github.findReleaseByTag(u,i,g):null;if(R)return await this.storage.updateReleaseRun(e,{status:"published",githubReleaseId:R.id,githubReleaseUrl:R.url,completedAt:new Date().toISOString()})??void 0;await this.storage.updateReleaseRun(e,{status:"publishing"});let S=await this.github.createGitHubRelease(u,i,{tagName:g,targetCommitish:n.triggerMergeSha,name:h,body:T});return await this.storage.updateReleaseRun(e,{status:"published",githubReleaseId:S.id,githubReleaseUrl:S.url,completedAt:new Date().toISOString()})??void 0}catch(n){return this.failRun(e,BY(n))}finally{this.inProgress.delete(e)}})}async loadIncludedPulls(e,r,n,i){if(!this.github.listMergedPullsForReleaseCandidate)return[i];let s=await this.github.listMergedPullsForReleaseCandidate(e,r,{baseBranch:n.baseBranch,untilMergedAt:n.triggerMergedAt,triggerPr:i}),a=new Map;for(let o of s)a.set(o.mergeSha||`${o.repo}#${o.number}`,o);return a.has(i.mergeSha)||a.set(i.mergeSha,i),Array.from(a.values()).sort((o,u)=>o.mergedAt.localeCompare(u.mergedAt))}async failRun(e,r){return this.storage.updateReleaseRun(e,{status:"error",error:r,completedAt:new Date().toISOString()})}async withRepoLock(e,r){let n=this.repoLocks.get(e)??Promise.resolve(),i,s=new Promise(o=>{i=()=>o()}),a=n.then(()=>s);this.repoLocks.set(e,a),await n;try{return await r()}finally{i?.(),this.repoLocks.get(e)===a&&this.repoLocks.delete(e)}}scheduleProcessing(e){let r=e.id;if(this.scheduleBackgroundJob){this.scheduleBackgroundJob("process_release_run",r,Or("process_release_run",r),{releaseRunId:r,...On({label:`Processing release for ${e.repo}`,detail:`PR #${e.triggerPrNumber} - ${e.triggerPrTitle}`,targetUrl:e.triggerPrUrl})}).catch(n=>{FY.warn({err:n instanceof Error?n.message:String(n),runId:r},"Failed to schedule release run")});return}this.processReleaseRun(r).catch(()=>{})}};function MY(t){return{number:t.triggerPrNumber,title:t.triggerPrTitle,url:t.triggerPrUrl,author:"unknown",repo:t.repo,mergedAt:t.triggerMergedAt,mergeSha:t.triggerMergeSha}}function jY(t){return{number:t.number,title:t.title,url:t.url,author:t.author,mergedAt:t.mergedAt,mergeSha:t.mergeSha}}function qY(t,e){let r=t.title?.trim();return r?r.startsWith(e)?r:`${e} - ${r}`:e}function UY(t,e){return{shouldRelease:!0,reason:`Manual release requested. Evaluator recommendation: ${t.reason}`,bump:"patch",title:"Manual release",notes:GY(e)}}function GY(t){return`## Changes
|
|
1081
1081
|
${t.length>0?t.map(r=>`- #${r.number} ${r.title} (@${r.author})`).join(`
|
|
1082
|
-
`):"- Manual release requested."}`}function BY(t){return(t instanceof Error?t.message:String(t)).trim().slice(0,2e3)}function VP(t){return t==="skipped"||t==="published"}function HY(t){return new Promise(e=>setTimeout(e,t))}var $Y=["fix_submitted","escalated"],zY={monitoring:["failed","escalated"],failed:["fixing","escalated"],fixing:["fix_submitted","escalated"],fix_submitted:[],escalated:[]},rp=class{constructor(e,r=()=>new Date){this.storage=e;this.clock=r}async createSession(e){return this.storage.createDeploymentHealingSession({...e,deploymentId:null,deploymentLog:null,fixBranch:null,fixPrNumber:null,fixPrUrl:null,state:"monitoring",error:null,completedAt:null})}async ensureSession(e){let r=await this.storage.getDeploymentHealingSessionByRepoAndMergeSha(e.repo,e.mergeSha);return r||this.createSession(e)}async transitionTo(e,r,n={}){let i=await this.storage.getDeploymentHealingSession(e);if(!i)throw new Error(`Deployment healing session not found: ${e}`);if(i.state===r){let o=await this.storage.updateDeploymentHealingSession(e,n);if(!o)throw new Error(`Deployment healing session not found: ${e}`);return o}if(!zY[i.state].includes(r))throw new Error(`Illegal deployment healing transition: ${i.state} -> ${r}`);let s={...n,state:r};$Y.includes(r)&&(s.completedAt=n.completedAt??this.clock().toISOString());let a=await this.storage.updateDeploymentHealingSession(e,s);if(!a)throw new Error(`Deployment healing session not found: ${e}`);return a}};var JP=zt("runtime"),$e=class extends Error{statusCode;constructor(e,r){super(r),this.name="AppRuntimeError",this.statusCode=e}};function XP(t){return t instanceof Error?t.message:String(t)}function nt(t,e){if(t===void 0)throw new $e(404,e);return t}function WY(t){switch(t.kind){case"sync_watched_repos":return"Sync watched repositories";case"babysit_pr":return"Babysitting PR";case"process_release_run":return"Processing release";case"answer_pr_question":return"Answering PR question";case"generate_social_changelog":return"Social changelog generation removed";case"heal_deployment":return"Healing deployment"}}function np(t,e){let r=t.payload[e];return typeof r=="string"&&r.trim()?r:null}var VY={Claude:{auth:["Run `claude auth login` on this machine.","Restart oh-my-pr if it was launched before you refreshed credentials.","Rerun the babysitter for this PR."],cli_missing:["Install the Claude Code CLI on this machine.","Restart oh-my-pr after installing.","Rerun the babysitter for this PR."]},Codex:{auth:["Run `codex login` on this machine.","Restart oh-my-pr if it was launched before you refreshed credentials.","Rerun the babysitter for this PR."],cli_missing:["Install the Codex CLI on this machine.","Restart oh-my-pr after installing.","Rerun the babysitter for this PR."]}};function j0(t,e){return{agentLabel:t,kind:e,fixSteps:VY[t][e]}}function JY(t){let e=t.toLowerCase();return e.includes("claude evaluation failed")||e.includes("claude apply failed")?"Claude":e.includes("codex evaluation failed")||e.includes("codex apply failed")?"Codex":null}function KP(t){if(t.kind!=="babysit_pr"||!t.lastError)return null;let e=lm(t.lastError);if(!e)return null;let r=JY(t.lastError);if(r)return j0(r,e);let n=np(t,"preferredAgent");return n==="claude"?j0("Claude",e):n==="codex"?j0("Codex",e):null}function QP(t){return t.flatMap(e=>{let r=e.mergeCommitSha?.trim();return r?[{number:e.number,title:e.title,url:e.url,author:e.author,repo:e.repo,mergedAt:e.mergedAt,mergeSha:r}]:[]})}function ZP(t={}){let e=t.storage??Q_(),r=new YP.EventEmitter,n=t.backgroundJobQueue??new Xl(e),i,s=async(...w)=>{let k=await n.enqueue(...w);return i.wake(),k},a=t.deploymentHealingManager??new rp(e),o=t.releaseManager??new tp(e,{github:{buildOctokit:lr,getDefaultBranch:E0,findLatestSemverReleaseTag:P4,bumpReleaseTag:A4,listUnreleasedMergedPulls:async(w,k,x)=>{let C=await T0(w,k,{baseRef:x.baseBranch});return QP(C)},listMergedPullsForReleaseCandidate:async(w,k,x)=>{let C=await T0(w,k,{baseRef:x.baseBranch}),_=Date.parse(x.untilMergedAt);return QP(C.filter(D=>!Number.isFinite(_)||Date.parse(D.mergedAt)<=_))},findReleaseByTag:async(w,k,x)=>{let _=(await Gl(w,k)).find(D=>!D.draft&&D.tagName===x);return _?{id:_.id,url:_.htmlUrl,tagName:_.tagName,name:_.name}:null},createGitHubRelease:async(w,k,x)=>{let C=await C4(w,k,{tagName:x.tagName,targetCommitish:x.targetCommitish,name:x.name,body:x.body});return{id:C.id,url:C.htmlUrl,tagName:C.tagName,name:C.name}}},scheduleBackgroundJob:s}),u=t.babysitter??new Zl(e,void 0,void 0,o,s,a);i=t.backgroundJobDispatcher??new ep({storage:e,queue:n,handlers:BP({storage:e,babysitter:u,releaseManager:o,deploymentHealingManager:a}),onReclaimedJobs:w=>{for(let k of w)k.kind==="babysit_pr"&&e.addLog(k.targetId,"warn",`Reclaimed expired background job ${k.id} for PR ${k.targetId}`,{phase:"background.job",metadata:{jobId:k.id,kind:k.kind,leaseOwner:k.leaseOwner,leaseExpiresAt:k.leaseExpiresAt,attemptCount:k.attemptCount}}).catch(x=>{JP.warn({err:x instanceof Error?x.message:String(x)},"Failed to log reclaimed background job")})}});let c=null,l=0,p=t.watcherScheduler??HP(async()=>{await s("sync_watched_repos","runtime:1",Or("sync_watched_repos","runtime:1"))},w=>{JP.warn({err:w instanceof Error?w.message:String(w)},"Repository babysitter watcher failed")}),d=p.run,m=t.startBackgroundServices??!0,f=t.startWatcher??m,g=!1,h=()=>{r.emit("change")},T=async()=>({...await e.getRuntimeState(),activeRuns:i.getActiveRunCount()}),R=async w=>{let k=new Set,x=new Set,C=new Set,_=new Set;for(let fe of w)if(fe.kind==="babysit_pr")k.add(fe.targetId);else if(fe.kind==="answer_pr_question"){let oe=np(fe,"prId");oe&&k.add(oe)}else fe.kind==="process_release_run"?x.add(fe.targetId):fe.kind==="generate_social_changelog"?C.add(fe.targetId):fe.kind==="heal_deployment"&&_.add(fe.targetId);let[D,E,U,Z,ge]=await Promise.all([k.size>0?e.getPRs():Promise.resolve([]),k.size>0?e.getArchivedPRs():Promise.resolve([]),x.size>0?e.listReleaseRuns():Promise.resolve([]),C.size>0?e.getSocialChangelogs():Promise.resolve([]),_.size>0?e.listDeploymentHealingSessions():Promise.resolve([])]),Ee=new Map;for(let fe of ge)Ee.set(fe.id,fe),Ee.set(`${fe.repo}:${fe.mergeSha}`,fe);return{prsById:new Map([...D,...E].map(fe=>[fe.id,fe])),releaseRunsById:new Map(U.map(fe=>[fe.id,fe])),socialChangelogsById:new Map(Z.map(fe=>[fe.id,fe])),deploymentHealingSessionsByTarget:Ee}},S=(w,k)=>{let x=oP(w.payload);if(x)return x;if(w.kind==="sync_watched_repos")return{label:"Sync watched repositories",detail:null,targetUrl:null};if(w.kind==="babysit_pr"){let C=k.prsById.get(w.targetId);if(C)return{label:`Babysitting PR #${C.number}`,detail:`${C.repo} - ${C.title}`,targetUrl:C.url}}if(w.kind==="answer_pr_question"){let C=np(w,"prId"),_=C?k.prsById.get(C):void 0;if(_)return{label:`Answering question for PR #${_.number}`,detail:`${_.repo} - ${_.title}`,targetUrl:_.url}}if(w.kind==="process_release_run"){let C=k.releaseRunsById.get(w.targetId);if(C)return{label:`Processing release for ${C.repo}`,detail:`PR #${C.triggerPrNumber} - ${C.triggerPrTitle}`,targetUrl:C.triggerPrUrl}}if(w.kind==="generate_social_changelog"){let C=k.socialChangelogsById.get(w.targetId);if(C)return{label:"Social changelog generation removed",detail:`${C.date} - ${C.triggerCount} merged PRs`,targetUrl:null}}if(w.kind==="heal_deployment"){let C=k.deploymentHealingSessionsByTarget.get(w.targetId);if(C)return{label:`Healing ${C.platform} deployment`,detail:`${C.repo} PR #${C.triggerPrNumber} - ${C.triggerPrTitle}`,targetUrl:C.triggerPrUrl}}return{label:WY(w),detail:w.targetId,targetUrl:null}},P=(w,k)=>{let x=S(w,k);return{id:w.id,kind:w.kind,status:w.status==="leased"?"in_progress":w.status==="failed"?"failed":"queued",label:x.label,detail:x.detail,targetId:w.targetId,targetUrl:x.targetUrl,queuedAt:w.createdAt,availableAt:w.availableAt,startedAt:w.heartbeatAt,updatedAt:w.updatedAt,attemptCount:w.attemptCount,lastError:w.lastError}},F=(w,k)=>{if(w.kind==="babysit_pr")return k.prsById.get(w.targetId)?.status==="archived";if(w.kind==="answer_pr_question"){let x=np(w,"prId");return x?k.prsById.get(x)?.status==="archived":!1}return!1},I=(w,k)=>{let x=KP(w);if(!x)return null;let C=k.prsById.get(w.targetId);if(!C||C.status!=="error")return null;let _=x.kind==="auth"?"authentication failed":"CLI not installed",D=x.kind==="auth"?"local agent credentials are invalid or expired":"the agent CLI is not installed on this machine";return{id:w.id,severity:"warning",title:`${x.agentLabel} ${_}`,message:`Babysitter could not run ${x.agentLabel} for PR #${C.number} in ${C.repo} because ${D}.`,fixSteps:x.fixSteps,targetId:w.targetId,targetUrl:C.url,createdAt:w.createdAt,updatedAt:w.updatedAt}},A=async w=>{let[k,x,C]=await Promise.all([i.waitForIdle(w),u.waitForIdle(w),o.waitForIdle(w)]);return k&&x&&C},j=async()=>{let w=await e.getConfig(),k=Math.max(1e4,w.pollIntervalMs||12e4);c&&l===k||(c&&(clearInterval(c),c=null),l=k,c=setInterval(()=>{d()},k))},v=async(w,k)=>{await s("babysit_pr",w.id,Or("babysit_pr",w.id),{preferredAgent:k,...On({label:`Babysitting PR #${w.number}`,detail:`${w.repo} - ${w.title}`,targetUrl:w.url})})},L={async start(){g||(g=!0,m&&await i.start(),f&&(await j(),u.resumeInterruptedRuns(),d()))},stop(){g=!1,i.stop(),c&&(clearInterval(c),c=null)},subscribe(w){return r.on("change",w),()=>{r.off("change",w)}},getRuntimeSnapshot:T,async listActivities(){let[w,k,x]=await Promise.all([e.listBackgroundJobs({status:"failed"}),e.listBackgroundJobs({status:"leased"}),e.listBackgroundJobs({status:"queued"})]),C=await R([...w,...k,...x]),_=w.filter(Ee=>!F(Ee,C)),D=_.filter(Ee=>KP(Ee)),E=_.map(Ee=>P(Ee,C)),U=k.map(Ee=>P(Ee,C)),Z=x.map(Ee=>P(Ee,C)),ge=D.map(Ee=>I(Ee,C)).filter(Ee=>!!Ee).sort((Ee,fe)=>Date.parse(fe.updatedAt)-Date.parse(Ee.updatedAt)).slice(0,5);return{failed:E,inProgress:U,queued:Z,warnings:ge,generatedAt:new Date().toISOString()}},async clearFailedActivities(){let w=await e.clearFailedBackgroundJobs();return w>0&&h(),{cleared:w}},async setDrainMode(w){let k=await e.updateRuntimeState({drainMode:w.enabled,drainRequestedAt:w.enabled?new Date().toISOString():null,drainReason:w.enabled?w.reason??null:null});if(w.enabled&&w.waitForIdle){let C=await A(w.timeoutMs??12e4),_=await T();return h(),{...k,..._,drained:C}}let x=await T();return h(),{...k,...x}},async listRepos(){let w=await e.getConfig(),k=await e.getPRs();return Array.from(new Set([...w.watchedRepos,...k.map(x=>x.repo)])).sort((x,C)=>x.localeCompare(C))},async listRepoSettings(){let[w,k]=await Promise.all([e.listRepoSettings(),e.getPRs()]),x=new Map(w.map(C=>[C.repo,C]));for(let C of k)x.has(C.repo)||x.set(C.repo,{repo:C.repo,autoCreateReleases:!0,ownPrsOnly:!0});return Array.from(x.values()).sort((C,_)=>C.repo.localeCompare(_.repo))},async addRepo(w){let k=dt(w);if(!k)throw new $e(400,"Invalid repository. Use owner/repo or https://github.com/owner/repo");let x=Pn(k),C=await e.getConfig();return C.watchedRepos.includes(x)||await e.updateConfig({watchedRepos:[...C.watchedRepos,x].sort((_,D)=>_.localeCompare(D))}),d(),h(),{repo:x}},async updateRepoSettings(w,k){let x=dt(w);if(!x)throw new $e(400,"Invalid repository. Use owner/repo or https://github.com/owner/repo");let C=Pn(x),_=await e.updateRepoSettings(C,k);return h(),_},async syncRepos(){if((await e.getRuntimeState()).drainMode)throw new $e(409,"Drain mode is enabled. Sync-triggered runs are blocked until drain mode is disabled.");return await p.runAndReportErrors(),h(),{ok:!0}},async createManualRelease(w){let k=dt(w);if(!k)throw new $e(400,"Invalid repository. Use owner/repo or https://github.com/owner/repo");let x=Pn(k),C=await o.enqueueManualRepoRelease(x);if(!C)throw new $e(409,`No unreleased merged pull requests found for ${x}`);return h(),C},async listPRs(w="active"){return w==="archived"?e.getArchivedPRs():e.getPRs()},async getPR(w){return await e.getPR(w)??null},async addPR(w){let k;try{({url:k}=U_.parse({url:w}))}catch(ge){throw ge instanceof b.ZodError?new $e(400,ge.errors[0]?.message??"Invalid PR URL"):ge}let x=jl(k);if(!x)throw new $e(400,"Invalid GitHub PR URL. Expected: https://github.com/owner/repo/pull/123");let C=`${x.owner}/${x.repo}`,_=await e.getPRByRepoAndNumber(C,x.number);if(_)return _;let D=await e.getConfig(),E=await lr(D),U=await Ul(E,x),Z=await e.addPR({number:x.number,title:U.title,repo:C,branch:U.branch,author:U.author,url:U.url,status:"watching",feedbackItems:[],accepted:0,rejected:0,flagged:0,testsPassed:null,lintPassed:null,lastChecked:null});return await e.addLog(Z.id,"info",`Registered PR #${x.number} from ${C}`),await e.addLog(Z.id,"info",`Repository ${C} added to auto-babysit watch list`),D.watchedRepos.includes(C)||await e.updateConfig({watchedRepos:[...D.watchedRepos,C].sort((ge,Ee)=>ge.localeCompare(Ee))}),await v(Z,D.codingAgent),h(),Z},async removePR(w){if(!await e.removePR(w))throw new $e(404,"PR not found");return h(),{ok:!0}},async setPRWatchEnabled(w,k){let x=nt(await e.getPR(w),"PR not found"),C=await e.updatePR(x.id,{watchEnabled:k}),_=nt(C,"PR not found");return x.watchEnabled!==k&&(await e.addLog(x.id,"info",k?"Background watch resumed":"Background watch paused"),k&&d()),h(),_},async setWatchEnabled(w,k){return L.setPRWatchEnabled(w,k)},async fetchPRFeedback(w){let k=nt(await e.getPR(w),"PR not found");await e.updatePR(k.id,{status:"processing",lastChecked:new Date().toISOString()}),await e.addLog(k.id,"info","Syncing GitHub comments/reviews...");try{let x=await u.syncFeedbackForPR(k.id);return h(),x}catch(x){let C=XP(x);throw await e.updatePR(k.id,{status:"error",lastChecked:new Date().toISOString()}),await e.addLog(k.id,"error",`Fetch failed: ${C}`),x}},async triagePR(w){let k=nt(await e.getPR(w),"PR not found");await e.updatePR(k.id,{status:"processing"}),await e.addLog(k.id,"info","Triaging feedback...");let x=k.feedbackItems.map(U=>{if(U.decision)return U;let Z=U.body.toLowerCase();return Z.includes("lgtm")||Z.includes("looks good")?Ni(U,!1,"Acknowledgement, no code change requested"):Z.includes("please")||Z.includes("should")||Z.includes("fix")||Z.includes("error")||Z.includes("fail")?{...Ni(U,!0,"Likely actionable request"),action:U.body}:pP(U,"Unclear actionability, flagged for manual review")}),C=x.filter(U=>U.decision==="accept").length,_=x.filter(U=>U.decision==="reject").length,D=x.filter(U=>U.decision==="flag").length,E=await e.updatePR(k.id,{feedbackItems:x,accepted:C,rejected:_,flagged:D,status:"watching"});return await e.addLog(k.id,"info",`Triage complete: ${C} accept, ${_} reject, ${D} flag`),h(),nt(E,"PR not found")},async applyPR(w){let k=nt(await e.getPR(w),"PR not found");if((await e.getRuntimeState()).drainMode)throw new $e(409,"Drain mode is enabled. Manual runs are blocked until drain mode is disabled.");let C=await e.getConfig();await e.updatePR(k.id,{status:"processing"}),await e.addLog(k.id,"info",`Launching autonomous babysitter run using ${C.codingAgent}`),await v(k,C.codingAgent);let _=await e.getPR(k.id);return h(),nt(_,"PR disappeared after apply run")},async babysitPR(w){let k=nt(await e.getPR(w),"PR not found");if((await e.getRuntimeState()).drainMode)throw new $e(409,"Drain mode is enabled. Manual runs are blocked until drain mode is disabled.");let C=await e.getConfig();await e.addLog(k.id,"info",`Manual babysitter trigger using ${C.codingAgent}`),await v(k,C.codingAgent);let _=await e.getPR(k.id);return h(),nt(_,"PR disappeared after babysit run")},async queueBabysit(w){return L.babysitPR(w)},async setFeedbackDecision(w,k,x){let C=nt(await e.getPR(w),"PR not found"),_=await LP({storage:e,pr:C,feedbackId:k,decision:x});return h(),nt(_,"PR not found")},async retryFeedback(w,k){let x=await u.retryFeedbackItem(w,k);if(x.kind==="pr_not_found")throw new $e(404,"PR not found");if(x.kind==="feedback_not_found")throw new $e(404,"Feedback item not found");if(x.kind==="feedback_not_retryable")throw new $e(400,"Only failed or warning items can be retried");await e.addLog(w,"info",`Feedback item ${k} queued for retry`);let C=await e.getConfig();return await v(x.updated,C.codingAgent),h(),x.updated},async listPRQuestions(w){return nt(await e.getPR(w),"PR not found"),e.getQuestions(w)},async askQuestion(w,k){let x=nt(await e.getPR(w),"PR not found"),C;try{C=H_.parse({question:k})}catch(D){throw D instanceof b.ZodError?new $e(400,D.errors[0]?.message??"Invalid question"):D}let _=await e.addQuestion(w,C.question);try{await s("answer_pr_question",_.id,Or("answer_pr_question",_.id),{prId:w,...On({label:`Answering question for PR #${x.number}`,detail:`${x.repo} - ${x.title}`,targetUrl:x.url})})}catch(D){let E=XP(D);throw await e.updateQuestion(_.id,{status:"error",error:E.trim().slice(0,2e3)}),D}return h(),_},async listLogs(w){return e.getLogs(w)},async getOnboardingStatus(){let w=await e.getConfig();return S4(w,w.watchedRepos)},async installReviewWorkflow(w,k){let x=await e.getConfig();return k4(x,w,k)},async listHealingSessions(){return e.listHealingSessions()},async getHealingSession(w){return nt(await e.getHealingSession(w),"Healing session not found")},async listDeploymentHealingSessions(w){return e.listDeploymentHealingSessions(w?{repo:w}:void 0)},async getDeploymentHealingSession(w){return nt(await e.getDeploymentHealingSession(w),"Deployment healing session not found")},async getConfig(){return e.getConfig()},async updateConfig(w){let k=await e.updateConfig(w);return f&&g&&await j(),h(),k},async listSocialChangelogs(){return e.getSocialChangelogs()},async getSocialChangelog(w){return nt(await e.getSocialChangelog(w),"Changelog not found")},async listReleaseRuns(){return e.listReleaseRuns()},async getReleaseRun(w){return nt(await e.getReleaseRun(w),"Release run not found")},async retryReleaseRun(w){let k=await o.retryReleaseRun(w);if(!k)throw new $e(404,"Release run not found");return h(),k}};return L}function eC(t){return t instanceof $e}var tC="https://github.com/yungookim/oh-my-pr/releases",XY="https://api.github.com/repos/yungookim/oh-my-pr/releases/latest",KY=3600*1e3;function QY(t,e){let r=Ii(t),n=Ii(e);return!r||!n?0:r.major!==n.major?r.major-n.major:r.minor!==n.minor?r.minor-n.minor:r.patch-n.patch}function YY(t){return{currentVersion:t,latestVersion:null,latestReleaseUrl:tC,updateAvailable:!1}}async function ZY(t,e=fetch){let r=t.trim(),n=YY(r);if(!Ii(r))return n;try{let i=await e(XY,{headers:{accept:"application/vnd.github+json","user-agent":`oh-my-pr/${r}`}});if(!i.ok)return n;let s=await i.json(),a=s.tag_name?.trim()??null;return s.draft||s.prerelease||!a||!Ii(a)?n:{currentVersion:r,latestVersion:a,latestReleaseUrl:s.html_url?.trim()||tC,updateAvailable:QY(a,r)>0}}catch{return n}}function rC(t=fetch,e={}){let r=e.cacheTtlMs??KY,n=e.now??Date.now,i=new Map,s=new Map;return async a=>{let o=a.trim(),u=i.get(o);if(u&&u.expiresAt>n())return u.status;let c=s.get(o);if(c)return c;let l=ZY(o,t).then(p=>(i.set(o,{status:p,expiresAt:n()+r}),s.delete(o),p),p=>{throw s.delete(o),p});return s.set(o,l),l}}var iC="***";function eZ(t){return t instanceof Error?t.message:String(t)}function ve(t,e){if(e instanceof b.ZodError){t.status(400).json({error:e.errors[0]?.message??"Invalid request"});return}if(e instanceof Me){t.status(e.statusCode).json({error:e.message});return}if(eC(e)){t.status(e.statusCode).json({error:e.message});return}t.status(500).json({error:eZ(e)})}function sC(t){return t?`${iC}${t.slice(-4)}`:""}function tZ(t,e){let r=t.map(n=>({token:n,masked:sC(n),used:!1}));return e.map(n=>{let i=n.trim();if(!i)return"";if(i.startsWith(iC)){let s=r.find(a=>!a.used&&a.masked===i);if(s)return s.used=!0,s.token}return i}).filter(Boolean)}function rZ(t,e){let r=e.githubTokens??(e.githubToken!==void 0?[e.githubToken]:void 0);if(r===void 0)return e;let{githubToken:n,...i}=e;return{...i,githubTokens:tZ(t.githubTokens,r)}}function nC(t){let e=t.githubTokens.map(sC);return{...t,githubTokens:e,githubToken:e[0]??""}}async function aC(t,e,r={}){let n=r.runtime??ZP(r),i=r.appUpdateChecker??rC();return await n.start(),t.on("close",()=>{n.stop()}),e.get("/api/runtime",async(s,a)=>{a.json(await n.getRuntimeSnapshot())}),e.get("/api/activities",async(s,a)=>{a.json(await n.listActivities())}),e.delete("/api/activities/failed",async(s,a)=>{try{a.json(await n.clearFailedActivities())}catch(o){ve(a,o)}}),e.post("/api/runtime/drain",async(s,a)=>{try{let o=b.object({enabled:b.boolean(),reason:b.string().optional(),waitForIdle:b.boolean().optional(),timeoutMs:b.number().int().positive().max(6e5).optional()}).parse(s.body),u=await n.setDrainMode(o);if(o.enabled&&o.waitForIdle&&u.drained===!1)return a.status(202).json(u);a.json(u)}catch(o){ve(a,o)}}),e.get("/api/repos",async(s,a)=>{a.json(await n.listRepos())}),e.get("/api/repos/settings",async(s,a)=>{a.json(await n.listRepoSettings())}),e.post("/api/repos",async(s,a)=>{try{let{repo:o}=b.object({repo:b.string().min(1)}).parse(s.body);a.status(201).json(await n.addRepo(o))}catch(o){ve(a,o)}}),e.patch("/api/repos/settings",async(s,a)=>{try{let o=b.object({repo:b.string().min(1),autoCreateReleases:b.boolean().optional(),ownPrsOnly:b.boolean().optional()}).refine(l=>l.autoCreateReleases!==void 0||l.ownPrsOnly!==void 0,"At least one repository setting must be provided").parse(s.body),{repo:u,...c}=o;a.json(await n.updateRepoSettings(u,c))}catch(o){ve(a,o)}}),e.post("/api/repos/sync",async(s,a)=>{try{a.json(await n.syncRepos())}catch(o){ve(a,o)}}),e.post("/api/repos/release",async(s,a)=>{try{let{repo:o}=b.object({repo:b.string().min(1)}).parse(s.body);a.status(201).json(await n.createManualRelease(o))}catch(o){ve(a,o)}}),e.get("/api/prs",async(s,a)=>{a.json(await n.listPRs("active"))}),e.get("/api/prs/archived",async(s,a)=>{a.json(await n.listPRs("archived"))}),e.get("/api/prs/:id",async(s,a)=>{let o=await n.getPR(s.params.id);if(!o)return a.status(404).json({error:"PR not found"});a.json(o)}),e.post("/api/prs",async(s,a)=>{try{a.status(201).json(await n.addPR(s.body?.url))}catch(o){ve(a,o)}}),e.delete("/api/prs/:id",async(s,a)=>{try{a.json(await n.removePR(s.params.id))}catch(o){ve(a,o)}}),e.patch("/api/prs/:id/watch",async(s,a)=>{try{let{enabled:o}=b.object({enabled:b.boolean()}).parse(s.body);a.json(await n.setPRWatchEnabled(s.params.id,o))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/fetch",async(s,a)=>{try{a.json(await n.fetchPRFeedback(s.params.id))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/triage",async(s,a)=>{try{a.json(await n.triagePR(s.params.id))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/apply",async(s,a)=>{try{a.json(await n.applyPR(s.params.id))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/babysit",async(s,a)=>{try{a.json(await n.babysitPR(s.params.id))}catch(o){ve(a,o)}}),e.patch("/api/prs/:id/feedback/:feedbackId",async(s,a)=>{try{let{decision:o}=b.object({decision:b.enum(["accept","reject","flag"])}).parse(s.body);a.json(await n.setFeedbackDecision(s.params.id,s.params.feedbackId,o))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/feedback/:feedbackId/retry",async(s,a)=>{try{a.json(await n.retryFeedback(s.params.id,s.params.feedbackId))}catch(o){ve(a,o)}}),e.get("/api/prs/:id/questions",async(s,a)=>{try{a.json(await n.listPRQuestions(s.params.id))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/questions",async(s,a)=>{try{a.status(201).json(await n.askQuestion(s.params.id,s.body?.question))}catch(o){ve(a,o)}}),e.get("/api/logs",async(s,a)=>{let o=typeof s.query.prId=="string"?s.query.prId:void 0;a.json(await n.listLogs(o))}),e.get("/api/onboarding/status",async(s,a)=>{try{a.json(await n.getOnboardingStatus())}catch(o){ve(a,o)}}),e.post("/api/onboarding/install-review",async(s,a)=>{try{let{repo:o,tool:u}=b.object({repo:b.string().min(1),tool:b.enum(["claude","codex"])}).parse(s.body);a.json(await n.installReviewWorkflow(o,u))}catch(o){ve(a,o)}}),e.get("/api/healing-sessions",async(s,a)=>{try{a.json(await n.listHealingSessions())}catch(o){ve(a,o)}}),e.get("/api/healing-sessions/:id",async(s,a)=>{try{a.json(await n.getHealingSession(s.params.id))}catch(o){ve(a,o)}}),e.get("/api/deployment-healing-sessions",async(s,a)=>{try{let o=typeof s.query.repo=="string"?s.query.repo:void 0;a.json(await n.listDeploymentHealingSessions(o))}catch(o){ve(a,o)}}),e.get("/api/deployment-healing-sessions/:id",async(s,a)=>{try{a.json(await n.getDeploymentHealingSession(s.params.id))}catch(o){ve(a,o)}}),e.get("/api/config",async(s,a)=>{a.json(nC(await n.getConfig()))}),e.get("/api/app-update",async(s,a)=>{try{a.json(await i("4.2.1"))}catch(o){ve(a,o)}}),e.get("/api/changelogs",async(s,a)=>{try{a.json(await n.listSocialChangelogs())}catch(o){ve(a,o)}}),e.get("/api/changelogs/:id",async(s,a)=>{try{a.json(await n.getSocialChangelog(s.params.id))}catch(o){ve(a,o)}}),e.get("/api/releases",async(s,a)=>{try{a.json(await n.listReleaseRuns())}catch(o){ve(a,o)}}),e.get("/api/releases/:id",async(s,a)=>{try{a.json(await n.getReleaseRun(s.params.id))}catch(o){ve(a,o)}}),e.post("/api/releases/:id/retry",async(s,a)=>{try{a.json(await n.retryReleaseRun(s.params.id))}catch(o){ve(a,o)}}),e.patch("/api/config",async(s,a)=>{try{let o=ic.partial().parse(s.body),u=await n.getConfig();a.json(nC(await n.updateConfig(rZ(u,o))))}catch(o){ve(a,o)}}),t}var oC=qe(Sf(),1),uC=qe(require("fs"),1),q0=qe(require("path"),1);function cC(t){let e=q0.default.resolve(__dirname,"public");if(!uC.default.existsSync(e))throw new Error(`Could not find the build directory: ${e}, make sure to build the client first`);t.use(oC.default.static(e)),t.use("/{*path}",(r,n)=>{n.sendFile(q0.default.resolve(e,"index.html"))})}var nZ=new Set(["127.0.0.1","::1","::ffff:127.0.0.1","localhost"]);function iZ(t){if(!t)return!1;let e=t.replace(/^\[|\]$/g,"");return nZ.has(e)?!0:e.startsWith("::ffff:")?e.slice(7).startsWith("127."):!!e.startsWith("127.")}function lC(t,e,r){let n=t.ip??t.socket?.remoteAddress;if(!iZ(n)){e.status(403).json({error:"Forbidden",message:"oh-my-pr only accepts connections from the local machine. External access is not permitted."});return}r()}var dC=require("http");var sZ=zt("server"),Gi=(0,ip.default)(),pC=(0,dC.createServer)(Gi);Gi.use(ip.default.json({verify:(t,e,r)=>{t.rawBody=r}}));Gi.use(ip.default.urlencoded({extended:!1}));Gi.use("/api",lC);function fC(t,e="express"){Jg.info({source:e},t)}async function aZ(t){let{default:e}=await import("open");await e(t)}(async()=>{await aC(pC,Gi),Gi.use((e,r,n,i)=>{let s=e,a=s.status||s.statusCode||500,o=s.message||"Internal Server Error";return sZ.error({err:e instanceof Error?e.message:String(e),status:a},"Internal Server Error"),n.headersSent?i(e):n.status(a).json({message:o})}),cC(Gi);let t=parseInt(process.env.PORT||"5001",10);pC.listen({port:t,host:"0.0.0.0"},()=>{let e=`http://localhost:${t}`;console.log(`
|
|
1083
|
-
oh-my-pr v4.
|
|
1082
|
+
`):"- Manual release requested."}`}function BY(t){return(t instanceof Error?t.message:String(t)).trim().slice(0,2e3)}function VP(t){return t==="skipped"||t==="published"}function HY(t){return new Promise(e=>setTimeout(e,t))}var $Y=["fix_submitted","escalated"],zY={monitoring:["failed","escalated"],failed:["fixing","escalated"],fixing:["fix_submitted","escalated"],fix_submitted:[],escalated:[]},rp=class{constructor(e,r=()=>new Date){this.storage=e;this.clock=r}async createSession(e){return this.storage.createDeploymentHealingSession({...e,deploymentId:null,deploymentLog:null,fixBranch:null,fixPrNumber:null,fixPrUrl:null,state:"monitoring",error:null,completedAt:null})}async ensureSession(e){let r=await this.storage.getDeploymentHealingSessionByRepoAndMergeSha(e.repo,e.mergeSha);return r||this.createSession(e)}async transitionTo(e,r,n={}){let i=await this.storage.getDeploymentHealingSession(e);if(!i)throw new Error(`Deployment healing session not found: ${e}`);if(i.state===r){let o=await this.storage.updateDeploymentHealingSession(e,n);if(!o)throw new Error(`Deployment healing session not found: ${e}`);return o}if(!zY[i.state].includes(r))throw new Error(`Illegal deployment healing transition: ${i.state} -> ${r}`);let s={...n,state:r};$Y.includes(r)&&(s.completedAt=n.completedAt??this.clock().toISOString());let a=await this.storage.updateDeploymentHealingSession(e,s);if(!a)throw new Error(`Deployment healing session not found: ${e}`);return a}};var JP=zt("runtime"),$e=class extends Error{statusCode;constructor(e,r){super(r),this.name="AppRuntimeError",this.statusCode=e}};function XP(t){return t instanceof Error?t.message:String(t)}function it(t,e){if(t===void 0)throw new $e(404,e);return t}function WY(t){switch(t.kind){case"sync_watched_repos":return"Sync watched repositories";case"babysit_pr":return"Babysitting PR";case"process_release_run":return"Processing release";case"answer_pr_question":return"Answering PR question";case"generate_social_changelog":return"Social changelog generation removed";case"heal_deployment":return"Healing deployment"}}function np(t,e){let r=t.payload[e];return typeof r=="string"&&r.trim()?r:null}var VY={Claude:{auth:["Run `claude auth login` on this machine.","Restart oh-my-pr if it was launched before you refreshed credentials.","Rerun the babysitter for this PR."],cli_missing:["Install the Claude Code CLI on this machine.","Restart oh-my-pr after installing.","Rerun the babysitter for this PR."]},Codex:{auth:["Run `codex login` on this machine.","Restart oh-my-pr if it was launched before you refreshed credentials.","Rerun the babysitter for this PR."],cli_missing:["Install the Codex CLI on this machine.","Restart oh-my-pr after installing.","Rerun the babysitter for this PR."]}};function j0(t,e){return{agentLabel:t,kind:e,fixSteps:VY[t][e]}}function JY(t){let e=t.toLowerCase();return e.includes("claude evaluation failed")||e.includes("claude apply failed")?"Claude":e.includes("codex evaluation failed")||e.includes("codex apply failed")?"Codex":null}function KP(t){if(t.kind!=="babysit_pr"||!t.lastError)return null;let e=lm(t.lastError);if(!e)return null;let r=JY(t.lastError);if(r)return j0(r,e);let n=np(t,"preferredAgent");return n==="claude"?j0("Claude",e):n==="codex"?j0("Codex",e):null}function QP(t){return t.flatMap(e=>{let r=e.mergeCommitSha?.trim();return r?[{number:e.number,title:e.title,url:e.url,author:e.author,repo:e.repo,mergedAt:e.mergedAt,mergeSha:r}]:[]})}function ZP(t={}){let e=t.storage??Q_(),r=new YP.EventEmitter,n=t.backgroundJobQueue??new Xl(e),i,s=async(...w)=>{let k=await n.enqueue(...w);return i.wake(),k},a=t.deploymentHealingManager??new rp(e),o=t.releaseManager??new tp(e,{github:{buildOctokit:lr,getDefaultBranch:E0,findLatestSemverReleaseTag:P4,bumpReleaseTag:A4,listUnreleasedMergedPulls:async(w,k,x)=>{let C=await T0(w,k,{baseRef:x.baseBranch});return QP(C)},listMergedPullsForReleaseCandidate:async(w,k,x)=>{let C=await T0(w,k,{baseRef:x.baseBranch}),_=Date.parse(x.untilMergedAt);return QP(C.filter(D=>!Number.isFinite(_)||Date.parse(D.mergedAt)<=_))},findReleaseByTag:async(w,k,x)=>{let _=(await Gl(w,k)).find(D=>!D.draft&&D.tagName===x);return _?{id:_.id,url:_.htmlUrl,tagName:_.tagName,name:_.name}:null},createGitHubRelease:async(w,k,x)=>{let C=await C4(w,k,{tagName:x.tagName,targetCommitish:x.targetCommitish,name:x.name,body:x.body});return{id:C.id,url:C.htmlUrl,tagName:C.tagName,name:C.name}}},scheduleBackgroundJob:s}),u=t.babysitter??new Zl(e,void 0,void 0,o,s,a);i=t.backgroundJobDispatcher??new ep({storage:e,queue:n,handlers:BP({storage:e,babysitter:u,releaseManager:o,deploymentHealingManager:a}),onReclaimedJobs:w=>{for(let k of w)k.kind==="babysit_pr"&&e.addLog(k.targetId,"warn",`Reclaimed expired background job ${k.id} for PR ${k.targetId}`,{phase:"background.job",metadata:{jobId:k.id,kind:k.kind,leaseOwner:k.leaseOwner,leaseExpiresAt:k.leaseExpiresAt,attemptCount:k.attemptCount}}).catch(x=>{JP.warn({err:x instanceof Error?x.message:String(x)},"Failed to log reclaimed background job")})}});let c=null,l=0,p=t.watcherScheduler??HP(async()=>{await s("sync_watched_repos","runtime:1",Or("sync_watched_repos","runtime:1"))},w=>{JP.warn({err:w instanceof Error?w.message:String(w)},"Repository babysitter watcher failed")}),d=p.run,m=t.startBackgroundServices??!0,f=t.startWatcher??m,g=!1,h=()=>{r.emit("change")},T=async()=>({...await e.getRuntimeState(),activeRuns:i.getActiveRunCount()}),R=async w=>{let k=new Set,x=new Set,C=new Set,_=new Set;for(let fe of w)if(fe.kind==="babysit_pr")k.add(fe.targetId);else if(fe.kind==="answer_pr_question"){let oe=np(fe,"prId");oe&&k.add(oe)}else fe.kind==="process_release_run"?x.add(fe.targetId):fe.kind==="generate_social_changelog"?C.add(fe.targetId):fe.kind==="heal_deployment"&&_.add(fe.targetId);let[D,E,U,Z,ge]=await Promise.all([k.size>0?e.getPRs():Promise.resolve([]),k.size>0?e.getArchivedPRs():Promise.resolve([]),x.size>0?e.listReleaseRuns():Promise.resolve([]),C.size>0?e.getSocialChangelogs():Promise.resolve([]),_.size>0?e.listDeploymentHealingSessions():Promise.resolve([])]),Ee=new Map;for(let fe of ge)Ee.set(fe.id,fe),Ee.set(`${fe.repo}:${fe.mergeSha}`,fe);return{prsById:new Map([...D,...E].map(fe=>[fe.id,fe])),releaseRunsById:new Map(U.map(fe=>[fe.id,fe])),socialChangelogsById:new Map(Z.map(fe=>[fe.id,fe])),deploymentHealingSessionsByTarget:Ee}},S=(w,k)=>{let x=oP(w.payload);if(x)return x;if(w.kind==="sync_watched_repos")return{label:"Sync watched repositories",detail:null,targetUrl:null};if(w.kind==="babysit_pr"){let C=k.prsById.get(w.targetId);if(C)return{label:`Babysitting PR #${C.number}`,detail:`${C.repo} - ${C.title}`,targetUrl:C.url}}if(w.kind==="answer_pr_question"){let C=np(w,"prId"),_=C?k.prsById.get(C):void 0;if(_)return{label:`Answering question for PR #${_.number}`,detail:`${_.repo} - ${_.title}`,targetUrl:_.url}}if(w.kind==="process_release_run"){let C=k.releaseRunsById.get(w.targetId);if(C)return{label:`Processing release for ${C.repo}`,detail:`PR #${C.triggerPrNumber} - ${C.triggerPrTitle}`,targetUrl:C.triggerPrUrl}}if(w.kind==="generate_social_changelog"){let C=k.socialChangelogsById.get(w.targetId);if(C)return{label:"Social changelog generation removed",detail:`${C.date} - ${C.triggerCount} merged PRs`,targetUrl:null}}if(w.kind==="heal_deployment"){let C=k.deploymentHealingSessionsByTarget.get(w.targetId);if(C)return{label:`Healing ${C.platform} deployment`,detail:`${C.repo} PR #${C.triggerPrNumber} - ${C.triggerPrTitle}`,targetUrl:C.triggerPrUrl}}return{label:WY(w),detail:w.targetId,targetUrl:null}},P=(w,k)=>{let x=S(w,k);return{id:w.id,kind:w.kind,status:w.status==="leased"?"in_progress":w.status==="failed"?"failed":"queued",label:x.label,detail:x.detail,targetId:w.targetId,targetUrl:x.targetUrl,queuedAt:w.createdAt,availableAt:w.availableAt,startedAt:w.heartbeatAt,updatedAt:w.updatedAt,attemptCount:w.attemptCount,lastError:w.lastError}},F=(w,k)=>{if(w.kind==="babysit_pr")return k.prsById.get(w.targetId)?.status==="archived";if(w.kind==="answer_pr_question"){let x=np(w,"prId");return x?k.prsById.get(x)?.status==="archived":!1}return!1},I=(w,k)=>{let x=KP(w);if(!x)return null;let C=k.prsById.get(w.targetId);if(!C||C.status!=="error")return null;let _=x.kind==="auth"?"authentication failed":"CLI not installed",D=x.kind==="auth"?"local agent credentials are invalid or expired":"the agent CLI is not installed on this machine";return{id:w.id,severity:"warning",title:`${x.agentLabel} ${_}`,message:`Babysitter could not run ${x.agentLabel} for PR #${C.number} in ${C.repo} because ${D}.`,fixSteps:x.fixSteps,targetId:w.targetId,targetUrl:C.url,createdAt:w.createdAt,updatedAt:w.updatedAt}},A=async w=>{let[k,x,C]=await Promise.all([i.waitForIdle(w),u.waitForIdle(w),o.waitForIdle(w)]);return k&&x&&C},j=async()=>{let w=await e.getConfig(),k=Math.max(1e4,w.pollIntervalMs||12e4);c&&l===k||(c&&(clearInterval(c),c=null),l=k,c=setInterval(()=>{d()},k))},v=async(w,k)=>{await s("babysit_pr",w.id,Or("babysit_pr",w.id),{preferredAgent:k,...On({label:`Babysitting PR #${w.number}`,detail:`${w.repo} - ${w.title}`,targetUrl:w.url})})},L={async start(){g||(g=!0,m&&await i.start(),f&&(await j(),u.resumeInterruptedRuns(),d()))},stop(){g=!1,i.stop(),c&&(clearInterval(c),c=null)},subscribe(w){return r.on("change",w),()=>{r.off("change",w)}},getRuntimeSnapshot:T,async listActivities(){let[w,k,x]=await Promise.all([e.listBackgroundJobs({status:"failed"}),e.listBackgroundJobs({status:"leased"}),e.listBackgroundJobs({status:"queued"})]),C=await R([...w,...k,...x]),_=w.filter(Ee=>!F(Ee,C)),D=_.filter(Ee=>KP(Ee)),E=_.map(Ee=>P(Ee,C)),U=k.map(Ee=>P(Ee,C)),Z=x.map(Ee=>P(Ee,C)),ge=D.map(Ee=>I(Ee,C)).filter(Ee=>!!Ee).sort((Ee,fe)=>Date.parse(fe.updatedAt)-Date.parse(Ee.updatedAt)).slice(0,5);return{failed:E,inProgress:U,queued:Z,warnings:ge,generatedAt:new Date().toISOString()}},async clearFailedActivities(){let w=await e.clearFailedBackgroundJobs();return w>0&&h(),{cleared:w}},async setDrainMode(w){let k=await e.updateRuntimeState({drainMode:w.enabled,drainRequestedAt:w.enabled?new Date().toISOString():null,drainReason:w.enabled?w.reason??null:null});if(w.enabled&&w.waitForIdle){let C=await A(w.timeoutMs??12e4),_=await T();return h(),{...k,..._,drained:C}}let x=await T();return h(),{...k,...x}},async listRepos(){let w=await e.getConfig(),k=await e.getPRs();return Array.from(new Set([...w.watchedRepos,...k.map(x=>x.repo)])).sort((x,C)=>x.localeCompare(C))},async listRepoSettings(){let[w,k]=await Promise.all([e.listRepoSettings(),e.getPRs()]),x=new Map(w.map(C=>[C.repo,C]));for(let C of k)x.has(C.repo)||x.set(C.repo,{repo:C.repo,autoCreateReleases:!1,ownPrsOnly:!0});return Array.from(x.values()).sort((C,_)=>C.repo.localeCompare(_.repo))},async addRepo(w){let k=dt(w);if(!k)throw new $e(400,"Invalid repository. Use owner/repo or https://github.com/owner/repo");let x=Pn(k),C=await e.getConfig();return C.watchedRepos.includes(x)||await e.updateConfig({watchedRepos:[...C.watchedRepos,x].sort((_,D)=>_.localeCompare(D))}),d(),h(),{repo:x}},async updateRepoSettings(w,k){let x=dt(w);if(!x)throw new $e(400,"Invalid repository. Use owner/repo or https://github.com/owner/repo");let C=Pn(x),_=await e.updateRepoSettings(C,k);return h(),_},async syncRepos(){if((await e.getRuntimeState()).drainMode)throw new $e(409,"Drain mode is enabled. Sync-triggered runs are blocked until drain mode is disabled.");return await p.runAndReportErrors(),h(),{ok:!0}},async createManualRelease(w){let k=dt(w);if(!k)throw new $e(400,"Invalid repository. Use owner/repo or https://github.com/owner/repo");let x=Pn(k),C=await o.enqueueManualRepoRelease(x);if(!C)throw new $e(409,`No unreleased merged pull requests found for ${x}`);return h(),C},async listPRs(w="active"){return w==="archived"?e.getArchivedPRs():e.getPRs()},async getPR(w){return await e.getPR(w)??null},async addPR(w){let k;try{({url:k}=U_.parse({url:w}))}catch(ge){throw ge instanceof b.ZodError?new $e(400,ge.errors[0]?.message??"Invalid PR URL"):ge}let x=jl(k);if(!x)throw new $e(400,"Invalid GitHub PR URL. Expected: https://github.com/owner/repo/pull/123");let C=`${x.owner}/${x.repo}`,_=await e.getPRByRepoAndNumber(C,x.number);if(_)return _;let D=await e.getConfig(),E=await lr(D),U=await Ul(E,x),Z=await e.addPR({number:x.number,title:U.title,repo:C,branch:U.branch,author:U.author,url:U.url,status:"watching",feedbackItems:[],accepted:0,rejected:0,flagged:0,testsPassed:null,lintPassed:null,lastChecked:null});return await e.addLog(Z.id,"info",`Registered PR #${x.number} from ${C}`),await e.addLog(Z.id,"info",`Repository ${C} added to auto-babysit watch list`),D.watchedRepos.includes(C)||await e.updateConfig({watchedRepos:[...D.watchedRepos,C].sort((ge,Ee)=>ge.localeCompare(Ee))}),await v(Z,D.codingAgent),h(),Z},async removePR(w){if(!await e.removePR(w))throw new $e(404,"PR not found");return h(),{ok:!0}},async setPRWatchEnabled(w,k){let x=it(await e.getPR(w),"PR not found"),C=await e.updatePR(x.id,{watchEnabled:k}),_=it(C,"PR not found");return x.watchEnabled!==k&&(await e.addLog(x.id,"info",k?"Background watch resumed":"Background watch paused"),k&&d()),h(),_},async setWatchEnabled(w,k){return L.setPRWatchEnabled(w,k)},async fetchPRFeedback(w){let k=it(await e.getPR(w),"PR not found");await e.updatePR(k.id,{status:"processing",lastChecked:new Date().toISOString()}),await e.addLog(k.id,"info","Syncing GitHub comments/reviews...");try{let x=await u.syncFeedbackForPR(k.id);return h(),x}catch(x){let C=XP(x);throw await e.updatePR(k.id,{status:"error",lastChecked:new Date().toISOString()}),await e.addLog(k.id,"error",`Fetch failed: ${C}`),x}},async triagePR(w){let k=it(await e.getPR(w),"PR not found");await e.updatePR(k.id,{status:"processing"}),await e.addLog(k.id,"info","Triaging feedback...");let x=k.feedbackItems.map(U=>{if(U.decision)return U;let Z=U.body.toLowerCase();return Z.includes("lgtm")||Z.includes("looks good")?Ni(U,!1,"Acknowledgement, no code change requested"):Z.includes("please")||Z.includes("should")||Z.includes("fix")||Z.includes("error")||Z.includes("fail")?{...Ni(U,!0,"Likely actionable request"),action:U.body}:pP(U,"Unclear actionability, flagged for manual review")}),C=x.filter(U=>U.decision==="accept").length,_=x.filter(U=>U.decision==="reject").length,D=x.filter(U=>U.decision==="flag").length,E=await e.updatePR(k.id,{feedbackItems:x,accepted:C,rejected:_,flagged:D,status:"watching"});return await e.addLog(k.id,"info",`Triage complete: ${C} accept, ${_} reject, ${D} flag`),h(),it(E,"PR not found")},async applyPR(w){let k=it(await e.getPR(w),"PR not found");if((await e.getRuntimeState()).drainMode)throw new $e(409,"Drain mode is enabled. Manual runs are blocked until drain mode is disabled.");let C=await e.getConfig();await e.updatePR(k.id,{status:"processing"}),await e.addLog(k.id,"info",`Launching autonomous babysitter run using ${C.codingAgent}`),await v(k,C.codingAgent);let _=await e.getPR(k.id);return h(),it(_,"PR disappeared after apply run")},async babysitPR(w){let k=it(await e.getPR(w),"PR not found");if((await e.getRuntimeState()).drainMode)throw new $e(409,"Drain mode is enabled. Manual runs are blocked until drain mode is disabled.");let C=await e.getConfig();await e.addLog(k.id,"info",`Manual babysitter trigger using ${C.codingAgent}`),await v(k,C.codingAgent);let _=await e.getPR(k.id);return h(),it(_,"PR disappeared after babysit run")},async queueBabysit(w){return L.babysitPR(w)},async setFeedbackDecision(w,k,x){let C=it(await e.getPR(w),"PR not found"),_=await LP({storage:e,pr:C,feedbackId:k,decision:x});return h(),it(_,"PR not found")},async retryFeedback(w,k){let x=await u.retryFeedbackItem(w,k);if(x.kind==="pr_not_found")throw new $e(404,"PR not found");if(x.kind==="feedback_not_found")throw new $e(404,"Feedback item not found");if(x.kind==="feedback_not_retryable")throw new $e(400,"Only failed or warning items can be retried");await e.addLog(w,"info",`Feedback item ${k} queued for retry`);let C=await e.getConfig();return await v(x.updated,C.codingAgent),h(),x.updated},async listPRQuestions(w){return it(await e.getPR(w),"PR not found"),e.getQuestions(w)},async askQuestion(w,k){let x=it(await e.getPR(w),"PR not found"),C;try{C=H_.parse({question:k})}catch(D){throw D instanceof b.ZodError?new $e(400,D.errors[0]?.message??"Invalid question"):D}let _=await e.addQuestion(w,C.question);try{await s("answer_pr_question",_.id,Or("answer_pr_question",_.id),{prId:w,...On({label:`Answering question for PR #${x.number}`,detail:`${x.repo} - ${x.title}`,targetUrl:x.url})})}catch(D){let E=XP(D);throw await e.updateQuestion(_.id,{status:"error",error:E.trim().slice(0,2e3)}),D}return h(),_},async listLogs(w){return e.getLogs(w)},async getOnboardingStatus(){let w=await e.getConfig();return S4(w,w.watchedRepos)},async installReviewWorkflow(w,k){let x=await e.getConfig();return k4(x,w,k)},async listHealingSessions(){return e.listHealingSessions()},async getHealingSession(w){return it(await e.getHealingSession(w),"Healing session not found")},async listDeploymentHealingSessions(w){return e.listDeploymentHealingSessions(w?{repo:w}:void 0)},async getDeploymentHealingSession(w){return it(await e.getDeploymentHealingSession(w),"Deployment healing session not found")},async getConfig(){return e.getConfig()},async updateConfig(w){let k=await e.updateConfig(w);return f&&g&&await j(),h(),k},async listSocialChangelogs(){return e.getSocialChangelogs()},async getSocialChangelog(w){return it(await e.getSocialChangelog(w),"Changelog not found")},async listReleaseRuns(){return e.listReleaseRuns()},async getReleaseRun(w){return it(await e.getReleaseRun(w),"Release run not found")},async retryReleaseRun(w){let k=await o.retryReleaseRun(w);if(!k)throw new $e(404,"Release run not found");return h(),k}};return L}function eC(t){return t instanceof $e}var tC="https://github.com/yungookim/oh-my-pr/releases",XY="https://api.github.com/repos/yungookim/oh-my-pr/releases/latest",KY=3600*1e3;function QY(t,e){let r=Ii(t),n=Ii(e);return!r||!n?0:r.major!==n.major?r.major-n.major:r.minor!==n.minor?r.minor-n.minor:r.patch-n.patch}function YY(t){return{currentVersion:t,latestVersion:null,latestReleaseUrl:tC,updateAvailable:!1}}async function ZY(t,e=fetch){let r=t.trim(),n=YY(r);if(!Ii(r))return n;try{let i=await e(XY,{headers:{accept:"application/vnd.github+json","user-agent":`oh-my-pr/${r}`}});if(!i.ok)return n;let s=await i.json(),a=s.tag_name?.trim()??null;return s.draft||s.prerelease||!a||!Ii(a)?n:{currentVersion:r,latestVersion:a,latestReleaseUrl:s.html_url?.trim()||tC,updateAvailable:QY(a,r)>0}}catch{return n}}function rC(t=fetch,e={}){let r=e.cacheTtlMs??KY,n=e.now??Date.now,i=new Map,s=new Map;return async a=>{let o=a.trim(),u=i.get(o);if(u&&u.expiresAt>n())return u.status;let c=s.get(o);if(c)return c;let l=ZY(o,t).then(p=>(i.set(o,{status:p,expiresAt:n()+r}),s.delete(o),p),p=>{throw s.delete(o),p});return s.set(o,l),l}}var iC="***";function eZ(t){return t instanceof Error?t.message:String(t)}function ve(t,e){if(e instanceof b.ZodError){t.status(400).json({error:e.errors[0]?.message??"Invalid request"});return}if(e instanceof Me){t.status(e.statusCode).json({error:e.message});return}if(eC(e)){t.status(e.statusCode).json({error:e.message});return}t.status(500).json({error:eZ(e)})}function sC(t){return t?`${iC}${t.slice(-4)}`:""}function tZ(t,e){let r=t.map(n=>({token:n,masked:sC(n),used:!1}));return e.map(n=>{let i=n.trim();if(!i)return"";if(i.startsWith(iC)){let s=r.find(a=>!a.used&&a.masked===i);if(s)return s.used=!0,s.token}return i}).filter(Boolean)}function rZ(t,e){let r=e.githubTokens??(e.githubToken!==void 0?[e.githubToken]:void 0);if(r===void 0)return e;let{githubToken:n,...i}=e;return{...i,githubTokens:tZ(t.githubTokens,r)}}function nC(t){let e=t.githubTokens.map(sC);return{...t,githubTokens:e,githubToken:e[0]??""}}async function aC(t,e,r={}){let n=r.runtime??ZP(r),i=r.appUpdateChecker??rC();return await n.start(),t.on("close",()=>{n.stop()}),e.get("/api/runtime",async(s,a)=>{a.json(await n.getRuntimeSnapshot())}),e.get("/api/activities",async(s,a)=>{a.json(await n.listActivities())}),e.delete("/api/activities/failed",async(s,a)=>{try{a.json(await n.clearFailedActivities())}catch(o){ve(a,o)}}),e.post("/api/runtime/drain",async(s,a)=>{try{let o=b.object({enabled:b.boolean(),reason:b.string().optional(),waitForIdle:b.boolean().optional(),timeoutMs:b.number().int().positive().max(6e5).optional()}).parse(s.body),u=await n.setDrainMode(o);if(o.enabled&&o.waitForIdle&&u.drained===!1)return a.status(202).json(u);a.json(u)}catch(o){ve(a,o)}}),e.get("/api/repos",async(s,a)=>{a.json(await n.listRepos())}),e.get("/api/repos/settings",async(s,a)=>{a.json(await n.listRepoSettings())}),e.post("/api/repos",async(s,a)=>{try{let{repo:o}=b.object({repo:b.string().min(1)}).parse(s.body);a.status(201).json(await n.addRepo(o))}catch(o){ve(a,o)}}),e.patch("/api/repos/settings",async(s,a)=>{try{let o=b.object({repo:b.string().min(1),autoCreateReleases:b.boolean().optional(),ownPrsOnly:b.boolean().optional()}).refine(l=>l.autoCreateReleases!==void 0||l.ownPrsOnly!==void 0,"At least one repository setting must be provided").parse(s.body),{repo:u,...c}=o;a.json(await n.updateRepoSettings(u,c))}catch(o){ve(a,o)}}),e.post("/api/repos/sync",async(s,a)=>{try{a.json(await n.syncRepos())}catch(o){ve(a,o)}}),e.post("/api/repos/release",async(s,a)=>{try{let{repo:o}=b.object({repo:b.string().min(1)}).parse(s.body);a.status(201).json(await n.createManualRelease(o))}catch(o){ve(a,o)}}),e.get("/api/prs",async(s,a)=>{a.json(await n.listPRs("active"))}),e.get("/api/prs/archived",async(s,a)=>{a.json(await n.listPRs("archived"))}),e.get("/api/prs/:id",async(s,a)=>{let o=await n.getPR(s.params.id);if(!o)return a.status(404).json({error:"PR not found"});a.json(o)}),e.post("/api/prs",async(s,a)=>{try{a.status(201).json(await n.addPR(s.body?.url))}catch(o){ve(a,o)}}),e.delete("/api/prs/:id",async(s,a)=>{try{a.json(await n.removePR(s.params.id))}catch(o){ve(a,o)}}),e.patch("/api/prs/:id/watch",async(s,a)=>{try{let{enabled:o}=b.object({enabled:b.boolean()}).parse(s.body);a.json(await n.setPRWatchEnabled(s.params.id,o))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/fetch",async(s,a)=>{try{a.json(await n.fetchPRFeedback(s.params.id))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/triage",async(s,a)=>{try{a.json(await n.triagePR(s.params.id))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/apply",async(s,a)=>{try{a.json(await n.applyPR(s.params.id))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/babysit",async(s,a)=>{try{a.json(await n.babysitPR(s.params.id))}catch(o){ve(a,o)}}),e.patch("/api/prs/:id/feedback/:feedbackId",async(s,a)=>{try{let{decision:o}=b.object({decision:b.enum(["accept","reject","flag"])}).parse(s.body);a.json(await n.setFeedbackDecision(s.params.id,s.params.feedbackId,o))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/feedback/:feedbackId/retry",async(s,a)=>{try{a.json(await n.retryFeedback(s.params.id,s.params.feedbackId))}catch(o){ve(a,o)}}),e.get("/api/prs/:id/questions",async(s,a)=>{try{a.json(await n.listPRQuestions(s.params.id))}catch(o){ve(a,o)}}),e.post("/api/prs/:id/questions",async(s,a)=>{try{a.status(201).json(await n.askQuestion(s.params.id,s.body?.question))}catch(o){ve(a,o)}}),e.get("/api/logs",async(s,a)=>{let o=typeof s.query.prId=="string"?s.query.prId:void 0;a.json(await n.listLogs(o))}),e.get("/api/onboarding/status",async(s,a)=>{try{a.json(await n.getOnboardingStatus())}catch(o){ve(a,o)}}),e.post("/api/onboarding/install-review",async(s,a)=>{try{let{repo:o,tool:u}=b.object({repo:b.string().min(1),tool:b.enum(["claude","codex"])}).parse(s.body);a.json(await n.installReviewWorkflow(o,u))}catch(o){ve(a,o)}}),e.get("/api/healing-sessions",async(s,a)=>{try{a.json(await n.listHealingSessions())}catch(o){ve(a,o)}}),e.get("/api/healing-sessions/:id",async(s,a)=>{try{a.json(await n.getHealingSession(s.params.id))}catch(o){ve(a,o)}}),e.get("/api/deployment-healing-sessions",async(s,a)=>{try{let o=typeof s.query.repo=="string"?s.query.repo:void 0;a.json(await n.listDeploymentHealingSessions(o))}catch(o){ve(a,o)}}),e.get("/api/deployment-healing-sessions/:id",async(s,a)=>{try{a.json(await n.getDeploymentHealingSession(s.params.id))}catch(o){ve(a,o)}}),e.get("/api/config",async(s,a)=>{a.json(nC(await n.getConfig()))}),e.get("/api/app-update",async(s,a)=>{try{a.json(await i("4.3.0"))}catch(o){ve(a,o)}}),e.get("/api/changelogs",async(s,a)=>{try{a.json(await n.listSocialChangelogs())}catch(o){ve(a,o)}}),e.get("/api/changelogs/:id",async(s,a)=>{try{a.json(await n.getSocialChangelog(s.params.id))}catch(o){ve(a,o)}}),e.get("/api/releases",async(s,a)=>{try{a.json(await n.listReleaseRuns())}catch(o){ve(a,o)}}),e.get("/api/releases/:id",async(s,a)=>{try{a.json(await n.getReleaseRun(s.params.id))}catch(o){ve(a,o)}}),e.post("/api/releases/:id/retry",async(s,a)=>{try{a.json(await n.retryReleaseRun(s.params.id))}catch(o){ve(a,o)}}),e.patch("/api/config",async(s,a)=>{try{let o=ic.partial().parse(s.body),u=await n.getConfig();a.json(nC(await n.updateConfig(rZ(u,o))))}catch(o){ve(a,o)}}),t}var oC=qe(Sf(),1),uC=qe(require("fs"),1),q0=qe(require("path"),1);function cC(t){let e=q0.default.resolve(__dirname,"public");if(!uC.default.existsSync(e))throw new Error(`Could not find the build directory: ${e}, make sure to build the client first`);t.use(oC.default.static(e)),t.use("/{*path}",(r,n)=>{n.sendFile(q0.default.resolve(e,"index.html"))})}var nZ=new Set(["127.0.0.1","::1","::ffff:127.0.0.1","localhost"]);function iZ(t){if(!t)return!1;let e=t.replace(/^\[|\]$/g,"");return nZ.has(e)?!0:e.startsWith("::ffff:")?e.slice(7).startsWith("127."):!!e.startsWith("127.")}function lC(t,e,r){let n=t.ip??t.socket?.remoteAddress;if(!iZ(n)){e.status(403).json({error:"Forbidden",message:"oh-my-pr only accepts connections from the local machine. External access is not permitted."});return}r()}var dC=require("http");var sZ=zt("server"),Gi=(0,ip.default)(),pC=(0,dC.createServer)(Gi);Gi.use(ip.default.json({verify:(t,e,r)=>{t.rawBody=r}}));Gi.use(ip.default.urlencoded({extended:!1}));Gi.use("/api",lC);function fC(t,e="express"){Jg.info({source:e},t)}async function aZ(t){let{default:e}=await import("open");await e(t)}(async()=>{await aC(pC,Gi),Gi.use((e,r,n,i)=>{let s=e,a=s.status||s.statusCode||500,o=s.message||"Internal Server Error";return sZ.error({err:e instanceof Error?e.message:String(e),status:a},"Internal Server Error"),n.headersSent?i(e):n.status(a).json({message:o})}),cC(Gi);let t=parseInt(process.env.PORT||"5001",10);pC.listen({port:t,host:"0.0.0.0"},()=>{let e=`http://localhost:${t}`;console.log(`
|
|
1083
|
+
oh-my-pr v4.3.0
|
|
1084
1084
|
Dashboard: ${e}
|
|
1085
1085
|
`),!process.env.TAURI_DEV&&!process.env.OH_MY_PR_DESKTOP&&aZ(e).catch(n=>{fC(`Could not open browser automatically: ${n.message}`)})})})();0&&(module.exports={log});
|
|
1086
1086
|
/*! Bundled license information:
|