@oss-autopilot/core 3.40.1 → 3.40.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";var $F=Object.create;var Dg=Object.defineProperty;var OF=Object.getOwnPropertyDescriptor;var IF=Object.getOwnPropertyNames;var xF=Object.getPrototypeOf,DF=Object.prototype.hasOwnProperty;var A=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var bC=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},re=(e,t)=>{for(var r in t)Dg(e,r,{get:t[r],enumerable:!0})},LF=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of IF(t))!DF.call(e,s)&&s!==r&&Dg(e,s,{get:()=>t[s],enumerable:!(n=OF(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?$F(xF(e)):{},LF(t||!e||!e.__esModule?Dg(r,"default",{value:e,enumerable:!0}):r,e));var V={};re(V,{BIGINT_FORMAT_RANGES:()=>uc,CONSTANT_CATCH:()=>Gl,Class:()=>Ng,NUMBER_FORMAT_RANGES:()=>cc,aborted:()=>Lt,allowsEval:()=>jg,assert:()=>zF,assertEqual:()=>NF,assertIs:()=>UF,assertNever:()=>jF,assertNotEqual:()=>GF,assignProp:()=>St,attachSchema:()=>lc,base64ToUint8Array:()=>TC,base64urlToUint8Array:()=>aN,cached:()=>Xo,captureStackTrace:()=>Ml,cleanEnum:()=>iN,cleanRegex:()=>dn,clone:()=>Oe,cloneDef:()=>WF,codePointLength:()=>Os,constantCatch:()=>qg,createTransparentProxy:()=>YF,defineLazy:()=>Gg,defineLazyInternal:()=>ye,derived:()=>dN,esc:()=>Dt,escapeRegex:()=>wr,explicitlyAborted:()=>Hg,extend:()=>eN,finalizeIssue:()=>qt,floatSafeRemainder:()=>oc,getElementAtPath:()=>VF,getEnumValues:()=>Yo,getLengthableOrigin:()=>pc,getParsedType:()=>JF,getSizableOrigin:()=>dc,hexToUint8Array:()=>uN,hide:()=>mc,installLazyProp:()=>gN,isObject:()=>$s,isPlainObject:()=>br,issue:()=>ri,joinValues:()=>Dl,jsonStringifyReplacer:()=>Qo,members:()=>Vg,merge:()=>rN,mergeDefs:()=>Cr,normalizeParams:()=>U,nullish:()=>Ll,numKeys:()=>KF,objectClone:()=>BF,omit:()=>XF,optionalKeys:()=>Bg,own:()=>Un,parsedType:()=>Wg,partial:()=>nN,pick:()=>QF,prefixIssues:()=>Vt,primitiveTypes:()=>zg,promiseAllObject:()=>qF,propertyKeyTypes:()=>ac,randomString:()=>ZF,rawShape:()=>ei,required:()=>sN,safeExtend:()=>tN,shallowClone:()=>ic,sizeCaps:()=>ti,slugify:()=>Ug,stringifyPrimitive:()=>Fl,toZod:()=>sc,uint8ArrayToBase64:()=>$C,uint8ArrayToBase64url:()=>cN,uint8ArrayToHex:()=>lN,unwrapMessage:()=>Jo});function NF(e){return e}function GF(e){return e}function sc(){return e=>e}function UF(e){}function jF(e){throw new Error("Unexpected value in exhaustive check")}function zF(e){}function Yo(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,s])=>t.indexOf(+n)===-1).map(([n,s])=>s)}function Dl(e,t="|"){return e.map(r=>Fl(r)).join(t)}function Qo(e,t){return typeof t=="bigint"?t.toString():t}function Xo(e){return new Fg(e)}function Ll(e){return e==null}function dn(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function oc(e,t){let r=e/t,n=Math.round(r),s=4*Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<s?0:r-n}function Gg(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==CC)return n===void 0&&(n=CC,n=r()),n},set(s){Object.defineProperty(e,t,{value:s})},configurable:!0})}function BF(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function St(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ei(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function ln(e){return ei(e._zod.def)??e._zod.def.shape}function PC(e,t,r){Object.defineProperty(e,t,{get(){let n=r();return St(this,t,n),n},enumerable:!0,configurable:!0})}function EC(e,t,r){t in e?St(e,t,r):e[t]=r}function Ts(e,t,r,n){let s=ln(t);for(let o of r){let i=Object.getOwnPropertyDescriptor(s,o);i.enumerable&&(i.get?PC(e,o,()=>{let a=t._zod.def.shape[o];return n?n(a,o):a}):EC(e,o,n?n(i.value,o):i.value))}}function HF(e,t){for(let r of Reflect.ownKeys(t)){let n=Object.getOwnPropertyDescriptor(t,r);n.enumerable&&(n.get?PC(e,r,()=>t[r]):EC(e,r,n.value))}}function Cr(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function WF(e){return Cr(e._zod.def)}function VF(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function qF(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let s={};for(let o=0;o<t.length;o++)s[t[o]]=n[o];return s})}function ZF(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Dt(e){return JSON.stringify(e)}function Ug(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function $s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function br(e){if($s(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!($s(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ic(e){return br(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function KF(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function wr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oe(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function U(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function YF(e){let t;return new Proxy({},{get(r,n,s){return t??(t=e()),Reflect.get(t,n,s)},set(r,n,s,o){return t??(t=e()),Reflect.set(t,n,s,o)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,s){return t??(t=e()),Reflect.defineProperty(t,n,s)}})}function Fl(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Bg(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}function QF(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let o={};return Ts(o,e,Nl(e,t)),Oe(e,Cr(r,{shape:o,checks:[]}))}function Nl(e,t){let r=ln(e),n=[];for(let s of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,s)?.enumerable)throw new Error(`Unrecognized key: "${String(s)}"`);t[s]&&n.push(s)}return n}function XF(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let o=new Set(Nl(e,t)),i={};return Ts(i,e,Reflect.ownKeys(ln(e)).filter(a=>!o.has(a))),Oe(e,Cr(r,{shape:i,checks:[]}))}function eN(e,t){if(!br(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=ln(e);for(let o of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(s,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Oe(e,Cr(e._zod.def,{shape:AC(e,t)}))}function AC(e,t){let r={};return Ts(r,e,Reflect.ownKeys(ln(e))),HF(r,t),r}function tN(e,t){if(!br(t))throw new Error("Invalid input to safeExtend: expected a plain object");return Oe(e,Cr(e._zod.def,{shape:AC(e,t)}))}function rN(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};Ts(r,e,Reflect.ownKeys(ln(e))),Ts(r,t,Reflect.ownKeys(ln(t)));let n=Cr(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Oe(e,n)}function nN(e,t,r,n="partial"){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(`.${n}() cannot be used on object schemas containing refinements`);let a=r?new Set(Nl(t,r)):void 0,c={};return Ts(c,t,Reflect.ownKeys(ln(t)),e&&((u,d)=>a&&!a.has(d)?u:new e({type:"optional",innerType:u}))),Oe(t,Cr(t._zod.def,{shape:c,checks:[]}))}function sN(e,t,r){let n=r?new Set(Nl(t,r)):void 0,s={};return Ts(s,t,Reflect.ownKeys(ln(t)),(o,i)=>n&&!n.has(i)?o:new e({type:"nonoptional",innerType:o})),Oe(t,Cr(t._zod.def,{shape:s}))}function Lt(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Hg(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Vt(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Jo(e){return typeof e=="string"?e:e?.message}function ti(e){let t=[];for(let r of e??[]){let n=r._zod.def;if(!/_(length|size)$|_equals$/.test(n.check))break;let s=n.maximum??n.length??n.size;s>=0&&t.push([s,r])}return t}function lc(e,t,r){var n;for(let s=t;s<e.length;s++)(n=e[s]).schema??(n.schema=r)}function qt(e,t,r){var n;let s=e.inst?._zod?.traits;s?.has("$ZodType")&&(s.has("$ZodCheck")?(n=e).schema??(n.schema=e.inst):e.schema=e.inst);let o=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:Jo(e.inst?._zod.def?.error?.(e))??Jo(o?.(e))??Jo(t?.error?.(e))??Jo(r.customError?.(e))??Jo(r.localeError?.(e))??"Invalid input",a={};for(let c of Object.keys(e))c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__"||(a[c]=e[c]);return a.path??(a.path=[]),a.message=i,t?.reportInput&&(a.input=e.input),a}function dc(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Os(e){let t=e.length;if(!oN.test(e))return t;let r=t;for(let n=0;n<t-1;n++)(e.charCodeAt(n)&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320&&(r--,n++);return r}function pc(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wg(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function ri(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function iN(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function TC(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function $C(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function aN(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return TC(t+r)}function cN(e){return $C(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function uN(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function lN(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function Vg(e,t){for(let r in t){let n=Object.getOwnPropertyDescriptor(t,r);n.get?Object.defineProperty(e,r,{...n,enumerable:!1}):pN(e,r,n.value)}}function Un(e,t,r,n=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:n,value:r}),r}function mc(e,t,r){return Un(e,t,r,!1)}function dN(e,t){for(let r in e){let n=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return Un(this,r,n(this))},set(s){Un(this,r,s)}})}return t}function pN(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:Un(this,t,r.bind(this))},set(n){Un(this,t,n)}})}function mN(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}function ye(e,t,r){let n=Object.getPrototypeOf(e._zod);if(t in n&&Mg!==e._zod){Mg=void 0;return}Mg=e._zod,Object.defineProperty(n,t,{configurable:!0,get(){Object.defineProperty(this,t,fN);let s=Gn;Gn=!1;try{let o=r(this);return Gn?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o}),Gn=Gn||s,o}catch(o){throw delete this[t],Gn=Gn||s,o}},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s})}})}function gN(e,t,r,n){let s=mN(e,t);s&&Object.defineProperty(s,t,{configurable:!0,get(){let o={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,t,o),o.value=r(this),Object.defineProperty(this,t,o),o.value},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:n,value:o})}})}function qg(e){let t=()=>e;return t[Gl]=!0,t}var Fg,CC,Ml,jg,JF,ac,zg,cc,uc,oN,Ng,Mg,Gn,fN,Gl,rt=A(()=>{jn();Fg=class{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}};CC=Symbol("evaluating");Ml="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};jg=Xo(()=>{if(ht.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});JF=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},ac=new Set(["string","number","symbol"]),zg=new Set(["string","number","bigint","boolean","symbol","undefined"]);cc={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},uc={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};oN=/[\uD800-\uDBFF]/;Ng=class{constructor(...t){}};Gn=!1,fN={configurable:!0,get(){Gn=!0}};Gl="~constantCatch"});function hN(e){let t=IC;if(t){let r=t.stackTraceLimit;if(typeof r=="number"){try{t.stackTraceLimit=0}catch{return IC=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function $(e,t,r,n){let s={};function o(m){this.def=m,this.constr=p,this.traits=new Set}o.prototype=s;let i=r,a=i&&new WeakSet;function c(m,f){if(m._zod){if(m._zod.traits.has(e))return}else{Zg.value=new o(f);try{Object.defineProperty(m,"_zod",Zg)}finally{Zg.value=void 0}}if(m._zod.traits.add(e),t(m,f),a){let h=Object.getPrototypeOf(m),b=m._zod.constr.prototype,w=h;for(;w&&w!==b;)w=Object.getPrototypeOf(w);let y=w??h;a.has(y)||(a.add(y),Vg(y,i))}let g=p.prototype;for(let h in g)Object.prototype.hasOwnProperty.call(g,h)&&(h in m||(m[h]=g[h].bind(m)))}let u=n?.Parent??Object;class d extends u{}Object.defineProperty(d,"name",{value:e});function p(m){let f=n?.Parent?hN(d):this;c(f,m);let g=f._zod.deferred;if(g){for(let b of g)b();f._zod.deferred=void 0}let h=globalThis.__zod_globalConfig?.postProcessor;return h&&h(f),f}return Object.defineProperty(p,"init",{value:c}),Object.defineProperty(p,Symbol.hasInstance,{value:m=>n?.Parent&&m instanceof n.Parent?!0:m?._zod?.traits?.has(e)}),Object.defineProperty(p,"name",{value:e}),p}function Ye(e){return e&&Object.assign(ht,e),ht}var OC,Kg,Zg,IC,Jg,Zt,zn,ht,jn=A(()=>{rt();Kg=Object.freeze({status:"aborted"}),Zg={value:void 0,enumerable:!1},IC="captureStackTrace"in Error?Error:null;Jg=Symbol("zod_brand"),Zt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},zn=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(OC=globalThis).__zod_globalConfig??(OC.__zod_globalConfig={});ht=globalThis.__zod_globalConfig});function yN(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Qo,2)),e.message}function bN(e){this._zod.message=e}function RN(e,t,r){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:r(),writable:!0,enumerable:!0,configurable:!0}):e[t]=r()),e[t]}function fc(e,t=r=>r.message){let r={},n=[];for(let s of e.issues)s.path.length>0?RN(r,s.path[0],()=>[]).push(t(s)):n.push(t(s));return{formErrors:n,fieldErrors:r}}function gc(e,t=r=>r.message){let r={_errors:[]},n=(s,o=[])=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a},[...o,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...o,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...o,...i.path]);else{let a=[...o,...i.path];if(a.length===0)r._errors.push(t(i));else{let c=r,u=0;for(;u<a.length;){let d=a[u],p=u===a.length-1;if(d==="_errors"){p&&c._errors.push(t(i)),u++;continue}Object.prototype.hasOwnProperty.call(c,d)||Object.defineProperty(c,d,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let m=c[d];p&&m._errors.push(t(i)),c=m,u++}}}};return n(e),r}function eh(e,t=r=>r.message){let r={errors:[]},n=(s,o=[])=>{var i;for(let a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>n({issues:c},[...o,...a.path]));else if(a.code==="invalid_key")n({issues:a.issues},[...o,...a.path]);else if(a.code==="invalid_element")n({issues:a.issues},[...o,...a.path]);else{let c=[...o,...a.path];if(c.length===0){r.errors.push(t(a));continue}let u=r,d=0;for(;d<c.length;){let p=c[d],m=d===c.length-1;typeof p=="string"?(u.properties??(u.properties={}),Object.prototype.hasOwnProperty.call(u.properties,p)||Object.defineProperty(u.properties,p,{value:{errors:[]},enumerable:!0,writable:!0,configurable:!0}),u=u.properties[p]):(u.items??(u.items=[]),(i=u.items)[p]??(i[p]={errors:[]}),u=u.items[p]),m&&u.errors.push(t(a)),d++}}};return n(e),r}function LC(e){let t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function th(e){let t=[],r=[...e.issues].sort((n,s)=>(n.path??[]).length-(s.path??[]).length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${LC(n.path)}`);return t.join(`
3
- `)}var wN,Qg,xC,DC,Xg,Kt,rh=A(()=>{jn();rt();wN={get:yN,set:bN,enumerable:!0,configurable:!0},Qg={value:void 0,enumerable:!1},xC=new WeakSet([Object.prototype,Error.prototype]),DC=(e,t)=>{e.name="$ZodError",Qg.value=t,Object.defineProperty(e,"issues",Qg),Qg.value=void 0,Object.defineProperty(e,"message",wN);let r=Object.getPrototypeOf(e);xC.has(r)||(xC.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}}))},Xg=$("$ZodError",DC),Kt=$("$ZodError",DC,void 0,{Parent:Error})});function Ul(e,t){return{callee:t?.callee??e,Err:t?.Err}}function MC(e,t,r){let n;return{success:!1,get error(){return n||(n=new e(t.map(s=>qt(s,r,Ye()))),t=void 0,r=void 0),n},set error(s){n=s,t=void 0,r=void 0}}}function PN(e,t,r){let n=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},s=e._zod.bag.fallbackRun,o;if(s?(n[CN]=!0,o=s({value:t,issues:[]},n)):o=e._zod.run({value:t,issues:[]},n),o instanceof Promise)throw new Zt;return o.issues.length===0}var ni,jl,si,zl,oi,_N,ii,vN,kN,CN,hc,yc,Bl,EN,Hl,AN,Wl,TN,Vl,$N,ql,ON,Zl,IN,Kl,xN,Jl,DN,nh=A(()=>{jn();rh();rt();ni=e=>{let t=(r,n,s,o)=>{let i=s?{...s,async:!1}:{async:!1},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Zt;if(a.issues.length){let c=new(o?.Err??e)(a.issues.map(u=>qt(u,i,Ye())));throw Ml(c,o?.callee??t),c}return a.value};return t},jl=ni(Kt),si=e=>{let t=async(r,n,s,o)=>{let i=s?{...s,async:!0}:{async:!0},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new(o?.Err??e)(a.issues.map(u=>qt(u,i,Ye())));throw Ml(c,o?.callee??t),c}return a.value};return t},zl=si(Kt),oi=e=>(t,r,n)=>{let s=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Zt;return o.issues.length?MC(e,o.issues,s):{success:!0,data:o.value}},_N=oi(Kt);ii=e=>async(t,r,n)=>{let s=n?{...n,async:!0}:{async:!0},o=t._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?MC(e,o.issues,s):{success:!0,data:o.value}},vN=ii(Kt),kN=Symbol.for("zod.compile.invalid"),CN=Symbol.for("zod.compile.fallback"),hc=((e,t,r)=>{let n=e._zod.bag.validator;if(n!==void 0){if(n(t)!==kN)return!0;if(n.definite===!0&&r===void 0)return!1}return PN(e,t,r)});yc=async(e,t,r)=>{let n=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},s=e._zod.run({value:t,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length===0},Bl=e=>{let t=ni(e),r=(n,s,o,i)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return t(n,s,a,Ul(r,i))};return r},EN=Bl(Kt),Hl=e=>{let t=ni(e),r=(n,s,o,i)=>t(n,s,o,Ul(r,i));return r},AN=Hl(Kt),Wl=e=>{let t=si(e),r=async(n,s,o,i)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return await t(n,s,a,Ul(r,i))};return r},TN=Wl(Kt),Vl=e=>{let t=si(e),r=async(n,s,o,i)=>await t(n,s,o,Ul(r,i));return r},$N=Vl(Kt),ql=e=>(t,r,n)=>{let s=n?{...n,direction:"backward"}:{direction:"backward"};return oi(e)(t,r,s)},ON=ql(Kt),Zl=e=>(t,r,n)=>oi(e)(t,r,n),IN=Zl(Kt),Kl=e=>async(t,r,n)=>{let s=n?{...n,direction:"backward"}:{direction:"backward"};return ii(e)(t,r,s)},xN=Kl(Kt),Jl=e=>async(t,r,n)=>ii(e)(t,r,n),DN=Jl(Kt)});var Rr={};re(Rr,{anyString:()=>$h,base64:()=>Sh,base64url:()=>_h,bigint:()=>Ih,boolean:()=>xh,browserEmail:()=>zN,cidrv4:()=>wh,cidrv6:()=>Rh,creditCard:()=>Yl,cuid:()=>oh,cuid2:()=>ih,currencyCode:()=>Ph,date:()=>Eh,datetime:()=>Th,domain:()=>kh,duration:()=>ph,e164:()=>Ch,email:()=>fh,emoji:()=>gh,extendedDuration:()=>LN,guid:()=>mh,hex:()=>Nh,hostname:()=>vh,html5Email:()=>GN,httpProtocol:()=>bc,iban:()=>Ql,idnEmail:()=>jN,integer:()=>wc,ipv4:()=>hh,ipv6:()=>yh,ksuid:()=>uh,lowercase:()=>Mh,mac:()=>bh,md5_base64:()=>VN,md5_base64url:()=>qN,md5_hex:()=>WN,nanoid:()=>lh,nanoidOfLength:()=>dh,null:()=>Dh,number:()=>pn,rfc5322Email:()=>UN,sha1_base64:()=>KN,sha1_base64url:()=>JN,sha1_hex:()=>ZN,sha256_base64:()=>QN,sha256_base64url:()=>XN,sha256_hex:()=>YN,sha384_base64:()=>tG,sha384_base64url:()=>rG,sha384_hex:()=>eG,sha512_base64:()=>sG,sha512_base64url:()=>oG,sha512_hex:()=>nG,string:()=>Oh,time:()=>Ah,ulid:()=>ah,undefined:()=>Lh,unicodeEmail:()=>FC,uppercase:()=>Fh,uuid:()=>Is,uuid4:()=>MN,uuid6:()=>FN,uuid7:()=>NN,xid:()=>ch});function dh(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}function gh(){return new RegExp(BN,"u")}function HN(e){return new RegExp(`^${e}$`)}function sh(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ah(e){return new RegExp(`^${sh(e)}$`)}function Th(e){let t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${sh({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,n=e.local?`${r}|${sh({precision:e.precision})}`:r;return new RegExp(`^${NC}T(?:${n})$`)}function Rc(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Sc(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var oh,ih,ah,ch,uh,lh,ph,LN,mh,Is,MN,FN,NN,fh,GN,UN,FC,jN,zN,BN,hh,yh,bh,wh,Rh,Sh,_h,vh,kh,bc,Ch,Yl,Ph,Ql,NC,Eh,$h,Oh,Ih,wc,pn,xh,Dh,Lh,Mh,Fh,Nh,WN,VN,qN,ZN,KN,JN,YN,QN,XN,eG,tG,rG,nG,sG,oG,xs=A(()=>{rt();oh=/^[cC][0-9a-z]{6,}$/,ih=/^[0-9a-z]+$/,ah=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,ch=/^[0-9a-vA-V]{20}$/,uh=/^[A-Za-z0-9]{27}$/,lh=/^[a-zA-Z0-9_-]{21}$/;ph=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,LN=/^[-+]?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)?)??$/,mh=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Is=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,MN=Is(4),FN=Is(6),NN=Is(7),fh=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,GN=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,UN=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,FC=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,jN=FC,zN=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,BN="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";hh=/^(?:(?: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])$/,yh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,bh=e=>{let t=wr(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},wh=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Rh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Sh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_h=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,vh=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,kh=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,bc=/^https?$/,Ch=/^\+[1-9]\d{6,14}$/,Yl=/^\d(?:[ -]?\d){11,18}$/,Ph=/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,Ql=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,NC="(?:(?:\\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])))";Eh=HN(NC);$h=/^[\s\S]{0,}$/,Oh=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Ih=/^-?\d+n?$/,wc=/^-?\d+$/,pn=/^-?\d+(?:\.\d+)?$/,xh=/^(?:true|false)$/i,Dh=/^null$/i,Lh=/^undefined$/i,Mh=/^[^A-Z]*$/,Fh=/^[^a-z]*$/,Nh=/^[0-9a-fA-F]*$/;WN=/^[0-9a-fA-F]{32}$/,VN=Rc(22,"=="),qN=Sc(22),ZN=/^[0-9a-fA-F]{40}$/,KN=Rc(27,"="),JN=Sc(27),YN=/^[0-9a-fA-F]{64}$/,QN=Rc(43,"="),XN=Sc(43),eG=/^[0-9a-fA-F]{96}$/,tG=Rc(64,""),rG=Sc(64),nG=/^[0-9a-fA-F]{128}$/,sG=Rc(86,"=="),oG=Sc(86)});function ed(e,t,r){e.issues.length&&t.issues.push(...Vt(r,e.issues))}var Fe,Gh,Uh,Xl,td,rd,jh,zh,Bh,Hh,Wh,Vh,qh,Zh,Kh,ai,Jh,Yh,Qh,Xh,ey,ty,ry,ny,sy,oy,nd=A(()=>{jn();xs();rt();Fe=$("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Gh=e=>{let t=e.value;return!Ll(t)&&t.size!==void 0},Uh=e=>{let t=e.value;return!Ll(t)&&t.length!==void 0},Xl={number:"number",bigint:"bigint",object:"date"},td=$("$ZodCheckLessThan",(e,t)=>{Fe.init(e,t);let r=Xl[typeof t.value];e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:Xl[typeof n.value]??r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rd=$("$ZodCheckGreaterThan",(e,t)=>{Fe.init(e,t);let r=Xl[typeof t.value];e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:Xl[typeof n.value]??r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),jh=$("$ZodCheckMultipleOf",(e,t)=>{Fe.init(e,t),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):oc(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),zh=$("$ZodCheckNumberFormat",(e,t)=>{Fe.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[s,o]=cc[t.format];e._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<s&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),a>o&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Bh=$("$ZodCheckBigIntFormat",(e,t)=>{Fe.init(e,t);let[r,n]=uc[t.format];e._zod.check=s=>{let o=s.value;o<r&&s.issues.push({origin:"bigint",input:o,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),o>n&&s.issues.push({origin:"bigint",input:o,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),Hh=$("$ZodCheckMaxSize",(e,t)=>{var r;Fe.init(e,t),(r=e._zod.def).when??(r.when=Gh),e._zod.check=n=>{let s=n.value;s.size<=t.maximum||n.issues.push({origin:dc(s),code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),Wh=$("$ZodCheckMinSize",(e,t)=>{var r;Fe.init(e,t),(r=e._zod.def).when??(r.when=Gh),e._zod.check=n=>{let s=n.value;s.size>=t.minimum||n.issues.push({origin:dc(s),code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),Vh=$("$ZodCheckSizeEquals",(e,t)=>{var r;Fe.init(e,t),(r=e._zod.def).when??(r.when=Gh),e._zod.check=n=>{let s=n.value,o=s.size;if(o===t.size)return;let i=o>t.size;n.issues.push({origin:dc(s),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),qh=$("$ZodCheckMaxLength",(e,t)=>{var r;Fe.init(e,t),(r=e._zod.def).when??(r.when=Uh),e._zod.check=n=>{let s=n.value,o=s.length;if((typeof s=="string"&&o>t.maximum?Os(s):o)<=t.maximum)return;let a=pc(s);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),Zh=$("$ZodCheckMinLength",(e,t)=>{var r;Fe.init(e,t),(r=e._zod.def).when??(r.when=Uh),e._zod.check=n=>{let s=n.value,o=s.length;if((typeof s=="string"&&o>=t.minimum&&o<t.minimum*2?Os(s):o)>=t.minimum)return;let a=pc(s);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),Kh=$("$ZodCheckLengthEquals",(e,t)=>{var r;Fe.init(e,t),(r=e._zod.def).when??(r.when=Uh),e._zod.check=n=>{let s=n.value,o=s.length,i=typeof s=="string"&&o>=t.length&&o<=t.length*2?Os(s):o;if(i===t.length)return;let a=pc(s),c=i>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ai=$("$ZodCheckStringFormat",(e,t)=>{var r,n;Fe.init(e,t),t.pattern?(r=e._zod).check??(r.check=s=>{t.pattern.lastIndex=0,!t.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:t.format,input:s.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Jh=$("$ZodCheckRegex",(e,t)=>{ai.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Yh=$("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Mh),ai.init(e,t)}),Qh=$("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Fh),ai.init(e,t)}),Xh=$("$ZodCheckIncludes",(e,t)=>{Fe.init(e,t);let r=wr(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position},}${r}`:r);t.pattern=n,e._zod.check=s=>{s.value.includes(t.includes,t.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:s.value,inst:e,continue:!t.abort})}}),ey=$("$ZodCheckStartsWith",(e,t)=>{Fe.init(e,t);let r=new RegExp(`^${wr(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),ty=$("$ZodCheckEndsWith",(e,t)=>{Fe.init(e,t);let r=new RegExp(`.*${wr(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});ry=$("$ZodCheckProperty",(e,t)=>{Fe.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(s=>ed(s,r,t.property));ed(n,r,t.property)}}),ny=$("$ZodCheckProperties",(e,t)=>{Fe.init(e,t),mc(e,Symbol.iterator,function*(){yield e});let r;e._zod.check=n=>{if(n.value==null){n.issues.push({expected:"object",code:"invalid_type",input:n.value,inst:e});return}r??(r=Reflect.ownKeys(t.shape).map(i=>[i,t.shape[i]]));let s=n.value,o;for(let[i,a]of r){let c=a._zod.run({value:s[i],issues:[]},{});c instanceof Promise?(o??(o=[]),o.push(c.then(u=>ed(u,n,i)))):ed(c,n,i)}if(o)return Promise.all(o).then(()=>{})}}),sy=$("$ZodCheckMimeType",(e,t)=>{Fe.init(e,t);let r=new Set(t.mime);e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),oy=$("$ZodCheckOverwrite",(e,t)=>{Fe.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}})});var Ds,sd=A(()=>{Ds=class{constructor(t=[],r={}){this.content=[],this.indent=0,this.args=t,this.closed=r}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
3
+ `)}var wN,Qg,xC,DC,Xg,Kt,rh=A(()=>{jn();rt();wN={get:yN,set:bN,enumerable:!0,configurable:!0},Qg={value:void 0,enumerable:!1},xC=new WeakSet([Object.prototype,Error.prototype]),DC=(e,t)=>{e.name="$ZodError",Qg.value=t,Object.defineProperty(e,"issues",Qg),Qg.value=void 0,Object.defineProperty(e,"message",wN);let r=Object.getPrototypeOf(e);xC.has(r)||(xC.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}}))},Xg=$("$ZodError",DC),Kt=$("$ZodError",DC,void 0,{Parent:Error})});function Ul(e,t){return{callee:t?.callee??e,Err:t?.Err}}function MC(e,t,r){let n;return{success:!1,get error(){return n||(n=new e(t.map(s=>qt(s,r,Ye()))),t=void 0,r=void 0),n},set error(s){n=s,t=void 0,r=void 0}}}function PN(e,t,r){let n=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},s=e._zod.bag.fallbackRun,o;if(s?(n[CN]=!0,o=s({value:t,issues:[]},n)):o=e._zod.run({value:t,issues:[]},n),o instanceof Promise)throw new Zt;return o.issues.length===0}var ni,jl,si,zl,oi,_N,ii,vN,kN,CN,hc,yc,Bl,EN,Hl,AN,Wl,TN,Vl,$N,ql,ON,Zl,IN,Kl,xN,Jl,DN,nh=A(()=>{jn();rh();rt();ni=e=>{let t=(r,n,s,o)=>{let i=s?{...s,async:!1}:{async:!1},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Zt;if(a.issues.length){let c=new(o?.Err??e)(a.issues.map(u=>qt(u,i,Ye())));throw Ml(c,o?.callee??t),c}return a.value};return t},jl=ni(Kt),si=e=>{let t=async(r,n,s,o)=>{let i=s?{...s,async:!0}:{async:!0},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new(o?.Err??e)(a.issues.map(u=>qt(u,i,Ye())));throw Ml(c,o?.callee??t),c}return a.value};return t},zl=si(Kt),oi=e=>(t,r,n)=>{let s=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Zt;return o.issues.length?MC(e,o.issues,s):{success:!0,data:o.value}},_N=oi(Kt);ii=e=>async(t,r,n)=>{let s=n?{...n,async:!0}:{async:!0},o=t._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?MC(e,o.issues,s):{success:!0,data:o.value}},vN=ii(Kt),kN=Symbol.for("zod.compile.invalid"),CN=Symbol.for("zod.compile.fallback"),hc=((e,t,r)=>{let n=e._zod.bag.validator;if(n!==void 0){if(n(t)!==kN)return!0;if(n.definite===!0&&r===void 0)return!1}return PN(e,t,r)});yc=async(e,t,r)=>{let n=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},s=e._zod.run({value:t,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length===0},Bl=e=>{let t=ni(e),r=(n,s,o,i)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return t(n,s,a,Ul(r,i))};return r},EN=Bl(Kt),Hl=e=>{let t=ni(e),r=(n,s,o,i)=>t(n,s,o,Ul(r,i));return r},AN=Hl(Kt),Wl=e=>{let t=si(e),r=async(n,s,o,i)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return await t(n,s,a,Ul(r,i))};return r},TN=Wl(Kt),Vl=e=>{let t=si(e),r=async(n,s,o,i)=>await t(n,s,o,Ul(r,i));return r},$N=Vl(Kt),ql=e=>(t,r,n)=>{let s=n?{...n,direction:"backward"}:{direction:"backward"};return oi(e)(t,r,s)},ON=ql(Kt),Zl=e=>(t,r,n)=>oi(e)(t,r,n),IN=Zl(Kt),Kl=e=>async(t,r,n)=>{let s=n?{...n,direction:"backward"}:{direction:"backward"};return ii(e)(t,r,s)},xN=Kl(Kt),Jl=e=>async(t,r,n)=>ii(e)(t,r,n),DN=Jl(Kt)});var Rr={};re(Rr,{anyString:()=>$h,base64:()=>Sh,base64url:()=>_h,bigint:()=>Ih,boolean:()=>xh,browserEmail:()=>zN,cidrv4:()=>wh,cidrv6:()=>Rh,creditCard:()=>Yl,cuid:()=>oh,cuid2:()=>ih,currencyCode:()=>Ph,date:()=>Eh,datetime:()=>Th,domain:()=>kh,duration:()=>ph,e164:()=>Ch,email:()=>fh,emoji:()=>gh,extendedDuration:()=>LN,guid:()=>mh,hex:()=>Nh,hostname:()=>vh,html5Email:()=>GN,httpProtocol:()=>bc,iban:()=>Ql,idnEmail:()=>jN,integer:()=>wc,ipv4:()=>hh,ipv6:()=>yh,ksuid:()=>uh,lowercase:()=>Mh,mac:()=>bh,md5_base64:()=>VN,md5_base64url:()=>qN,md5_hex:()=>WN,nanoid:()=>lh,nanoidOfLength:()=>dh,null:()=>Dh,number:()=>pn,rfc5322Email:()=>UN,sha1_base64:()=>KN,sha1_base64url:()=>JN,sha1_hex:()=>ZN,sha256_base64:()=>QN,sha256_base64url:()=>XN,sha256_hex:()=>YN,sha384_base64:()=>tG,sha384_base64url:()=>rG,sha384_hex:()=>eG,sha512_base64:()=>sG,sha512_base64url:()=>oG,sha512_hex:()=>nG,string:()=>Oh,time:()=>Ah,ulid:()=>ah,undefined:()=>Lh,unicodeEmail:()=>FC,uppercase:()=>Fh,uuid:()=>Is,uuid4:()=>MN,uuid6:()=>FN,uuid7:()=>NN,xid:()=>ch});function dh(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}function gh(){return new RegExp(BN,"u")}function HN(e){return new RegExp(`^${e}$`)}function sh(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ah(e){return new RegExp(`^${sh(e)}$`)}function Th(e){let t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${sh({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,n=e.local?`${r}|${sh({precision:e.precision})}`:r;return new RegExp(`^${NC}T(?:${n})$`)}function Rc(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Sc(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var oh,ih,ah,ch,uh,lh,ph,LN,mh,Is,MN,FN,NN,fh,GN,UN,FC,jN,zN,BN,hh,yh,bh,wh,Rh,Sh,_h,vh,kh,bc,Ch,Yl,Ph,Ql,NC,Eh,$h,Oh,Ih,wc,pn,xh,Dh,Lh,Mh,Fh,Nh,WN,VN,qN,ZN,KN,JN,YN,QN,XN,eG,tG,rG,nG,sG,oG,xs=A(()=>{rt();oh=/^[cC][0-9a-z]{6,}$/,ih=/^[0-9a-z]+$/,ah=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,ch=/^[0-9a-vA-V]{20}$/,uh=/^[A-Za-z0-9]{27}$/,lh=/^[a-zA-Z0-9_-]{21}$/;ph=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,LN=/^[-+]?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)?)??$/,mh=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Is=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,MN=Is(4),FN=Is(6),NN=Is(7),fh=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,GN=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,UN=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,FC=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,jN=FC,zN=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,BN="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";hh=/^(?:(?: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])$/,yh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,bh=e=>{let t=wr(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},wh=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Rh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Sh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_h=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,vh=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,kh=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,bc=/^https?$/,Ch=/^\+[1-9]\d{6,14}$/,Yl=/^\d(?:[ -]?\d){11,18}$/,Ph=/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,Ql=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,NC="(?:(?:\\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])))";Eh=HN(NC);$h=/^[\s\S]{0,}$/,Oh=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Ih=/^-?\d+n?$/,wc=/^-?\d+$/,pn=/^-?\d+(?:\.\d+)?$/,xh=/^(?:true|false)$/i,Dh=/^null$/i,Lh=/^undefined$/i,Mh=/^[^A-Z]*$/,Fh=/^[^a-z]*$/,Nh=/^[0-9a-fA-F]*$/;WN=/^[0-9a-fA-F]{32}$/,VN=Rc(22,"=="),qN=Sc(22),ZN=/^[0-9a-fA-F]{40}$/,KN=Rc(27,"="),JN=Sc(27),YN=/^[0-9a-fA-F]{64}$/,QN=Rc(43,"="),XN=Sc(43),eG=/^[0-9a-fA-F]{96}$/,tG=Rc(64,""),rG=Sc(64),nG=/^[0-9a-fA-F]{128}$/,sG=Rc(86,"=="),oG=Sc(86)});function ed(e,t,r){e.issues.length&&t.issues.push(...Vt(r,e.issues))}var Ne,Gh,Uh,Xl,td,rd,jh,zh,Bh,Hh,Wh,Vh,qh,Zh,Kh,ai,Jh,Yh,Qh,Xh,ey,ty,ry,ny,sy,oy,nd=A(()=>{jn();xs();rt();Ne=$("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Gh=e=>{let t=e.value;return!Ll(t)&&t.size!==void 0},Uh=e=>{let t=e.value;return!Ll(t)&&t.length!==void 0},Xl={number:"number",bigint:"bigint",object:"date"},td=$("$ZodCheckLessThan",(e,t)=>{Ne.init(e,t);let r=Xl[typeof t.value];e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:Xl[typeof n.value]??r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rd=$("$ZodCheckGreaterThan",(e,t)=>{Ne.init(e,t);let r=Xl[typeof t.value];e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:Xl[typeof n.value]??r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),jh=$("$ZodCheckMultipleOf",(e,t)=>{Ne.init(e,t),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):oc(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),zh=$("$ZodCheckNumberFormat",(e,t)=>{Ne.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[s,o]=cc[t.format];e._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<s&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),a>o&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Bh=$("$ZodCheckBigIntFormat",(e,t)=>{Ne.init(e,t);let[r,n]=uc[t.format];e._zod.check=s=>{let o=s.value;o<r&&s.issues.push({origin:"bigint",input:o,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),o>n&&s.issues.push({origin:"bigint",input:o,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),Hh=$("$ZodCheckMaxSize",(e,t)=>{var r;Ne.init(e,t),(r=e._zod.def).when??(r.when=Gh),e._zod.check=n=>{let s=n.value;s.size<=t.maximum||n.issues.push({origin:dc(s),code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),Wh=$("$ZodCheckMinSize",(e,t)=>{var r;Ne.init(e,t),(r=e._zod.def).when??(r.when=Gh),e._zod.check=n=>{let s=n.value;s.size>=t.minimum||n.issues.push({origin:dc(s),code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),Vh=$("$ZodCheckSizeEquals",(e,t)=>{var r;Ne.init(e,t),(r=e._zod.def).when??(r.when=Gh),e._zod.check=n=>{let s=n.value,o=s.size;if(o===t.size)return;let i=o>t.size;n.issues.push({origin:dc(s),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),qh=$("$ZodCheckMaxLength",(e,t)=>{var r;Ne.init(e,t),(r=e._zod.def).when??(r.when=Uh),e._zod.check=n=>{let s=n.value,o=s.length;if((typeof s=="string"&&o>t.maximum?Os(s):o)<=t.maximum)return;let a=pc(s);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),Zh=$("$ZodCheckMinLength",(e,t)=>{var r;Ne.init(e,t),(r=e._zod.def).when??(r.when=Uh),e._zod.check=n=>{let s=n.value,o=s.length;if((typeof s=="string"&&o>=t.minimum&&o<t.minimum*2?Os(s):o)>=t.minimum)return;let a=pc(s);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),Kh=$("$ZodCheckLengthEquals",(e,t)=>{var r;Ne.init(e,t),(r=e._zod.def).when??(r.when=Uh),e._zod.check=n=>{let s=n.value,o=s.length,i=typeof s=="string"&&o>=t.length&&o<=t.length*2?Os(s):o;if(i===t.length)return;let a=pc(s),c=i>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ai=$("$ZodCheckStringFormat",(e,t)=>{var r,n;Ne.init(e,t),t.pattern?(r=e._zod).check??(r.check=s=>{t.pattern.lastIndex=0,!t.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:t.format,input:s.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Jh=$("$ZodCheckRegex",(e,t)=>{ai.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Yh=$("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Mh),ai.init(e,t)}),Qh=$("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Fh),ai.init(e,t)}),Xh=$("$ZodCheckIncludes",(e,t)=>{Ne.init(e,t);let r=wr(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position},}${r}`:r);t.pattern=n,e._zod.check=s=>{s.value.includes(t.includes,t.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:s.value,inst:e,continue:!t.abort})}}),ey=$("$ZodCheckStartsWith",(e,t)=>{Ne.init(e,t);let r=new RegExp(`^${wr(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),ty=$("$ZodCheckEndsWith",(e,t)=>{Ne.init(e,t);let r=new RegExp(`.*${wr(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});ry=$("$ZodCheckProperty",(e,t)=>{Ne.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(s=>ed(s,r,t.property));ed(n,r,t.property)}}),ny=$("$ZodCheckProperties",(e,t)=>{Ne.init(e,t),mc(e,Symbol.iterator,function*(){yield e});let r;e._zod.check=n=>{if(n.value==null){n.issues.push({expected:"object",code:"invalid_type",input:n.value,inst:e});return}r??(r=Reflect.ownKeys(t.shape).map(i=>[i,t.shape[i]]));let s=n.value,o;for(let[i,a]of r){let c=a._zod.run({value:s[i],issues:[]},{});c instanceof Promise?(o??(o=[]),o.push(c.then(u=>ed(u,n,i)))):ed(c,n,i)}if(o)return Promise.all(o).then(()=>{})}}),sy=$("$ZodCheckMimeType",(e,t)=>{Ne.init(e,t);let r=new Set(t.mime);e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),oy=$("$ZodCheckOverwrite",(e,t)=>{Ne.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}})});var Ds,sd=A(()=>{Ds=class{constructor(t=[],r={}){this.content=[],this.indent=0,this.args=t,this.closed=r}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
4
4
  `).filter(i=>i),s=Math.min(...n.map(i=>i.length-i.trimStart().length)),o=n.map(i=>i.slice(s)).map(i=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let t=Function,r=this?.content??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
5
5
  ${r.join(`
6
6
  `)}
@@ -54,18 +54,18 @@ ${r.join(`
54
54
  newResult[${C}] = ${P}.value;
55
55
  }
56
56
 
57
- `)}return b.write("payload.value = newResult;"),b.write("return payload;"),b.compile()},i,a=$s,c=!ht.jitless,d=c&&jg.value,p=t.catchall,m;e._zod.parse=(f,g)=>{m??(m=n.value);let h=f.value;return a(h)?c&&d&&g?.async===!1&&g.jitless!==!0?(i||(i=o(t.shape)),f=i(f,g),p?sP([],h,f,g,m,e,g?.abortEarly===!0):f):r(f,g):(f.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),f)}});Ac=$("$ZodUnion",(e,t)=>{pe.init(e,t),ye(e,"optin",n=>n.def.options.some(s=>s._zod.optin==="defaulted")?"defaulted":n.def.options.some(s=>s._zod.optin!==void 0)?"optional":void 0),ye(e,"optout",n=>n.def.options.some(s=>s._zod.optout==="optional")?"optional":void 0),ye(e,"values",n=>{if(n.def.options.every(s=>s._zod.values))return new Set(n.def.options.flatMap(s=>Array.from(s._zod.values)))}),ye(e,"pattern",n=>{if(n.def.options.every(s=>s._zod.pattern)){let s=n.def.options.map(o=>o._zod.pattern);return new RegExp(`^(${s.map(o=>dn(o.source)).join("|")})$`)}});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,s)=>{if(r)return r(n,s);let o=!1,i=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},s);if(c instanceof Promise)i.push(c),o=!0;else{if(c.issues.length===0)return c;i.push(c)}}return o?Promise.all(i).then(a=>jC(a,n,e,s)):jC(i,n,e,s)}});Yy=$("$ZodXor",(e,t)=>{Ac.init(e,t),t.inclusive=!1;let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,s)=>{if(r)return r(n,s);let o=!1,i=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},s);c instanceof Promise?(i.push(c),o=!0):i.push(c)}return o?Promise.all(i).then(a=>zC(a,n,e,s)):zC(i,n,e,s)}});Xy=$("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Ac.init(e,t);let r=e._zod.parse;ye(e,"propValues",s=>{let o={},i=0;for(let a of s.def.options){let c=a._zod.propValues;if(!c||Object.keys(c).length===0)throw new Error(`Invalid discriminated union option at index "${s.def.options.indexOf(a)}"`);c[s.def.discriminator]?.has(void 0)&&i++;for(let[u,d]of Object.entries(c)){Object.prototype.hasOwnProperty.call(o,u)||St(o,u,new Set);for(let p of d)o[u].add(p)}}return!s.def.unionFallback&&i>1&&o[s.def.discriminator]?.delete(void 0),o}),t.options.forEach((s,o)=>{let i=ei(s._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw new Error(`Invalid discriminated union option at index "${o}"`)});let n=Xo(()=>iP(t));e._zod.parse=(s,o)=>{let i=s.value;if(!$s(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),s;let a=i?.[t.discriminator],c=n.value.get(a);return c&&(a!==void 0||o.direction!=="backward")?c._zod.run(s,o):t.unionFallback||o.direction==="backward"?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()).filter(u=>n.value.get(u)!==null),input:i,path:[t.discriminator],inst:e}),s)}}),eb=$("$ZodIntersection",(e,t)=>{pe.init(e,t),e._zod.parse=(r,n)=>{let s=r.value,o=t.left._zod.run({value:s,issues:[]},n),i=t.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([c,u])=>BC(r,c,u)):BC(r,o,i)}});Sd=$("$ZodTuple",(e,t)=>{pe.init(e,t);let r=t.items,n=ht.memoizer;n?.attach(e),e._zod.parse=(s,o)=>{let i=s.value;if(!Array.isArray(i))return s.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),s;s.value=n?n.alloc(e,s,[],o):[];let a=[],c=HC(r,"optin"),u=HC(r,"optout");if(!t.rest){if(i.length<c)return s.issues.push({code:"too_small",minimum:c,inclusive:!0,input:i,inst:e,origin:"array"}),s;i.length>r.length&&s.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:i,inst:e,origin:"array"})}let d=new Array(r.length),p=t.rest?o?.abortEarly:void 0,m=!1;for(let f=0;f<r.length;f++){let g=r[f]._zod.run({value:i[f],issues:[]},o);g instanceof Promise?a.push(g.then(h=>{d[f]=h})):(d[f]=g,p&&!m&&g.issues.length&&(m=Lt(g)))}if(t.rest&&!m){let f=r.length-1,g=i.slice(r.length),h=s.issues.length;for(let b of g){if(p&&s.issues.length!==h){if(Lt(s,h))break;h=s.issues.length}f++;let w=t.rest._zod.run({value:b,issues:[]},o);w instanceof Promise?a.push(w.then(y=>WC(y,s,f))):WC(w,s,f)}}return a.length?Promise.all(a).then(()=>VC(d,s,r,i,u)):VC(d,s,r,i,u)}});tb=$("$ZodRecord",(e,t)=>{pe.init(e,t);let r=ht.memoizer;r?.attach(e),e._zod.parse=(n,s)=>{let o=n.value;if(!br(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},s):{};let c=new Set;for(let d of a)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){if(c.add(typeof d=="number"?d.toString():d),d==="__proto__")continue;let p=t.keyType._zod.run({value:d,issues:[]},s);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(g=>qt(g,s,Ye())),input:d,path:[d],inst:e});continue}let m=p.value;if(m==="__proto__")continue;let f=t.valueType._zod.run({value:o[d],issues:[]},s);f instanceof Promise?i.push(f.then(g=>{g.issues.length&&n.issues.push(...Vt(d,g.issues)),n.value[m]=g.value})):(f.issues.length&&n.issues.push(...Vt(d,f.issues)),n.value[m]=f.value)}let u;for(let d in o)if(!c.has(d))if(t.mode==="loose"){if(d==="__proto__")continue;n.value[d]=o[d]}else u=u??[],u.push(d);u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u,continue:!0})}else{n.value=r?r.alloc(e,n,{},s):{};let c;for(let u of Reflect.ownKeys(o)){if(u==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,u))continue;let d=t.keyType._zod.run({value:u,issues:[]},s);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof u=="string"&&pn.test(u)&&d.issues.length){let g=t.keyType._zod.run({value:Number(u),issues:[]},s);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(d=g)}if(d.issues.length){t.mode==="loose"?n.value[u]=o[u]:a?(c=c??[],c.push(u)):n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(g=>qt(g,s,Ye())),input:u,path:[u],inst:e});continue}let m=d.value;if(m==="__proto__")continue;let f=t.valueType._zod.run({value:o[u],issues:[]},s);f instanceof Promise?i.push(f.then(g=>{g.issues.length&&n.issues.push(...Vt(u,g.issues)),n.value[m]=g.value})):(f.issues.length&&n.issues.push(...Vt(u,f.issues)),n.value[m]=f.value)}c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c,continue:!0})}return i.length?Promise.all(i).then(()=>n):n}}),rb=$("$ZodMap",(e,t)=>{pe.init(e,t);let r=ht.memoizer;r?.attach(e),e._zod.parse=(n,s)=>{let o=n.value;if(!(o instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:o,inst:e}),n;let i=[];n.value=r?r.alloc(e,n,new Map,s):new Map;let a=s?.abortEarly,c=n.issues.length;for(let[u,d]of o){if(a&&n.issues.length!==c){if(Lt(n,c))break;c=n.issues.length}let p=t.keyType._zod.run({value:u,issues:[]},s),m=t.valueType._zod.run({value:d,issues:[]},s);p instanceof Promise||m instanceof Promise?i.push(Promise.all([p,m]).then(([f,g])=>{qC(f,g,n,u,o,e,s)})):qC(p,m,n,u,o,e,s)}return i.length?Promise.all(i).then(()=>n):n},Zy(e,mG)});nb=$("$ZodSet",(e,t)=>{pe.init(e,t);let r=ht.memoizer;r?.attach(e),e._zod.parse=(n,s)=>{let o=n.value;if(!(o instanceof Set))return n.issues.push({input:o,inst:e,expected:"set",code:"invalid_type"}),n;let i=[];n.value=r?r.alloc(e,n,new Set,s):new Set;let a=s?.abortEarly,c=n.issues.length;for(let u of o){if(a&&n.issues.length!==c){if(Lt(n,c))break;c=n.issues.length}let d=t.valueType._zod.run({value:u,issues:[]},s);d instanceof Promise?i.push(d.then(p=>ZC(p,n))):ZC(d,n)}return i.length?Promise.all(i).then(()=>n):n},Zy(e,fG)});sb=$("$ZodEnum",(e,t)=>{pe.init(e,t);let r=Yo(t.entries),n=new Set(r);e._zod.values=n,ye(e,"pattern",s=>{let o=Yo(s.def.entries).filter(i=>ac.has(typeof i));return new RegExp(o.length?`^(${o.map(i=>wr(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(s,o)=>{let i=s.value;return n.has(i)||s.issues.push({code:"invalid_value",values:r,input:i,inst:e}),s}}),ob=$("$ZodLiteral",(e,t)=>{pe.init(e,t);let r=new Set(t.values);e._zod.values=r,ye(e,"pattern",n=>{let s=n.def.values;return new RegExp(s.length?`^(${s.map(o=>typeof o=="string"?wr(o):o?wr(o.toString()):String(o)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(n,s)=>{let o=n.value;return r.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),ib=$("$ZodFile",(e,t)=>{pe.init(e,t),e._zod.parse=(r,n)=>{let s=r.value;return s instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:s,inst:e}),r}}),ab=$("$ZodTransform",(e,t)=>{pe.init(e,t),e._zod.optin="optional",ht.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new zn(e.constructor.name);let s=t.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(r.value=i,r));if(s instanceof Promise)throw new Zt;return r.value=s,r}});_d=$("$ZodOptional",(e,t)=>{pe.init(e,t),ye(e,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",ye(e,"values",r=>{let n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),ye(e,"pattern",r=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${dn(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let s=t.innerType._zod.run({value:r.value,issues:[]},n);return s instanceof Promise?s.then(o=>KC(r,o)):KC(r,s)}return t.innerType._zod.run(r,n)}}),cb=$("$ZodExactOptional",(e,t)=>{_d.init(e,t),ye(e,"values",r=>r.def.innerType._zod.values),ye(e,"pattern",r=>r.def.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),ub=$("$ZodNullable",(e,t)=>{pe.init(e,t),ye(e,"optin",r=>r.def.innerType._zod.optin),ye(e,"optout",r=>r.def.innerType._zod.optout),ye(e,"pattern",r=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${dn(n.source)}|null)$`):void 0}),ye(e,"values",r=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),lb=$("$ZodDefault",(e,t)=>{pe.init(e,t),e._zod.optin="defaulted",ye(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>JC(o,t)):JC(s,t)}});db=$("$ZodPrefault",(e,t)=>{pe.init(e,t),e._zod.optin="defaulted",ye(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),pb=$("$ZodNonOptional",(e,t)=>{pe.init(e,t),ye(e,"values",r=>{let n=r.def.innerType._zod.values;return n?new Set([...n].filter(s=>s!==void 0)):void 0}),e._zod.parse=(r,n)=>{let s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>YC(o,e)):YC(s,e)}});mb=$("$ZodSuccess",(e,t)=>{pe.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new zn("ZodSuccess");let s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.issues.length===0,r)):(r.value=s.issues.length===0,r)}});fb=$("$ZodCatch",(e,t)=>{pe.init(e,t),ye(e,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),ye(e,"optout",r=>r.def.innerType._zod.optout),ye(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let s=t.innerType._zod.run({value:r.value,issues:[]},n);return s instanceof Promise?s.then(o=>QC(r,o,t,n)):QC(r,s,t,n)}}),gb=$("$ZodNaN",(e,t)=>{pe.init(e,t),e._zod.parse=(r,n)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r)}),vd=$("$ZodPipe",(e,t)=>{pe.init(e,t),ye(e,"values",r=>r.def.in._zod.values),ye(e,"optin",r=>r.def.in._zod.optin),ye(e,"optout",r=>r.def.out._zod.optout),ye(e,"propValues",r=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let o=t.out._zod.run(r,n);return o instanceof Promise?o.then(i=>od(i,t.in,n)):od(o,t.in,n)}let s=t.in._zod.run(r,n);return s instanceof Promise?s.then(o=>od(o,t.out,n)):od(s,t.out,n)}});Tc=$("$ZodCodec",(e,t)=>{pe.init(e,t),ye(e,"values",r=>r.def.in._zod.values),ye(e,"optin",r=>r.def.in._zod.optin),ye(e,"optout",r=>r.def.out._zod.optout),ye(e,"propValues",r=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if((n.direction||"forward")==="forward"){let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>id(i,t,n)):id(o,t,n)}else{let o=t.out._zod.run(r,n);return o instanceof Promise?o.then(i=>id(i,t,n)):id(o,t,n)}}});hb=$("$ZodPreprocess",(e,t)=>{vd.init(e,t)}),yb=$("$ZodReadonly",(e,t)=>{pe.init(e,t),ye(e,"propValues",r=>r.def.innerType._zod.propValues),ye(e,"values",r=>r.def.innerType._zod.values),ye(e,"optin",r=>r.def.innerType?._zod?.optin),ye(e,"optout",r=>r.def.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(XC):XC(s)}});bb=$("$ZodTemplateLiteral",(e,t)=>{pe.init(e,t);let r=[];for(let n of t.parts)if(typeof n=="object"&&n!==null){let s=cy(n);if(!s)throw new Error(`Invalid template literal part, no pattern found: ${[...n._zod.traits].shift()}`);r.push(dn(s))}else if(n===null||zg.has(typeof n))r.push(wr(`${n}`));else throw new Error(`Invalid template literal part: ${n}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(n,s)=>typeof n.value!="string"?(n.issues.push({input:n.value,inst:e,expected:"string",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)}),wb=$("$ZodFunction",(e,t)=>(pe.init(e,t),Object.defineProperty(e,"_def",{value:t}),e._zod.def=t,e.implement=r=>{if(typeof r!="function")throw new Error("implement() must be called with a function");return Object.defineProperty(function(...n){let s=e._def.input?jl(e._def.input,n):n,o=Reflect.apply(r,this,s);return e._def.output?jl(e._def.output,o):o},"_zod",{value:e._zod,enumerable:!1})},e.implementAsync=r=>{if(typeof r!="function")throw new Error("implementAsync() must be called with a function");return Object.defineProperty(async function(...n){let s=e._def.input?await zl(e._def.input,n):n,o=await Reflect.apply(r,this,s);return e._def.output?await zl(e._def.output,o):o},"_zod",{value:e._zod,enumerable:!1})},e._zod.parse=(r,n)=>typeof r.value!="function"?(r.issues.push({code:"invalid_type",expected:"function",input:r.value,inst:e}),r):(e._def.output&&e._def.output._zod.def.type==="promise"?r.value=e.implementAsync(r.value):r.value=e.implement(r.value),r),e.input=(...r)=>{let n=e.constructor;return Array.isArray(r[0])?new n({type:"function",input:new Sd({type:"tuple",items:r[0],rest:r[1]}),output:e._def.output}):new n({type:"function",input:r[0],output:e._def.output})},e.output=r=>{let n=e.constructor;return new n({type:"function",input:e._def.input,output:r})},e)),Rb=$("$ZodPromise",(e,t)=>{pe.init(e,t),e._zod.parse=(r,n)=>Promise.resolve(r.value).then(s=>t.innerType._zod.run({value:s,issues:[]},n))}),$c=$("$ZodLazy",(e,t)=>{pe.init(e,t),Gg(e._zod,"innerType",()=>{let r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),ye(e,"pattern",r=>r.innerType?._zod?.pattern),ye(e,"propValues",r=>r.innerType?._zod?.propValues),ye(e,"optin",r=>r.innerType?._zod?.optin??void 0),ye(e,"optout",r=>r.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Sb=$("$ZodCustom",(e,t)=>{Fe.init(e,t),pe.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,s=t.fn(n);if(s instanceof Promise)return s.then(o=>eP(o,r,n,e));eP(s,r,n,e)}})});function uP(e){return e!==null&&typeof e=="object"}function _b(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}function Ic(e,t,r){let n=lP.get(e);if(n!==void 0)return n?Oc:li;if(t.has(e))return Oc;t.add(e);let s=li,o=d=>{if(s!==Oc&&d?._zod){let p=Ic(d,t,r);p>s&&(s=p)}},i=(d,p)=>{let m=li;for(let f of Reflect.ownKeys(d)){let g=Object.getOwnPropertyDescriptor(d,f);if(p&&!g.enumerable)continue;let h=g.get?Pd:g.value?._zod?Ic(g.value,t,r):li;h>m&&(m=h)}return m},a=d=>{d>s&&(s=d)},c=e._zod.def,u=c.type;switch(u){case"object":{let d=ei(c);a(d?i(d,!0):Pd),o(c.catchall);break}case"array":o(c.element);break;case"tuple":for(let d of c.items)o(d);o(c.rest);break;case"record":case"map":o(c.keyType),o(c.valueType);break;case"set":o(c.valueType);break;case"union":for(let d of c.options)o(d);break;case"intersection":o(c.left),o(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(c.innerType);break;case"pipe":o(c.in),o(c.out);break;case"function":o(c.input),o(c.output);break;case"lazy":{let d=c._cachedInner??(r?e._zod.innerType:void 0);a(d?Ic(d,t,!1):Pd);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let d in c){let p=Object.getOwnPropertyDescriptor(c,d);if(!p||p.get)continue;let m=p.value;if(!(!m||typeof m!="object")){if(m._zod)o(m);else if(Array.isArray(m))for(let f of m)o(f)}}}return t.delete(e),yG(e,s)}function yG(e,t){return t!==Pd&&lP.set(e,t===Oc),t}function Ad(e){return Ic(e,new Set,!0)!==li}function bG(e,t){let r=e.buckets.get(t);return r||(r=new WeakMap,e.buckets.set(t,r)),r}function xc(){return wG}function Td(e,t){let r=e[vb]?.backEdges;return r!==void 0&&uP(t)&&r.has(t)}var Ed,vb,cP,lP,li,Pd,Oc,kd,Cd,wG,kb=A(()=>{rt();Ed=class extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}},vb="~memo",cP=[];lP=new WeakMap,li=0,Pd=1,Oc=2;Cd=[],wG={alloc(e,t,r){let n=kd;if(!n)return r;kd=void 0;let s={value:r,issues:null};return n.set(t.value,s),Cd.push(s),r},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,n=(s,o)=>{if(o.direction!=="backward"&&Td(o,s.value))throw new Ed;return r(s,o)};e._zod.parse=n,e._zod.run===r&&(e._zod.run=n)})},attach(e){var t;let r,n=!1,s,o;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,a=(c,u)=>{if(r===void 0){let w=Ic(e,new Set,!1);if(w===li)return e._zod.parse=i,e._zod.run===a&&(e._zod.run=i),i(c,u);w===Oc||n?r=!0:n=!0}let d=c.value;if(!uP(d))return i(c,u);let p=u[vb];p||(p={buckets:new WeakMap,backEdges:void 0},u[vb]=p);let m;s===u?m=o:(m=bG(p,e),s=u,o=m);let f=m.get(d);if(f)return c.value=f.value,f.issues?f.issues.length&&c.issues.push(..._b(f.issues)):(c.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(f.value)),c;kd=m;let g=Cd.length,h=i(c,u);kd=void 0;let b=Cd.length>g?Cd.pop():void 0;return h instanceof Promise?h.then(w=>(b&&(b.issues=w.issues.length?_b(w.issues):cP),w)):(b&&(b.issues=h.issues.length?_b(h.issues):cP),h)};e._zod.parse=a,e._zod.run===i&&(e._zod.run=a)})}}});function $d(){return{localeError:RG()}}var RG,Cb=A(()=>{rt();RG=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};function s(o,i){return o==="number"&&typeof i=="number"&&!Number.isFinite(i)?String(i):n[o]??o}return o=>{switch(o.code){case"invalid_type":{let i=s(o.expected),a=Wg(o.input),c=s(a,o.input);return`Invalid input: expected ${i}, received ${c}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${Fl(o.values[0])}`:`Invalid option: expected one of ${Dl(o.values,"|")}`;case"too_big":{let i=o.exact?"exactly ":o.inclusive?"<=":"<",a=t(o.origin);return a?`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.exact?"exactly ":o.inclusive?">=":">",a=t(o.origin);return a?`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${a.unit}`:`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Dl(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(a=>`'${a}'`).join(" | ")}`:o.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}}});var Dc={};re(Dc,{en:()=>$d});var Pb=A(()=>{Cb()});function Id(){return new Od}var dP,Eb,Ab,Od,_t,Lc=A(()=>{Eb=Symbol("ZodOutput"),Ab=Symbol("ZodInput"),Od=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let s={...n,...this._map.get(t)};return Object.keys(s).length?s:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};(dP=globalThis).__zod_globalRegistry??(dP.__zod_globalRegistry=Id());_t=globalThis.__zod_globalRegistry});function _G(e,t){try{return Dd(e,{assertOnly:!0})}catch{return t}}function Ib(e,t){try{let r=Dd(e),n=xd(e,r);return n._zod.bag.validator=_G(e,r),n}catch(r){if(t?.strict)throw r;return e}}function xd(e,t){if(Ad(e))throw new Se("a schema whose subtree contains a reference cycle");let r=Oe(e),n=e._zod.run,s=n.__originalRun??n,o=(i,a)=>{if(a?.async||a?.direction==="backward"||a?.skipChecks||a?.[pP]||a&&Td(a,i.value))return s(i,a);let c=t(i.value);return c!==Mt?(i.value=c,i):(a&&(a[pP]=!0),s(i,a))};return o.__originalRun=s,r._zod.bag.fallbackRun=s,r._zod.bag.validator=t,r._zod.run=o,n.__originalRun||vG(r,e,t),r}function vG(e,t,r){let n=e,s=t;if(typeof s.safeParse=="function"){let o=s.safeParse;n.safeParse=(i,a)=>{let c=r(i);return c!==Mt?{success:!0,data:c}:o(i,a)}}if(typeof s.parse=="function"){let o=s.parse;n.parse=(i,a)=>{let c=r(i);return c!==Mt?c:o(i,a)}}}function Dd(e,t){let r=!0;try{r=Ad(e)}catch{}if(r)throw new Se("a schema whose subtree contains a reference cycle");let n={constants:new Map,constantCounter:0,varCounter:0,definite:!0},s=new Ds(["input"]),o=Ve(s,n,e,"input",!t?.assertOnly);s.write(o===null?"return true;":`return ${o};`);let i=["INVALID",...n.constants.keys()],a=[Mt,...n.constants.values()],c=s.content.join(`
57
+ `)}return b.write("payload.value = newResult;"),b.write("return payload;"),b.compile()},i,a=$s,c=!ht.jitless,d=c&&jg.value,p=t.catchall,m;e._zod.parse=(f,g)=>{m??(m=n.value);let h=f.value;return a(h)?c&&d&&g?.async===!1&&g.jitless!==!0?(i||(i=o(t.shape)),f=i(f,g),p?sP([],h,f,g,m,e,g?.abortEarly===!0):f):r(f,g):(f.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),f)}});Ac=$("$ZodUnion",(e,t)=>{pe.init(e,t),ye(e,"optin",n=>n.def.options.some(s=>s._zod.optin==="defaulted")?"defaulted":n.def.options.some(s=>s._zod.optin!==void 0)?"optional":void 0),ye(e,"optout",n=>n.def.options.some(s=>s._zod.optout==="optional")?"optional":void 0),ye(e,"values",n=>{if(n.def.options.every(s=>s._zod.values))return new Set(n.def.options.flatMap(s=>Array.from(s._zod.values)))}),ye(e,"pattern",n=>{if(n.def.options.every(s=>s._zod.pattern)){let s=n.def.options.map(o=>o._zod.pattern);return new RegExp(`^(${s.map(o=>dn(o.source)).join("|")})$`)}});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,s)=>{if(r)return r(n,s);let o=!1,i=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},s);if(c instanceof Promise)i.push(c),o=!0;else{if(c.issues.length===0)return c;i.push(c)}}return o?Promise.all(i).then(a=>jC(a,n,e,s)):jC(i,n,e,s)}});Yy=$("$ZodXor",(e,t)=>{Ac.init(e,t),t.inclusive=!1;let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,s)=>{if(r)return r(n,s);let o=!1,i=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},s);c instanceof Promise?(i.push(c),o=!0):i.push(c)}return o?Promise.all(i).then(a=>zC(a,n,e,s)):zC(i,n,e,s)}});Xy=$("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Ac.init(e,t);let r=e._zod.parse;ye(e,"propValues",s=>{let o={},i=0;for(let a of s.def.options){let c=a._zod.propValues;if(!c||Object.keys(c).length===0)throw new Error(`Invalid discriminated union option at index "${s.def.options.indexOf(a)}"`);c[s.def.discriminator]?.has(void 0)&&i++;for(let[u,d]of Object.entries(c)){Object.prototype.hasOwnProperty.call(o,u)||St(o,u,new Set);for(let p of d)o[u].add(p)}}return!s.def.unionFallback&&i>1&&o[s.def.discriminator]?.delete(void 0),o}),t.options.forEach((s,o)=>{let i=ei(s._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw new Error(`Invalid discriminated union option at index "${o}"`)});let n=Xo(()=>iP(t));e._zod.parse=(s,o)=>{let i=s.value;if(!$s(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),s;let a=i?.[t.discriminator],c=n.value.get(a);return c&&(a!==void 0||o.direction!=="backward")?c._zod.run(s,o):t.unionFallback||o.direction==="backward"?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()).filter(u=>n.value.get(u)!==null),input:i,path:[t.discriminator],inst:e}),s)}}),eb=$("$ZodIntersection",(e,t)=>{pe.init(e,t),e._zod.parse=(r,n)=>{let s=r.value,o=t.left._zod.run({value:s,issues:[]},n),i=t.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([c,u])=>BC(r,c,u)):BC(r,o,i)}});Sd=$("$ZodTuple",(e,t)=>{pe.init(e,t);let r=t.items,n=ht.memoizer;n?.attach(e),e._zod.parse=(s,o)=>{let i=s.value;if(!Array.isArray(i))return s.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),s;s.value=n?n.alloc(e,s,[],o):[];let a=[],c=HC(r,"optin"),u=HC(r,"optout");if(!t.rest){if(i.length<c)return s.issues.push({code:"too_small",minimum:c,inclusive:!0,input:i,inst:e,origin:"array"}),s;i.length>r.length&&s.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:i,inst:e,origin:"array"})}let d=new Array(r.length),p=t.rest?o?.abortEarly:void 0,m=!1;for(let f=0;f<r.length;f++){let g=r[f]._zod.run({value:i[f],issues:[]},o);g instanceof Promise?a.push(g.then(h=>{d[f]=h})):(d[f]=g,p&&!m&&g.issues.length&&(m=Lt(g)))}if(t.rest&&!m){let f=r.length-1,g=i.slice(r.length),h=s.issues.length;for(let b of g){if(p&&s.issues.length!==h){if(Lt(s,h))break;h=s.issues.length}f++;let w=t.rest._zod.run({value:b,issues:[]},o);w instanceof Promise?a.push(w.then(y=>WC(y,s,f))):WC(w,s,f)}}return a.length?Promise.all(a).then(()=>VC(d,s,r,i,u)):VC(d,s,r,i,u)}});tb=$("$ZodRecord",(e,t)=>{pe.init(e,t);let r=ht.memoizer;r?.attach(e),e._zod.parse=(n,s)=>{let o=n.value;if(!br(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},s):{};let c=new Set;for(let d of a)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){if(c.add(typeof d=="number"?d.toString():d),d==="__proto__")continue;let p=t.keyType._zod.run({value:d,issues:[]},s);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(g=>qt(g,s,Ye())),input:d,path:[d],inst:e});continue}let m=p.value;if(m==="__proto__")continue;let f=t.valueType._zod.run({value:o[d],issues:[]},s);f instanceof Promise?i.push(f.then(g=>{g.issues.length&&n.issues.push(...Vt(d,g.issues)),n.value[m]=g.value})):(f.issues.length&&n.issues.push(...Vt(d,f.issues)),n.value[m]=f.value)}let u;for(let d in o)if(!c.has(d))if(t.mode==="loose"){if(d==="__proto__")continue;n.value[d]=o[d]}else u=u??[],u.push(d);u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u,continue:!0})}else{n.value=r?r.alloc(e,n,{},s):{};let c;for(let u of Reflect.ownKeys(o)){if(u==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,u))continue;let d=t.keyType._zod.run({value:u,issues:[]},s);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof u=="string"&&pn.test(u)&&d.issues.length){let g=t.keyType._zod.run({value:Number(u),issues:[]},s);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(d=g)}if(d.issues.length){t.mode==="loose"?n.value[u]=o[u]:a?(c=c??[],c.push(u)):n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(g=>qt(g,s,Ye())),input:u,path:[u],inst:e});continue}let m=d.value;if(m==="__proto__")continue;let f=t.valueType._zod.run({value:o[u],issues:[]},s);f instanceof Promise?i.push(f.then(g=>{g.issues.length&&n.issues.push(...Vt(u,g.issues)),n.value[m]=g.value})):(f.issues.length&&n.issues.push(...Vt(u,f.issues)),n.value[m]=f.value)}c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c,continue:!0})}return i.length?Promise.all(i).then(()=>n):n}}),rb=$("$ZodMap",(e,t)=>{pe.init(e,t);let r=ht.memoizer;r?.attach(e),e._zod.parse=(n,s)=>{let o=n.value;if(!(o instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:o,inst:e}),n;let i=[];n.value=r?r.alloc(e,n,new Map,s):new Map;let a=s?.abortEarly,c=n.issues.length;for(let[u,d]of o){if(a&&n.issues.length!==c){if(Lt(n,c))break;c=n.issues.length}let p=t.keyType._zod.run({value:u,issues:[]},s),m=t.valueType._zod.run({value:d,issues:[]},s);p instanceof Promise||m instanceof Promise?i.push(Promise.all([p,m]).then(([f,g])=>{qC(f,g,n,u,o,e,s)})):qC(p,m,n,u,o,e,s)}return i.length?Promise.all(i).then(()=>n):n},Zy(e,mG)});nb=$("$ZodSet",(e,t)=>{pe.init(e,t);let r=ht.memoizer;r?.attach(e),e._zod.parse=(n,s)=>{let o=n.value;if(!(o instanceof Set))return n.issues.push({input:o,inst:e,expected:"set",code:"invalid_type"}),n;let i=[];n.value=r?r.alloc(e,n,new Set,s):new Set;let a=s?.abortEarly,c=n.issues.length;for(let u of o){if(a&&n.issues.length!==c){if(Lt(n,c))break;c=n.issues.length}let d=t.valueType._zod.run({value:u,issues:[]},s);d instanceof Promise?i.push(d.then(p=>ZC(p,n))):ZC(d,n)}return i.length?Promise.all(i).then(()=>n):n},Zy(e,fG)});sb=$("$ZodEnum",(e,t)=>{pe.init(e,t);let r=Yo(t.entries),n=new Set(r);e._zod.values=n,ye(e,"pattern",s=>{let o=Yo(s.def.entries).filter(i=>ac.has(typeof i));return new RegExp(o.length?`^(${o.map(i=>wr(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(s,o)=>{let i=s.value;return n.has(i)||s.issues.push({code:"invalid_value",values:r,input:i,inst:e}),s}}),ob=$("$ZodLiteral",(e,t)=>{pe.init(e,t);let r=new Set(t.values);e._zod.values=r,ye(e,"pattern",n=>{let s=n.def.values;return new RegExp(s.length?`^(${s.map(o=>typeof o=="string"?wr(o):o?wr(o.toString()):String(o)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(n,s)=>{let o=n.value;return r.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),ib=$("$ZodFile",(e,t)=>{pe.init(e,t),e._zod.parse=(r,n)=>{let s=r.value;return s instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:s,inst:e}),r}}),ab=$("$ZodTransform",(e,t)=>{pe.init(e,t),e._zod.optin="optional",ht.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new zn(e.constructor.name);let s=t.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(r.value=i,r));if(s instanceof Promise)throw new Zt;return r.value=s,r}});_d=$("$ZodOptional",(e,t)=>{pe.init(e,t),ye(e,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",ye(e,"values",r=>{let n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),ye(e,"pattern",r=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${dn(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let s=t.innerType._zod.run({value:r.value,issues:[]},n);return s instanceof Promise?s.then(o=>KC(r,o)):KC(r,s)}return t.innerType._zod.run(r,n)}}),cb=$("$ZodExactOptional",(e,t)=>{_d.init(e,t),ye(e,"values",r=>r.def.innerType._zod.values),ye(e,"pattern",r=>r.def.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),ub=$("$ZodNullable",(e,t)=>{pe.init(e,t),ye(e,"optin",r=>r.def.innerType._zod.optin),ye(e,"optout",r=>r.def.innerType._zod.optout),ye(e,"pattern",r=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${dn(n.source)}|null)$`):void 0}),ye(e,"values",r=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),lb=$("$ZodDefault",(e,t)=>{pe.init(e,t),e._zod.optin="defaulted",ye(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>JC(o,t)):JC(s,t)}});db=$("$ZodPrefault",(e,t)=>{pe.init(e,t),e._zod.optin="defaulted",ye(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),pb=$("$ZodNonOptional",(e,t)=>{pe.init(e,t),ye(e,"values",r=>{let n=r.def.innerType._zod.values;return n?new Set([...n].filter(s=>s!==void 0)):void 0}),e._zod.parse=(r,n)=>{let s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>YC(o,e)):YC(s,e)}});mb=$("$ZodSuccess",(e,t)=>{pe.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new zn("ZodSuccess");let s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.issues.length===0,r)):(r.value=s.issues.length===0,r)}});fb=$("$ZodCatch",(e,t)=>{pe.init(e,t),ye(e,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),ye(e,"optout",r=>r.def.innerType._zod.optout),ye(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let s=t.innerType._zod.run({value:r.value,issues:[]},n);return s instanceof Promise?s.then(o=>QC(r,o,t,n)):QC(r,s,t,n)}}),gb=$("$ZodNaN",(e,t)=>{pe.init(e,t),e._zod.parse=(r,n)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r)}),vd=$("$ZodPipe",(e,t)=>{pe.init(e,t),ye(e,"values",r=>r.def.in._zod.values),ye(e,"optin",r=>r.def.in._zod.optin),ye(e,"optout",r=>r.def.out._zod.optout),ye(e,"propValues",r=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let o=t.out._zod.run(r,n);return o instanceof Promise?o.then(i=>od(i,t.in,n)):od(o,t.in,n)}let s=t.in._zod.run(r,n);return s instanceof Promise?s.then(o=>od(o,t.out,n)):od(s,t.out,n)}});Tc=$("$ZodCodec",(e,t)=>{pe.init(e,t),ye(e,"values",r=>r.def.in._zod.values),ye(e,"optin",r=>r.def.in._zod.optin),ye(e,"optout",r=>r.def.out._zod.optout),ye(e,"propValues",r=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if((n.direction||"forward")==="forward"){let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>id(i,t,n)):id(o,t,n)}else{let o=t.out._zod.run(r,n);return o instanceof Promise?o.then(i=>id(i,t,n)):id(o,t,n)}}});hb=$("$ZodPreprocess",(e,t)=>{vd.init(e,t)}),yb=$("$ZodReadonly",(e,t)=>{pe.init(e,t),ye(e,"propValues",r=>r.def.innerType._zod.propValues),ye(e,"values",r=>r.def.innerType._zod.values),ye(e,"optin",r=>r.def.innerType?._zod?.optin),ye(e,"optout",r=>r.def.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(XC):XC(s)}});bb=$("$ZodTemplateLiteral",(e,t)=>{pe.init(e,t);let r=[];for(let n of t.parts)if(typeof n=="object"&&n!==null){let s=cy(n);if(!s)throw new Error(`Invalid template literal part, no pattern found: ${[...n._zod.traits].shift()}`);r.push(dn(s))}else if(n===null||zg.has(typeof n))r.push(wr(`${n}`));else throw new Error(`Invalid template literal part: ${n}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(n,s)=>typeof n.value!="string"?(n.issues.push({input:n.value,inst:e,expected:"string",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)}),wb=$("$ZodFunction",(e,t)=>(pe.init(e,t),Object.defineProperty(e,"_def",{value:t}),e._zod.def=t,e.implement=r=>{if(typeof r!="function")throw new Error("implement() must be called with a function");return Object.defineProperty(function(...n){let s=e._def.input?jl(e._def.input,n):n,o=Reflect.apply(r,this,s);return e._def.output?jl(e._def.output,o):o},"_zod",{value:e._zod,enumerable:!1})},e.implementAsync=r=>{if(typeof r!="function")throw new Error("implementAsync() must be called with a function");return Object.defineProperty(async function(...n){let s=e._def.input?await zl(e._def.input,n):n,o=await Reflect.apply(r,this,s);return e._def.output?await zl(e._def.output,o):o},"_zod",{value:e._zod,enumerable:!1})},e._zod.parse=(r,n)=>typeof r.value!="function"?(r.issues.push({code:"invalid_type",expected:"function",input:r.value,inst:e}),r):(e._def.output&&e._def.output._zod.def.type==="promise"?r.value=e.implementAsync(r.value):r.value=e.implement(r.value),r),e.input=(...r)=>{let n=e.constructor;return Array.isArray(r[0])?new n({type:"function",input:new Sd({type:"tuple",items:r[0],rest:r[1]}),output:e._def.output}):new n({type:"function",input:r[0],output:e._def.output})},e.output=r=>{let n=e.constructor;return new n({type:"function",input:e._def.input,output:r})},e)),Rb=$("$ZodPromise",(e,t)=>{pe.init(e,t),e._zod.parse=(r,n)=>Promise.resolve(r.value).then(s=>t.innerType._zod.run({value:s,issues:[]},n))}),$c=$("$ZodLazy",(e,t)=>{pe.init(e,t),Gg(e._zod,"innerType",()=>{let r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),ye(e,"pattern",r=>r.innerType?._zod?.pattern),ye(e,"propValues",r=>r.innerType?._zod?.propValues),ye(e,"optin",r=>r.innerType?._zod?.optin??void 0),ye(e,"optout",r=>r.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Sb=$("$ZodCustom",(e,t)=>{Ne.init(e,t),pe.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,s=t.fn(n);if(s instanceof Promise)return s.then(o=>eP(o,r,n,e));eP(s,r,n,e)}})});function uP(e){return e!==null&&typeof e=="object"}function _b(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}function Ic(e,t,r){let n=lP.get(e);if(n!==void 0)return n?Oc:li;if(t.has(e))return Oc;t.add(e);let s=li,o=d=>{if(s!==Oc&&d?._zod){let p=Ic(d,t,r);p>s&&(s=p)}},i=(d,p)=>{let m=li;for(let f of Reflect.ownKeys(d)){let g=Object.getOwnPropertyDescriptor(d,f);if(p&&!g.enumerable)continue;let h=g.get?Pd:g.value?._zod?Ic(g.value,t,r):li;h>m&&(m=h)}return m},a=d=>{d>s&&(s=d)},c=e._zod.def,u=c.type;switch(u){case"object":{let d=ei(c);a(d?i(d,!0):Pd),o(c.catchall);break}case"array":o(c.element);break;case"tuple":for(let d of c.items)o(d);o(c.rest);break;case"record":case"map":o(c.keyType),o(c.valueType);break;case"set":o(c.valueType);break;case"union":for(let d of c.options)o(d);break;case"intersection":o(c.left),o(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(c.innerType);break;case"pipe":o(c.in),o(c.out);break;case"function":o(c.input),o(c.output);break;case"lazy":{let d=c._cachedInner??(r?e._zod.innerType:void 0);a(d?Ic(d,t,!1):Pd);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let d in c){let p=Object.getOwnPropertyDescriptor(c,d);if(!p||p.get)continue;let m=p.value;if(!(!m||typeof m!="object")){if(m._zod)o(m);else if(Array.isArray(m))for(let f of m)o(f)}}}return t.delete(e),yG(e,s)}function yG(e,t){return t!==Pd&&lP.set(e,t===Oc),t}function Ad(e){return Ic(e,new Set,!0)!==li}function bG(e,t){let r=e.buckets.get(t);return r||(r=new WeakMap,e.buckets.set(t,r)),r}function xc(){return wG}function Td(e,t){let r=e[vb]?.backEdges;return r!==void 0&&uP(t)&&r.has(t)}var Ed,vb,cP,lP,li,Pd,Oc,kd,Cd,wG,kb=A(()=>{rt();Ed=class extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}},vb="~memo",cP=[];lP=new WeakMap,li=0,Pd=1,Oc=2;Cd=[],wG={alloc(e,t,r){let n=kd;if(!n)return r;kd=void 0;let s={value:r,issues:null};return n.set(t.value,s),Cd.push(s),r},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,n=(s,o)=>{if(o.direction!=="backward"&&Td(o,s.value))throw new Ed;return r(s,o)};e._zod.parse=n,e._zod.run===r&&(e._zod.run=n)})},attach(e){var t;let r,n=!1,s,o;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,a=(c,u)=>{if(r===void 0){let w=Ic(e,new Set,!1);if(w===li)return e._zod.parse=i,e._zod.run===a&&(e._zod.run=i),i(c,u);w===Oc||n?r=!0:n=!0}let d=c.value;if(!uP(d))return i(c,u);let p=u[vb];p||(p={buckets:new WeakMap,backEdges:void 0},u[vb]=p);let m;s===u?m=o:(m=bG(p,e),s=u,o=m);let f=m.get(d);if(f)return c.value=f.value,f.issues?f.issues.length&&c.issues.push(..._b(f.issues)):(c.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(f.value)),c;kd=m;let g=Cd.length,h=i(c,u);kd=void 0;let b=Cd.length>g?Cd.pop():void 0;return h instanceof Promise?h.then(w=>(b&&(b.issues=w.issues.length?_b(w.issues):cP),w)):(b&&(b.issues=h.issues.length?_b(h.issues):cP),h)};e._zod.parse=a,e._zod.run===i&&(e._zod.run=a)})}}});function $d(){return{localeError:RG()}}var RG,Cb=A(()=>{rt();RG=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};function s(o,i){return o==="number"&&typeof i=="number"&&!Number.isFinite(i)?String(i):n[o]??o}return o=>{switch(o.code){case"invalid_type":{let i=s(o.expected),a=Wg(o.input),c=s(a,o.input);return`Invalid input: expected ${i}, received ${c}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${Fl(o.values[0])}`:`Invalid option: expected one of ${Dl(o.values,"|")}`;case"too_big":{let i=o.exact?"exactly ":o.inclusive?"<=":"<",a=t(o.origin);return a?`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.exact?"exactly ":o.inclusive?">=":">",a=t(o.origin);return a?`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${a.unit}`:`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Dl(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(a=>`'${a}'`).join(" | ")}`:o.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}}});var Dc={};re(Dc,{en:()=>$d});var Pb=A(()=>{Cb()});function Id(){return new Od}var dP,Eb,Ab,Od,_t,Lc=A(()=>{Eb=Symbol("ZodOutput"),Ab=Symbol("ZodInput"),Od=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let s={...n,...this._map.get(t)};return Object.keys(s).length?s:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};(dP=globalThis).__zod_globalRegistry??(dP.__zod_globalRegistry=Id());_t=globalThis.__zod_globalRegistry});function _G(e,t){try{return Dd(e,{assertOnly:!0})}catch{return t}}function Ib(e,t){try{let r=Dd(e),n=xd(e,r);return n._zod.bag.validator=_G(e,r),n}catch(r){if(t?.strict)throw r;return e}}function xd(e,t){if(Ad(e))throw new Se("a schema whose subtree contains a reference cycle");let r=Oe(e),n=e._zod.run,s=n.__originalRun??n,o=(i,a)=>{if(a?.async||a?.direction==="backward"||a?.skipChecks||a?.[pP]||a&&Td(a,i.value))return s(i,a);let c=t(i.value);return c!==Mt?(i.value=c,i):(a&&(a[pP]=!0),s(i,a))};return o.__originalRun=s,r._zod.bag.fallbackRun=s,r._zod.bag.validator=t,r._zod.run=o,n.__originalRun||vG(r,e,t),r}function vG(e,t,r){let n=e,s=t;if(typeof s.safeParse=="function"){let o=s.safeParse;n.safeParse=(i,a)=>{let c=r(i);return c!==Mt?{success:!0,data:c}:o(i,a)}}if(typeof s.parse=="function"){let o=s.parse;n.parse=(i,a)=>{let c=r(i);return c!==Mt?c:o(i,a)}}}function Dd(e,t){let r=!0;try{r=Ad(e)}catch{}if(r)throw new Se("a schema whose subtree contains a reference cycle");let n={constants:new Map,constantCounter:0,varCounter:0,definite:!0},s=new Ds(["input"]),o=Ve(s,n,e,"input",!t?.assertOnly);s.write(o===null?"return true;":`return ${o};`);let i=["INVALID",...n.constants.keys()],a=[Mt,...n.constants.values()],c=s.content.join(`
58
58
  `),u=t?.debug?i.length>0?`// Constants: ${i.join(", ")}
59
59
  ${c}`:c:"",d=Function,p=`return (input) => {
60
60
  ${c}
61
- }`,m;try{m=new d(...i,p)(...a)}catch(f){throw new Se(`this schema (generated code failed to evaluate: ${f.message})`)}return t?.debug&&(m.code=u),m.definite=n.definite,m}function ue(e,t){for(let[n,s]of e.constants)if(s===t)return n;let r=`c${e.constantCounter++}`;return e.constants.set(r,t),r}function Fs(e,t){return e.definite=!1,ue(e,t)}function te(e){return`v${e.varCounter++}`}function kG(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return Mt;let n=r;return n.issues.length===0?n.value:Mt}function Tt(e,t,r,n,s=!0){let o=e.content.length,i=t.constants.size,a=t.constantCounter,c=t.varCounter;try{return Ve(e,t,r,n,s)}catch(u){if(!(u instanceof Se)||!u.islandable)throw u;if(e.content.length=o,t.constants.size>i){let d=Array.from(t.constants.keys()).slice(i);for(let p of d)t.constants.delete(p)}return t.constantCounter=a,t.varCounter=c,CG(e,t,r,n)}}function CG(e,t,r,n){t.definite=!1;let s=ue(t,r),o=ue(t,kG),i=te(t);return e.write(`const ${i} = ${o}(${s}, ${n});`),e.write(`if (${i} === INVALID) return INVALID;`),i}function EG(e,t,r,n){let s=r._zod.def.checks;if(!s||s.length===0)return n;let o=n;for(let i of s){let a=i._zod.def;if(a.when&&!PG.has(a.check))throw new Se('check with a custom "when" condition');switch(a.check){case"greater_than":AG(e,t,a,o);break;case"less_than":TG(e,t,a,o);break;case"multiple_of":$G(e,t,a,o);break;case"number_format":bP(e,a,o);break;case"min_length":{let c=Bn(a.minimum,"min_length"),u=Tb(e,t,o,`${o}.length >= ${c} && ${o}.length < ${a.minimum*2}`);e.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=Bn(a.maximum,"max_length"),u=Tb(e,t,o,`${o}.length > ${c}`);e.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=Bn(a.length,"length_equals"),u=Tb(e,t,o,`${o}.length >= ${c} && ${o}.length <= ${a.length*2}`);e.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":e.write(`if (${o}.size < ${Bn(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${o}.size > ${Bn(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${o}.size !== ${Bn(a.size,"size_equals")}) return INVALID;`);break;case"string_format":o=wP(e,t,a,o);break;case"custom":o=MG(e,t,i,o);break;case"bigint_format":OG(e,a,o);break;case"mime_type":IG(e,t,a,o);break;case"property":DG(e,t,a,o);break;case"properties":xG(e,t,a,o);break;case"overwrite":{let c=te(t);LG(e,t,i,o,c),o=c;break}default:throw new Se(`check type ${a.check}`)}}return o}function Tb(e,t,r,n){let s=ue(t,Os),o=te(t);return e.write(`const ${o} = typeof ${r} === "string" && ${n} ? ${s}(${r}) : ${r}.length;`),o}function Bn(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Se(`${t} bound of type ${typeof e}`);return`${e}`}function yP(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new Se("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new Se("comparison check with Invalid Date bound");return ue(e,t)}throw new Se(`comparison check bound of type ${typeof t}`)}function AG(e,t,r,n){let s=r.inclusive?"<":"<=";e.write(`if (${n} ${s} ${yP(t,r.value)}) return INVALID;`)}function TG(e,t,r,n){let s=r.inclusive?">":">=";e.write(`if (${n} ${s} ${yP(t,r.value)}) return INVALID;`)}function $G(e,t,r,n){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Se("multiple_of check with a zero divisor");e.write(`if (${n} % ${r.value}n !== 0n) return INVALID;`)}else{let s=ue(t,oc);e.write(`if (${s}(${n}, ${Bn(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function bP(e,t,r){let n=t.format;switch(n){case"safeint":e.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new Se(`number format ${n}`)}}function OG(e,t,r){let n=t.format;if(n)switch(n){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new Se(`bigint format ${n}`)}}function IG(e,t,r,n){let s=r.mime;if(s&&s.length>0){let o=ue(t,new Set(s));e.write(`if (!${o}.has(${n}.type)) return INVALID;`)}}function xG(e,t,r,n){if(r.when)throw new Se('check with a custom "when" condition');e.write(`if (${n} == null) return INVALID;`);let s=r.shape;for(let o of Reflect.ownKeys(s)){let i=typeof o=="symbol"?ue(t,o):Dt(o),a=te(t);e.write(`const ${a} = ${n}[${i}];`),Tt(e,t,s[o],a,!1)}}function DG(e,t,r,n){let s=`${n}[${JSON.stringify(r.property)}]`;Ve(e,t,r.schema,s)}function LG(e,t,r,n,s){let o=r._zod.def.tx;if(!o)throw new Se("overwrite check without a transform function");if(Ns(o))throw new Pr("z.compile: async overwrite transforms are not supported");let i=ue(t,o);e.write(`const ${s} = ${i}(${n});`)}function $b(){throw new Zt}function xb(e){this.issues.push(e)}function MG(e,t,r,n){let s=r._zod.def;if(s.fn){if(Ns(s.fn))throw new Pr("z.compile: async .refine() predicates are not supported");let o=Fs(t,s.fn),i=ue(t,$b),a=te(t);return e.write(`const ${a} = ${o}(${n});`),e.write(`if (${a} instanceof Promise) ${i}();`),e.write(`if (!${a}) return INVALID;`),n}if(r._zod.check){if(Ns(r._zod.check))throw new Pr("z.compile: async .superRefine() / check functions are not supported");let o=r._zod.check,a=Fs(t,u=>{let d={value:u,issues:[],addIssue:xb};return o(d)instanceof Promise&&$b(),d.issues.length===0?d.value:Mt}),c=te(t);return e.write(`const ${c} = ${a}(${n});`),e.write(`if (${c} === INVALID) return INVALID;`),c}throw new Se("custom check without a predicate or check function")}function wP(e,t,r,n,s=!0){let o=r.format;if(o==="base64"){let u=ue(t,Cc);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="base64url"){let u=ue(t,gd);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="jwt"){let u=ue(t,bd),d=ue(t,r.alg??null);return e.write(`if (!${u}(${n}, ${d})) return INVALID;`),n}if(o==="ipv6"){let u=ue(t,kc);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="cidrv6"){let u=ue(t,md);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="credit_card"){let u=ue(t,hd);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="iban"){let u=ue(t,yd);return e.write(`if (!${u}(${n})) return INVALID;`),n}let i=r;if(o==="url"||o==="httpurl"||i.normalize||i.hostname!==void 0||i.protocol!==void 0){let u=ue(t,ld),d=ue(t,r),p=te(t),m=te(t);if(e.write(`const ${p} = ${n}.trim();`),e.write(`const ${m} = ${u}(${p}, ${d});`),e.write(`if (typeof ${m} === "number") return INVALID;`),i.hostname!==void 0){let h=ue(t,dd);e.write(`if (!${h}(${m}, ${d}.hostname)) return INVALID;`)}if(i.protocol!==void 0){let h=ue(t,pd);e.write(`if (!${h}(${m}, ${d}.protocol)) return INVALID;`)}if(!s)return null;let f=te(t),g=i.normalize?`${m}.href`:`${ue(t,vc)}(${p})`;return e.write(`const ${f} = ${g};`),f}let a=r.fn;if(a){if(Ns(a))throw new Se(`async string format ${o}`);let u=ue(t,a);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(FG.has(o)&&r.pattern){let u=ue(t,r.pattern);return e.write(`${u}.lastIndex = 0;`),e.write(`if (!${u}.test(${n})) return INVALID;`),n}let c=r.format;switch(c){case"regex":throw new Se("regex format without a pattern");case"lowercase":e.write(`if (${n} !== ${n}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${n} !== ${n}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${n}.includes(${Dt(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;e.write(`if (${n}.slice(0, ${u.length}) !== ${Dt(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;e.write(`if (${n}.slice(-${u.length}) !== ${Dt(u)}) return INVALID;`);break}default:throw new Se(`string format ${c}`)}return n}function Ve(e,t,r,n,s=!0){let o=r._zod.def,i=o.type;if(o.coerce)throw new Se(`coercion (z.coerce.${i}())`);let a=s||!!o.checks?.length,c;switch(i){case"string":c=NG(e,t,r,n,a);break;case"number":c=GG(e,r,n);break;case"boolean":c=UG(e,n);break;case"bigint":c=jG(e,r,n);break;case"symbol":c=zG(e,n);break;case"undefined":c=BG(e,n);break;case"null":c=HG(e,n);break;case"any":case"unknown":c=n;break;case"never":e.write("return INVALID;"),c=n;break;case"void":c=WG(e,n);break;case"nan":c=VG(e,n);break;case"date":c=qG(e,n);break;case"object":c=ZG(e,t,r,n,a);break;case"optional":c=KG(e,t,r,n,a);break;case"nullable":c=QG(e,t,r,n,a);break;case"array":c=XG(e,t,r,n,a);break;case"literal":c=eU(e,t,r,n);break;case"enum":c=tU(e,t,r,n);break;case"readonly":{let u=fP(e,t,r,n),d=te(t);e.write(`const ${d} = Object.freeze(${u});`),c=d;break}case"success":fP(e,t,r,n),c="true";break;case"default":case"prefault":c=rU(e,t,r,n);break;case"nonoptional":c=nU(e,t,r,n);break;case"tuple":c=sU(e,t,r,n);break;case"union":c=oU(e,t,r,n);break;case"intersection":c=cU(e,t,r,n);break;case"record":c=uU(e,t,r,n);break;case"map":c=dU(e,t,r,n);break;case"set":c=pU(e,t,r,n);break;case"file":c=mU(e,n);break;case"template_literal":c=fU(e,t,r,n);break;case"lazy":c=gU(e,t,r,n);break;case"pipe":c=hU(e,t,r,n);break;case"custom":c=yU(e,t,r,n);break;case"transform":c=RU(e,t,r,n);break;case"catch":c=wU(e,t,r,n);break;default:throw new Se(`schema type ${i}`)}return c===null?null:EG(e,t,r,c)}function NG(e,t,r,n,s=!0){e.write(`if (typeof ${n} !== "string") return INVALID;`);let o=r._zod.def;return o.format===void 0?n:wP(e,t,o,n,s)}function GG(e,t,r){e.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let n=t._zod.def;return n.check==="number_format"&&n.format&&bP(e,{format:n.format},r),r}function UG(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function jG(e,t,r){e.write(`if (typeof ${r} !== "bigint") return INVALID;`);let n=t._zod.def;if(n.format)switch(n.format){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function zG(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function BG(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function HG(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function WG(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function VG(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function qG(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function ZG(e,t,r,n,s=!0){let o=r._zod.def;e.write(`if (typeof ${n} !== "object" || ${n} === null || Array.isArray(${n})) return INVALID;`);let i=o.shape,a=Object.keys(i),c=Object.getOwnPropertySymbols(i),u=c.length?[...a,...c]:a,d=y=>typeof y=="symbol"?ue(t,y):Dt(y),p=y=>typeof y=="symbol"?`[${d(y)}]`:Dt(y),m=i;if(a.includes("__proto__"))throw new Se('object shape key "__proto__"');let f=new Map;for(let y of u){let S=m[y],k=d(y),R=te(t);if(e.write(`const ${R} = ${n}[${k}];`),S._zod.optin!==void 0){let P=te(t);e.write(`let ${P} = (() => {`),e.indented(C=>{let E=Tt(C,t,S,R);C.write(`return ${E};`)}),e.write("})();"),S._zod.optout==="optional"?(e.write(`if (${P} === INVALID) {`),e.indented(C=>{C.write(`if (${k} in ${n}) return INVALID;`),C.write(`${P} = undefined;`)}),e.write("}")):e.write(`if (${P} === INVALID) return INVALID;`),f.set(y,P)}else{YG(S)&&e.write(`if (!(${k} in ${n})) return INVALID;`);let P=Tt(e,t,S,R,s);P!==null&&f.set(y,P)}}let g=o.catchall,h="none";if(g){let y=g._zod.def.type;if(y==="never"){let S=a.map(k=>`k !== ${Dt(k)}`).join(" && ")||"true";e.write(`for (const k in ${n}) {`),e.indented(k=>{k.write(`if (${S}) return INVALID;`)}),e.write("}")}else(y==="unknown"||y==="any")&&!g._zod.def.checks?.length?h="passthrough":h="schema"}let b=te(t),w=u.some(y=>mP(m[y])||Ob(m[y]));if(!s){if(h==="schema"){let y=a.length>0?ue(t,new Set(a)):null;e.write(`for (const k in ${n}) {`),e.indented(S=>{S.write('if (k === "__proto__") continue;'),y&&S.write(`if (${y}.has(k)) continue;`);let k=te(t);S.write(`const ${k} = ${n}[k];`),Tt(S,t,g,k,!1)}),e.write("}")}return null}if(w){e.write(`const ${b} = {};`);for(let y of u){let S=d(y),k=f.get(y);Ob(m[y])?e.write(`if (${S} in ${n}) ${b}[${S}] = ${k};`):mP(m[y])?e.write(`if (${k} !== undefined || ${S} in ${n}) ${b}[${S}] = ${k};`):e.write(`${b}[${S}] = ${k};`)}}else{let y=u.map(S=>`${p(S)}: ${f.get(S)}`).join(", ");e.write(`const ${b} = { ${y} };`)}if(h!=="none"){let y=a.length>0?ue(t,new Set(a)):null;e.write(`for (const k in ${n}) {`),e.indented(S=>{if(S.write('if (k === "__proto__") continue;'),y&&S.write(`if (${y}.has(k)) continue;`),h==="passthrough")S.write(`${b}[k] = ${n}[k];`);else{let k=te(t);S.write(`const ${k} = ${n}[k];`);let R=Tt(S,t,g,k);S.write(`${b}[k] = ${R};`)}}),e.write("}")}return b}function KG(e,t,r,n,s=!0){let o=r._zod.def;if(JG(r))return Ve(e,t,o.innerType,n,s);if(o.innerType._zod.optin==="defaulted"){let a=te(t),c=te(t);return e.write(`let ${a};`),e.write(`if (${n} === undefined) {`),e.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(d=>{let p=Ve(d,t,o.innerType,n);d.write(`return ${p};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${a} = ${c};`)}),e.write("} else {"),e.indented(u=>{let d=Ve(u,t,o.innerType,n);u.write(`${a} = ${d};`)}),e.write("}"),a}let i=s?te(t):null;return i&&e.write(`let ${i};`),e.write(`if (${n} !== undefined) {`),e.indented(a=>{let c=Ve(a,t,o.innerType,n,s);i&&c!==null&&a.write(`${i} = ${c};`)}),e.write("}"),i}function JG(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function YG(e){return e._zod.optin===void 0&&Ms(e)}function Ms(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?Ms(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?Ms(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(Ms):!0;case"intersection":return!t.left||!t.right?!0:Ms(t.left)&&Ms(t.right);case"pipe":return t.in?Ms(t.in):!0;default:return!0}}function Ob(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function mP(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&di(e)}function di(e){let t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?di(t.innerType):!0;case"union":return t.options?t.options.some(di):!0;case"intersection":return!t.left||!t.right||di(t.left)||di(t.right);case"pipe":return t.out?di(t.out):!0;default:return!0}}function QG(e,t,r,n,s=!0){let o=r._zod.def,i=s?te(t):null;return i&&e.write(`let ${i} = null;`),e.write(`if (${n} !== null) {`),e.indented(a=>{let c=Ve(a,t,o.innerType,n,s);i&&c!==null&&a.write(`${i} = ${c};`)}),e.write("}"),i}function Db(e,t,r){for(let[n,s]of ti(t._zod.def.checks))e.write(`if (${r} > ${Bn(n,s._zod.def.check)}) return INVALID;`)}function XG(e,t,r,n,s=!0){let o=r._zod.def;e.write(`if (!Array.isArray(${n})) return INVALID;`),Db(e,r,`${n}.length`);let i=s?te(t):null,a=te(t),c=te(t);return i&&e.write(`const ${i} = new Array(${n}.length);`),e.write(`for (let ${a} = 0; ${a} < ${n}.length; ${a}++) {`),e.indented(u=>{u.write(`const ${c} = ${n}[${a}];`);let d=Tt(u,t,o.element,c,s);i&&d!==null&&u.write(`${i}[${a}] = ${d};`)}),e.write("}"),i}function eU(e,t,r,n){let o=r._zod.def.values;if(o.length!==1){let a=ue(t,new Set(o));return e.write(`if (!${a}.has(${n})) return INVALID;`),n}let i=o[0];if(typeof i=="number"&&Number.isNaN(i)){let a=ue(t,new Set(o));return e.write(`if (!${a}.has(${n})) return INVALID;`),n}if(typeof i=="string")e.write(`if (${n} !== ${Dt(i)}) return INVALID;`);else if(typeof i=="number"||typeof i=="boolean")e.write(`if (${n} !== ${i}) return INVALID;`);else if(i===null)e.write(`if (${n} !== null) return INVALID;`);else if(i===void 0)e.write(`if (${n} !== undefined) return INVALID;`);else if(typeof i=="bigint")e.write(`if (${n} !== ${i}n) return INVALID;`);else throw new Se(`literal type ${typeof i}`);return n}function tU(e,t,r,n){let s=r._zod.values;if(!s)throw new Se("enum schema without enumerated values");let o=ue(t,s);return e.write(`if (!${o}.has(${n})) return INVALID;`),n}function fP(e,t,r,n){let s=r._zod.def;return Ve(e,t,s.innerType,n)}function rU(e,t,r,n){let s=r._zod.def,i=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!i)return Ve(e,t,s.innerType,n);let c=ue(t,i),u=te(t);return e.write(`let ${u} = ${n};`),e.write(`if (${n} === undefined) ${u} = ${c}();`),Ve(e,t,s.innerType,u)}let a=te(t);if(i){let c=ue(t,i),u=ue(t,ic);e.write(`let ${a};`),e.write(`if (${n} === undefined) {`),e.indented(d=>{d.write(`${a} = ${u}(${c}());`)}),e.write("} else {"),e.indented(d=>{let p=Ve(d,t,s.innerType,n);d.write(`${a} = ${p} === undefined ? ${u}(${c}()) : ${p};`)}),e.write("}")}else e.write(`let ${a};`),e.write(`if (${n} !== undefined) {`),e.indented(c=>{let u=Ve(c,t,s.innerType,n);c.write(`${a} = ${u};`)}),e.write("}");return a}function nU(e,t,r,n){let s=r._zod.def,o=Ve(e,t,s.innerType,n),i=te(t);return e.write(`const ${i} = ${o};`),e.write(`if (${i} === undefined) return INVALID;`),i}function sU(e,t,r,n){let s=r._zod.def,o=s.items,i=s.rest;e.write(`if (!Array.isArray(${n})) return INVALID;`);let a=gP(o,"optin"),c=gP(o,"optout");i?e.write(`if (${n}.length < ${a}) return INVALID;`):e.write(`if (${n}.length < ${a} || ${n}.length > ${o.length}) return INVALID;`);let u=te(t);e.write(`const ${u} = [];`);for(let d=0;d<o.length;d++){let p=o[d];if(d>=c)e.write(`if (${u}.length === ${d}) {`),e.indented(m=>{m.write(`if (${d} < ${n}.length) {`),m.indented(f=>{let g=te(t);f.write(`const ${g} = ${n}[${d}];`);let h=Tt(f,t,p,g);f.write(`${u}[${d}] = ${h};`)}),m.write("} else {"),m.indented(f=>{if(Ob(p)){f.write(`${u}.length = ${d};`);return}let g=te(t),h=te(t);f.write(`const ${g} = undefined;`),f.write(`const ${h} = (() => {`),f.indented(b=>{let w=Tt(b,t,p,g);b.write(`return ${w};`)}),f.write("})();"),f.write(`if (${h} === INVALID || ${h} === undefined) ${u}.length = ${d};`),f.write(`else ${u}[${d}] = ${h};`)}),m.write("}")}),e.write("}");else{let m=te(t);e.write(`const ${m} = ${n}[${d}];`);let f=Tt(e,t,p,m);e.write(`${u}[${d}] = ${f};`)}}if(i){let d=te(t),p=te(t);e.write(`for (let ${d} = ${o.length}; ${d} < ${n}.length; ${d}++) {`),e.indented(m=>{m.write(`const ${p} = ${n}[${d}];`);let f=Tt(m,t,i,p);m.write(`${u}[${d}] = ${f};`)}),e.write("}")}return u}function gP(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function oU(e,t,r,n){let s=r._zod.def,o=s.options;if(s.discriminator)return iU(e,t,s,n);if(s.inclusive===!1)throw new Se("exclusive unions (z.xor)");if(o.length===0)return e.write("return INVALID;"),n;if(o.length===1)return Ve(e,t,o[0],n);if(o.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(o.flatMap(d=>d._zod.def.values)),u=ue(t,c);return e.write(`if (!${u}.has(${n})) return INVALID;`),n}let a=te(t);e.write(`let ${a};`);for(let c=0;c<o.length;c++){let u=o[c];c===0?e.write(`${a} = (() => {`):e.write(`if (${a} === INVALID) ${a} = (() => {`),e.indented(d=>{let p=Ve(d,t,u,n);d.write(`return ${p};`)}),e.write("})();")}return e.write(`if (${a} === INVALID) return INVALID;`),a}function iU(e,t,r,n){if(r.unionFallback)throw new Se("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),n;let s=te(t),o=te(t);e.write(`const ${s} = ${n}?.[${Dt(r.discriminator)}];`),e.write(`let ${o};`);let i=!0,a=new Set;for(let c of r.options){let u=c._zod.propValues?.[r.discriminator];if(!u||u.size===0)throw new Se("discriminated union option without static discriminator values");for(let m of u){if(a.has(m))throw new Se(`duplicate discriminator value ${String(m)}`);a.add(m)}let d=Array.from(u,m=>aU(t,s,m)),p=i?"if":"else if";e.write(`${p} (${d.join(" || ")}) {`),e.indented(m=>{let f=Ve(m,t,c,n);m.write(`${o} = ${f};`)}),e.write("}"),i=!1}return e.write("else { return INVALID; }"),o}function aU(e,t,r){if(typeof r=="string")return`${t} === ${Dt(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${t})`:`${t} === ${r}`;if(typeof r=="boolean")return`${t} === ${r}`;if(r===null)return`${t} === null`;if(r===void 0)return`${t} === undefined`;if(typeof r=="bigint")return`${t} === ${r}n`;if(typeof r=="symbol"){let n=ue(e,r);return`${t} === ${n}`}throw new Se(`literal discriminator value ${String(r)}`)}function cU(e,t,r,n){let s=r._zod.def;t.definite=!1;let o=Tt(e,t,s.left,n),i=Tt(e,t,s.right,n),a=ue(t,ci),c=te(t);return e.write(`const ${c} = ${a}(${o}, ${i});`),e.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function uU(e,t,r,n){let s=r._zod.def,o=ue(t,br);e.write(`if (!${o}(${n})) return INVALID;`);let i=te(t),a=te(t),c=te(t);e.write(`const ${i} = {};`);let u=s,d=u.partial?void 0:s.keyType._zod.values;if(d){let f=[];for(let h of d){if(!(typeof h=="string"||typeof h=="number"||typeof h=="symbol"))throw new Se(`record key value ${String(h)}`);let b=typeof h=="number"?h.toString():h;if(b==="__proto__")throw new Se('record key "__proto__"');f.push(b);let w=ue(t,h),y=Ve(e,t,s.keyType,w),S=te(t);e.write(`const ${S} = ${n}[${lU(t,b)}];`);let k=Tt(e,t,s.valueType,S);e.write(`${i}[${y}] = ${k};`)}let g=ue(t,new Set(f));return e.write(`for (const ${a} in ${n}) {`),e.indented(h=>{h.write(`if (${g}.has(${a})) continue;`),u.mode==="loose"?h.write(`if (${a} !== "__proto__") ${i}[${a}] = ${n}[${a}];`):h.write("return INVALID;")}),e.write("}"),i}let p=s.keyType._zod.def;if(!(p.type==="string"&&p.format===void 0&&!p.coerce&&(p.checks?.length??0)===0)){let f=s.mode==="loose",g=Dd(s.keyType);g.definite===!1&&(t.definite=!1);let h=ue(t,g),b=ue(t,pn),w=te(t);return hP(e,t,n,a,y=>{y.write(`let ${w} = ${h}(${a});`),y.write(`if (${w} === INVALID && typeof ${a} === "string" && ${b}.test(${a})) ${w} = ${h}(Number(${a}));`),f?y.write(`if (${w} === INVALID) { ${i}[${a}] = ${n}[${a}]; continue; }`):y.write(`if (${w} === INVALID) return INVALID;`),y.write(`if (${w} === "__proto__") continue;`);let S=te(t);y.write(`const ${S} = ${n}[${a}];`);let k=Tt(y,t,s.valueType,S);y.write(`${i}[${w}] = ${k};`)}),i}return hP(e,t,n,a,f=>{f.write(`const ${c} = ${n}[${a}];`);let g=Tt(f,t,s.valueType,c);f.write(`${i}[${a}] = ${g};`)},"return INVALID;"),i}function hP(e,t,r,n,s,o){let i=ue(t,Object.prototype.propertyIsEnumerable),a=te(t),c=te(t),u=te(t);e.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),e.write(`const ${c} = Object.getOwnPropertyNames(${r});`),e.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),e.indented(d=>{d.write(`const ${n} = ${c}[${u}];`),d.write(`if (${n} === "__proto__" || !${i}.call(${r}, ${n})) continue;`),s(d)}),e.write("}"),e.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),e.indented(d=>{d.write(`const ${n} = ${a}[${u}];`),d.write(`if (!${i}.call(${r}, ${n})) continue;`),o?d.write(o):s(d)}),e.write("}")}function lU(e,t){return typeof t=="string"?Dt(t):ue(e,t)}function dU(e,t,r,n){let s=r._zod.def;e.write(`if (!(${n} instanceof Map)) return INVALID;`),Db(e,r,`${n}.size`);let o=te(t),i=te(t),a=te(t);return e.write(`const ${o} = new Map();`),e.write(`for (const [${i}, ${a}] of ${n}) {`),e.indented(c=>{let u=Ve(c,t,s.keyType,i),d=Ve(c,t,s.valueType,a);c.write(`${o}.set(${u}, ${d});`)}),e.write("}"),o}function pU(e,t,r,n){let s=r._zod.def;e.write(`if (!(${n} instanceof Set)) return INVALID;`),Db(e,r,`${n}.size`);let o=te(t),i=te(t);return e.write(`const ${o} = new Set();`),e.write(`for (const ${i} of ${n}) {`),e.indented(a=>{let c=Ve(a,t,s.valueType,i);a.write(`${o}.add(${c});`)}),e.write("}"),o}function mU(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function fU(e,t,r,n){e.write(`if (typeof ${n} !== "string") return INVALID;`);let s=r._zod.pattern;if(s){let o=ue(t,s);e.write(`${o}.lastIndex = 0;`),e.write(`if (!${o}.test(${n})) return INVALID;`)}return n}function gU(e,t,r,n){let s=r._zod.def,o=Fs(t,s.getter),i=ue(t,{parser:null});e.write(`if (!${i}.parser) {`),e.indented(c=>{c.write(`const inner = ${o}();`),c.write(`${i}.parser = function(input) {`),c.indented(u=>{u.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),u.write("return result.issues.length === 0 ? result.value : INVALID;")}),c.write("};")}),e.write("}");let a=te(t);return e.write(`const ${a} = ${i}.parser(${n});`),e.write(`if (${a} === INVALID) return INVALID;`),a}function hU(e,t,r,n){let s=r._zod.def,o=Ve(e,t,s.in,n);if(s.transform){if(Ns(s.transform))throw new Pr("z.compile: async transforms in pipes are not supported");let i=s.transform,c=Fs(t,d=>{let p={value:d,issues:[],addIssue:xb},m=i(d,p);return m instanceof Promise?Mt:p.issues.length===0?m:Mt}),u=te(t);return e.write(`const ${u} = ${c}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),Ve(e,t,s.out,u)}else return Ve(e,t,s.out,o)}function Ns(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function yU(e,t,r,n){let s=r._zod.def;if(s.fn){if(Ns(s.fn))throw new Pr("z.compile: async custom predicates are not supported");let o=Fs(t,s.fn),i=ue(t,$b),a=te(t);e.write(`const ${a} = ${o}(${n});`),e.write(`if (${a} instanceof Promise) ${i}();`),e.write(`if (!${a}) return INVALID;`)}else throw new Se("custom schema without a predicate function");return n}function bU(e,t,r){let n=e._zod.run({value:r,issues:[]},{});if(n&&typeof n.then=="function")return Mt;let s=n;return s.issues.length===0?s.value:t()}function wU(e,t,r,n){let s=r._zod.def;if(!s.catchValue[Gl])throw new Se("catch with a callback (only a constant catch value compiles)",!1);let o=te(t);e.write(`let ${o} = (() => {`),e.indented(u=>{let d=Tt(u,t,s.innerType,n);u.write(`return ${d};`)}),e.write("})();");let i=ue(t,s.innerType),a=Fs(t,s.catchValue),c=ue(t,bU);return e.write(`if (${o} === INVALID) {`),e.indented(u=>{u.write(`${o} = ${c}(${i}, ${a}, ${n});`),u.write(`if (${o} === INVALID) return INVALID;`)}),e.write("}"),o}function RU(e,t,r,n){let s=r._zod.def;if(s.transform){if(Ns(s.transform))throw new Pr("z.compile: async transforms are not supported");let o=s.transform,a=Fs(t,u=>{let d={value:u,issues:[],addIssue:xb},p=o(u,d);return p instanceof Promise?Mt:d.issues.length===0?p:Mt}),c=te(t);return e.write(`const ${c} = ${a}(${n});`),e.write(`if (${c} === INVALID) return INVALID;`),c}return n}var Mt,pP,Pr,Se,PG,FG,RP=A(()=>{jn();sd();kb();xs();ui();rt();Mt=Symbol.for("zod.compile.invalid"),pP=Symbol.for("zod.compile.fallback"),Pr=class extends Error{constructor(t="z.compile does not support async refinements, transforms, or checks"){super(t),this.name="ZodCompileAsyncError"}},Se=class extends Error{constructor(t,r=!0){super(`z.compile does not support ${t}; this schema must use the runtime parser`),this.name="ZodCompileUnsupportedError",this.islandable=r}};PG=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);FG=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"])});function Ld(e){return e.checks&&(e.checks=[...e.checks]),e}function Lb(e,t){return new e(Ld({type:"string",...U(t)}))}function Mb(e,t){return new e(Ld({type:"string",coerce:!0,...U(t)}))}function Md(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...U(t)})}function Fd(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...U(t)})}function Nd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...U(t)})}function Gd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...U(t)})}function Ud(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...U(t)})}function jd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...U(t)})}function Mc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...U(t)})}function zd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...U(t)})}function Bd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...U(t)})}function Hd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...U(t)})}function Wd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...U(t)})}function Vd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...U(t)})}function qd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...U(t)})}function Zd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...U(t)})}function Kd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...U(t)})}function Jd(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...U(t)})}function Fb(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...U(t)})}function Yd(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...U(t)})}function Qd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...U(t)})}function Xd(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...U(t)})}function ep(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...U(t)})}function tp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...U(t)})}function Nb(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...U(t)})}function Gb(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...U(t)})}function rp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...U(t)})}function Fc(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...U(t)})}function Nc(e,t){return new e({type:"string",format:"date",check:"string_format",...U(t)})}function Gc(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...U(t)})}function Uc(e,t){return new e({type:"string",format:"duration",check:"string_format",...U(t)})}function jb(e,t){return new e(Ld({type:"number",checks:[],...U(t)}))}function zb(e,t){return new e(Ld({type:"number",coerce:!0,checks:[],...U(t)}))}function Bb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...U(t)})}function Hb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...U(t)})}function Wb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...U(t)})}function Vb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...U(t)})}function qb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...U(t)})}function Zb(e,t){return new e({type:"boolean",...U(t)})}function Kb(e,t){return new e({type:"boolean",coerce:!0,...U(t)})}function Jb(e,t){return new e({type:"bigint",...U(t)})}function Yb(e,t){return new e({type:"bigint",coerce:!0,...U(t)})}function Qb(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...U(t)})}function Xb(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...U(t)})}function ew(e,t){return new e({type:"symbol",...U(t)})}function tw(e,t){return new e({type:"undefined",...U(t)})}function rw(e,t){return new e({type:"null",...U(t)})}function nw(e){return new e({type:"any"})}function sw(e){return new e({type:"unknown"})}function ow(e,t){return new e({type:"never",...U(t)})}function iw(e,t){return new e({type:"void",...U(t)})}function aw(e,t){return new e({type:"date",...U(t)})}function cw(e,t){return new e({type:"date",coerce:!0,...U(t)})}function uw(e,t){return new e({type:"nan",...U(t)})}function Ur(e,t){return new td({check:"less_than",...U(t),value:e,inclusive:!1})}function or(e,t){return new td({check:"less_than",...U(t),value:e,inclusive:!0})}function jr(e,t){return new rd({check:"greater_than",...U(t),value:e,inclusive:!1})}function ir(e,t){return new rd({check:"greater_than",...U(t),value:e,inclusive:!0})}function np(e){return jr(0,e)}function sp(e){return Ur(0,e)}function op(e){return or(0,e)}function ip(e){return ir(0,e)}function Hn(e,t){return new jh({check:"multiple_of",...U(t),value:e})}function Wn(e,t){return new Hh({check:"max_size",...U(t),maximum:e})}function zr(e,t){return new Wh({check:"min_size",...U(t),minimum:e})}function Gs(e,t){return new Vh({check:"size_equals",...U(t),size:e})}function Us(e,t){return new qh({check:"max_length",...U(t),maximum:e})}function mn(e,t){return new Zh({check:"min_length",...U(t),minimum:e})}function js(e,t){return new Kh({check:"length_equals",...U(t),length:e})}function pi(e,t){return new Jh({check:"string_format",format:"regex",...U(t),pattern:e})}function mi(e){return new Yh({check:"string_format",format:"lowercase",...U(e)})}function fi(e){return new Qh({check:"string_format",format:"uppercase",...U(e)})}function gi(e,t){return new Xh({check:"string_format",format:"includes",...U(t),includes:e})}function hi(e,t){return new ey({check:"string_format",format:"starts_with",...U(t),prefix:e})}function yi(e,t){return new ty({check:"string_format",format:"ends_with",...U(t),suffix:e})}function ap(e,t,r){return new ry({check:"property",property:e,schema:t,...U(r)})}function bi(e,t){return new ny({check:"properties",shape:e,...U(t)})}function wi(e,t){return new sy({check:"mime_type",mime:e,...U(t)})}function Er(e){return new oy({check:"overwrite",tx:e})}function Ri(e){return Er(t=>t.normalize(e))}function Si(){return Er(e=>e.trim())}function _i(){return Er(e=>e.toLowerCase())}function vi(){return Er(e=>e.toUpperCase())}function ki(){return Er(e=>Ug(e))}function lw(e,t,r){return new e({type:"array",element:t,...U(r)})}function SU(e,t,r){return new e({type:"union",options:t,...U(r)})}function _U(e,t,r){return new e({type:"union",options:t,inclusive:!1,...U(r)})}function vU(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...U(n)})}function kU(e,t,r){return new e({type:"intersection",left:t,right:r})}function CU(e,t,r,n){let s=r instanceof pe,o=s?n:r,i=s?r:null;return new e({type:"tuple",items:t,rest:i,...U(o)})}function PU(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...U(n)})}function EU(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...U(n)})}function AU(e,t,r){return new e({type:"set",valueType:t,...U(r)})}function TU(e,t,r){let n=Array.isArray(t)?Object.fromEntries(t.map(s=>[s,s])):t;return new e({type:"enum",entries:n,...U(r)})}function $U(e,t,r){return new e({type:"enum",entries:t,...U(r)})}function OU(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...U(r)})}function dw(e,t){return new e({type:"file",...U(t)})}function IU(e,t){return new e({type:"transform",transform:t})}function xU(e,t){return new e({type:"optional",innerType:t})}function DU(e,t){return new e({type:"nullable",innerType:t})}function LU(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():ic(r)}})}function MU(e,t,r){return new e({type:"nonoptional",innerType:t,...U(r)})}function FU(e,t){return new e({type:"success",innerType:t})}function NU(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:qg(r)})}function GU(e,t,r){return new e({type:"pipe",in:t,out:r})}function UU(e,t){return new e({type:"readonly",innerType:t})}function jU(e,t,r){return new e({type:"template_literal",parts:t,...U(r)})}function zU(e,t){return new e({type:"lazy",getter:t})}function BU(e,t){return new e({type:"promise",innerType:t})}function pw(e,t,r){let n=U(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function mw(e,t,r){return new e({type:"custom",check:"custom",fn:t,...U(r)})}function fw(e,t){let r=SP(n=>(n.addIssue=s=>{if(typeof s=="string")n.issues.push(ri(s,n.value,r._zod.def));else{let o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),"input"in o||(o.input=n.value),o.inst??(o.inst=r),o.continue??(o.continue=!r._zod.def.abort),n.issues.push(ri(o))}},e(n.value,n)),t);return r}function SP(e,t){let r=new Fe({check:"custom",...U(t)});return r._zod.check=e,r}function gw(e){let t=new Fe({check:"describe"});return t._zod.onattach=[r=>{let n=_t.get(r)??{};_t.add(r,{...n,description:e})}],t._zod.check=()=>{},t}function hw(e){let t=new Fe({check:"meta"});return t._zod.onattach=[r=>{let n=_t.get(r)??{};_t.add(r,{...n,...e})}],t._zod.check=()=>{},t}function yw(e,t){let r=U(t),n=r.truthy??["true","1","yes","on","y","enabled"],s=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(n=n.map(f=>typeof f=="string"?f.toLowerCase():f),s=s.map(f=>typeof f=="string"?f.toLowerCase():f));let o=new Set(n),i=new Set(s),a=e.Codec??Tc,c=e.Boolean??Ec,u=e.String??Ls,d=new u({type:"string",error:r.error}),p=new c({type:"boolean",error:r.error}),m=new a({type:"pipe",in:d,out:p,transform:((f,g)=>{let h=f;return r.case!=="sensitive"&&(h=h.toLowerCase()),o.has(h)?!0:i.has(h)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...i],input:g.value,inst:m,continue:!1}),{})}),reverseTransform:((f,g)=>f===!0?n[0]||"true":s[0]||"false"),error:r.error});return m._zod.bag.truthy=n,m._zod.bag.falsy=s,m._zod.bag.case=r.case??"insensitive",m}function zs(e,t,r,n={}){let s=U(n),o={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...s};return r instanceof RegExp&&(o.pattern=r),new e(o)}var Ub,_P=A(()=>{nd();Lc();ui();rt();Ub={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function jc(e,...t){for(let r of t)for(let n of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,n)&&St(e,n,r[n]);return e}function Vn(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??_t,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function ut(e,t,r,n,s){let o=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:n.path,message:s}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw new Error(s);return Object.assign(r,o),!0}function xe(e,t,r={path:[],schemaPath:[]}){var n;let s=e._zod.def,o=t.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let m=i.schema,f=t.processors[s.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);f(e,t,m,d)}let p=e._zod.parent;p&&(i.ref||(i.ref=p),xe(p,t,d),t.seen.get(p).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&jc(i.schema,c),t.io==="input"&&Ft(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function vP(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function qn(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let n=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let s=i=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(i[0])?.id,m=e.external.uri??(g=>g);if(p)return{ref:m(p)};let f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${m("__shared")}#/${a}/${vP(f)}`}}let c="#",u=`${c}/${a}/`;if(i[1]===r&&!i[1].schema.id)return{ref:c};let d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+vP(d)}},o=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=s(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let p in d)delete d[p];d.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
61
+ }`,m;try{m=new d(...i,p)(...a)}catch(f){throw new Se(`this schema (generated code failed to evaluate: ${f.message})`)}return t?.debug&&(m.code=u),m.definite=n.definite,m}function ue(e,t){for(let[n,s]of e.constants)if(s===t)return n;let r=`c${e.constantCounter++}`;return e.constants.set(r,t),r}function Fs(e,t){return e.definite=!1,ue(e,t)}function te(e){return`v${e.varCounter++}`}function kG(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return Mt;let n=r;return n.issues.length===0?n.value:Mt}function Tt(e,t,r,n,s=!0){let o=e.content.length,i=t.constants.size,a=t.constantCounter,c=t.varCounter;try{return Ve(e,t,r,n,s)}catch(u){if(!(u instanceof Se)||!u.islandable)throw u;if(e.content.length=o,t.constants.size>i){let d=Array.from(t.constants.keys()).slice(i);for(let p of d)t.constants.delete(p)}return t.constantCounter=a,t.varCounter=c,CG(e,t,r,n)}}function CG(e,t,r,n){t.definite=!1;let s=ue(t,r),o=ue(t,kG),i=te(t);return e.write(`const ${i} = ${o}(${s}, ${n});`),e.write(`if (${i} === INVALID) return INVALID;`),i}function EG(e,t,r,n){let s=r._zod.def.checks;if(!s||s.length===0)return n;let o=n;for(let i of s){let a=i._zod.def;if(a.when&&!PG.has(a.check))throw new Se('check with a custom "when" condition');switch(a.check){case"greater_than":AG(e,t,a,o);break;case"less_than":TG(e,t,a,o);break;case"multiple_of":$G(e,t,a,o);break;case"number_format":bP(e,a,o);break;case"min_length":{let c=Bn(a.minimum,"min_length"),u=Tb(e,t,o,`${o}.length >= ${c} && ${o}.length < ${a.minimum*2}`);e.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=Bn(a.maximum,"max_length"),u=Tb(e,t,o,`${o}.length > ${c}`);e.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=Bn(a.length,"length_equals"),u=Tb(e,t,o,`${o}.length >= ${c} && ${o}.length <= ${a.length*2}`);e.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":e.write(`if (${o}.size < ${Bn(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${o}.size > ${Bn(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${o}.size !== ${Bn(a.size,"size_equals")}) return INVALID;`);break;case"string_format":o=wP(e,t,a,o);break;case"custom":o=MG(e,t,i,o);break;case"bigint_format":OG(e,a,o);break;case"mime_type":IG(e,t,a,o);break;case"property":DG(e,t,a,o);break;case"properties":xG(e,t,a,o);break;case"overwrite":{let c=te(t);LG(e,t,i,o,c),o=c;break}default:throw new Se(`check type ${a.check}`)}}return o}function Tb(e,t,r,n){let s=ue(t,Os),o=te(t);return e.write(`const ${o} = typeof ${r} === "string" && ${n} ? ${s}(${r}) : ${r}.length;`),o}function Bn(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Se(`${t} bound of type ${typeof e}`);return`${e}`}function yP(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new Se("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new Se("comparison check with Invalid Date bound");return ue(e,t)}throw new Se(`comparison check bound of type ${typeof t}`)}function AG(e,t,r,n){let s=r.inclusive?"<":"<=";e.write(`if (${n} ${s} ${yP(t,r.value)}) return INVALID;`)}function TG(e,t,r,n){let s=r.inclusive?">":">=";e.write(`if (${n} ${s} ${yP(t,r.value)}) return INVALID;`)}function $G(e,t,r,n){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Se("multiple_of check with a zero divisor");e.write(`if (${n} % ${r.value}n !== 0n) return INVALID;`)}else{let s=ue(t,oc);e.write(`if (${s}(${n}, ${Bn(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function bP(e,t,r){let n=t.format;switch(n){case"safeint":e.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new Se(`number format ${n}`)}}function OG(e,t,r){let n=t.format;if(n)switch(n){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new Se(`bigint format ${n}`)}}function IG(e,t,r,n){let s=r.mime;if(s&&s.length>0){let o=ue(t,new Set(s));e.write(`if (!${o}.has(${n}.type)) return INVALID;`)}}function xG(e,t,r,n){if(r.when)throw new Se('check with a custom "when" condition');e.write(`if (${n} == null) return INVALID;`);let s=r.shape;for(let o of Reflect.ownKeys(s)){let i=typeof o=="symbol"?ue(t,o):Dt(o),a=te(t);e.write(`const ${a} = ${n}[${i}];`),Tt(e,t,s[o],a,!1)}}function DG(e,t,r,n){let s=`${n}[${JSON.stringify(r.property)}]`;Ve(e,t,r.schema,s)}function LG(e,t,r,n,s){let o=r._zod.def.tx;if(!o)throw new Se("overwrite check without a transform function");if(Ns(o))throw new Pr("z.compile: async overwrite transforms are not supported");let i=ue(t,o);e.write(`const ${s} = ${i}(${n});`)}function $b(){throw new Zt}function xb(e){this.issues.push(e)}function MG(e,t,r,n){let s=r._zod.def;if(s.fn){if(Ns(s.fn))throw new Pr("z.compile: async .refine() predicates are not supported");let o=Fs(t,s.fn),i=ue(t,$b),a=te(t);return e.write(`const ${a} = ${o}(${n});`),e.write(`if (${a} instanceof Promise) ${i}();`),e.write(`if (!${a}) return INVALID;`),n}if(r._zod.check){if(Ns(r._zod.check))throw new Pr("z.compile: async .superRefine() / check functions are not supported");let o=r._zod.check,a=Fs(t,u=>{let d={value:u,issues:[],addIssue:xb};return o(d)instanceof Promise&&$b(),d.issues.length===0?d.value:Mt}),c=te(t);return e.write(`const ${c} = ${a}(${n});`),e.write(`if (${c} === INVALID) return INVALID;`),c}throw new Se("custom check without a predicate or check function")}function wP(e,t,r,n,s=!0){let o=r.format;if(o==="base64"){let u=ue(t,Cc);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="base64url"){let u=ue(t,gd);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="jwt"){let u=ue(t,bd),d=ue(t,r.alg??null);return e.write(`if (!${u}(${n}, ${d})) return INVALID;`),n}if(o==="ipv6"){let u=ue(t,kc);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="cidrv6"){let u=ue(t,md);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="credit_card"){let u=ue(t,hd);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="iban"){let u=ue(t,yd);return e.write(`if (!${u}(${n})) return INVALID;`),n}let i=r;if(o==="url"||o==="httpurl"||i.normalize||i.hostname!==void 0||i.protocol!==void 0){let u=ue(t,ld),d=ue(t,r),p=te(t),m=te(t);if(e.write(`const ${p} = ${n}.trim();`),e.write(`const ${m} = ${u}(${p}, ${d});`),e.write(`if (typeof ${m} === "number") return INVALID;`),i.hostname!==void 0){let h=ue(t,dd);e.write(`if (!${h}(${m}, ${d}.hostname)) return INVALID;`)}if(i.protocol!==void 0){let h=ue(t,pd);e.write(`if (!${h}(${m}, ${d}.protocol)) return INVALID;`)}if(!s)return null;let f=te(t),g=i.normalize?`${m}.href`:`${ue(t,vc)}(${p})`;return e.write(`const ${f} = ${g};`),f}let a=r.fn;if(a){if(Ns(a))throw new Se(`async string format ${o}`);let u=ue(t,a);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(FG.has(o)&&r.pattern){let u=ue(t,r.pattern);return e.write(`${u}.lastIndex = 0;`),e.write(`if (!${u}.test(${n})) return INVALID;`),n}let c=r.format;switch(c){case"regex":throw new Se("regex format without a pattern");case"lowercase":e.write(`if (${n} !== ${n}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${n} !== ${n}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${n}.includes(${Dt(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;e.write(`if (${n}.slice(0, ${u.length}) !== ${Dt(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;e.write(`if (${n}.slice(-${u.length}) !== ${Dt(u)}) return INVALID;`);break}default:throw new Se(`string format ${c}`)}return n}function Ve(e,t,r,n,s=!0){let o=r._zod.def,i=o.type;if(o.coerce)throw new Se(`coercion (z.coerce.${i}())`);let a=s||!!o.checks?.length,c;switch(i){case"string":c=NG(e,t,r,n,a);break;case"number":c=GG(e,r,n);break;case"boolean":c=UG(e,n);break;case"bigint":c=jG(e,r,n);break;case"symbol":c=zG(e,n);break;case"undefined":c=BG(e,n);break;case"null":c=HG(e,n);break;case"any":case"unknown":c=n;break;case"never":e.write("return INVALID;"),c=n;break;case"void":c=WG(e,n);break;case"nan":c=VG(e,n);break;case"date":c=qG(e,n);break;case"object":c=ZG(e,t,r,n,a);break;case"optional":c=KG(e,t,r,n,a);break;case"nullable":c=QG(e,t,r,n,a);break;case"array":c=XG(e,t,r,n,a);break;case"literal":c=eU(e,t,r,n);break;case"enum":c=tU(e,t,r,n);break;case"readonly":{let u=fP(e,t,r,n),d=te(t);e.write(`const ${d} = Object.freeze(${u});`),c=d;break}case"success":fP(e,t,r,n),c="true";break;case"default":case"prefault":c=rU(e,t,r,n);break;case"nonoptional":c=nU(e,t,r,n);break;case"tuple":c=sU(e,t,r,n);break;case"union":c=oU(e,t,r,n);break;case"intersection":c=cU(e,t,r,n);break;case"record":c=uU(e,t,r,n);break;case"map":c=dU(e,t,r,n);break;case"set":c=pU(e,t,r,n);break;case"file":c=mU(e,n);break;case"template_literal":c=fU(e,t,r,n);break;case"lazy":c=gU(e,t,r,n);break;case"pipe":c=hU(e,t,r,n);break;case"custom":c=yU(e,t,r,n);break;case"transform":c=RU(e,t,r,n);break;case"catch":c=wU(e,t,r,n);break;default:throw new Se(`schema type ${i}`)}return c===null?null:EG(e,t,r,c)}function NG(e,t,r,n,s=!0){e.write(`if (typeof ${n} !== "string") return INVALID;`);let o=r._zod.def;return o.format===void 0?n:wP(e,t,o,n,s)}function GG(e,t,r){e.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let n=t._zod.def;return n.check==="number_format"&&n.format&&bP(e,{format:n.format},r),r}function UG(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function jG(e,t,r){e.write(`if (typeof ${r} !== "bigint") return INVALID;`);let n=t._zod.def;if(n.format)switch(n.format){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function zG(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function BG(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function HG(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function WG(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function VG(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function qG(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function ZG(e,t,r,n,s=!0){let o=r._zod.def;e.write(`if (typeof ${n} !== "object" || ${n} === null || Array.isArray(${n})) return INVALID;`);let i=o.shape,a=Object.keys(i),c=Object.getOwnPropertySymbols(i),u=c.length?[...a,...c]:a,d=y=>typeof y=="symbol"?ue(t,y):Dt(y),p=y=>typeof y=="symbol"?`[${d(y)}]`:Dt(y),m=i;if(a.includes("__proto__"))throw new Se('object shape key "__proto__"');let f=new Map;for(let y of u){let S=m[y],k=d(y),R=te(t);if(e.write(`const ${R} = ${n}[${k}];`),S._zod.optin!==void 0){let P=te(t);e.write(`let ${P} = (() => {`),e.indented(C=>{let E=Tt(C,t,S,R);C.write(`return ${E};`)}),e.write("})();"),S._zod.optout==="optional"?(e.write(`if (${P} === INVALID) {`),e.indented(C=>{C.write(`if (${k} in ${n}) return INVALID;`),C.write(`${P} = undefined;`)}),e.write("}")):e.write(`if (${P} === INVALID) return INVALID;`),f.set(y,P)}else{YG(S)&&e.write(`if (!(${k} in ${n})) return INVALID;`);let P=Tt(e,t,S,R,s);P!==null&&f.set(y,P)}}let g=o.catchall,h="none";if(g){let y=g._zod.def.type;if(y==="never"){let S=a.map(k=>`k !== ${Dt(k)}`).join(" && ")||"true";e.write(`for (const k in ${n}) {`),e.indented(k=>{k.write(`if (${S}) return INVALID;`)}),e.write("}")}else(y==="unknown"||y==="any")&&!g._zod.def.checks?.length?h="passthrough":h="schema"}let b=te(t),w=u.some(y=>mP(m[y])||Ob(m[y]));if(!s){if(h==="schema"){let y=a.length>0?ue(t,new Set(a)):null;e.write(`for (const k in ${n}) {`),e.indented(S=>{S.write('if (k === "__proto__") continue;'),y&&S.write(`if (${y}.has(k)) continue;`);let k=te(t);S.write(`const ${k} = ${n}[k];`),Tt(S,t,g,k,!1)}),e.write("}")}return null}if(w){e.write(`const ${b} = {};`);for(let y of u){let S=d(y),k=f.get(y);Ob(m[y])?e.write(`if (${S} in ${n}) ${b}[${S}] = ${k};`):mP(m[y])?e.write(`if (${k} !== undefined || ${S} in ${n}) ${b}[${S}] = ${k};`):e.write(`${b}[${S}] = ${k};`)}}else{let y=u.map(S=>`${p(S)}: ${f.get(S)}`).join(", ");e.write(`const ${b} = { ${y} };`)}if(h!=="none"){let y=a.length>0?ue(t,new Set(a)):null;e.write(`for (const k in ${n}) {`),e.indented(S=>{if(S.write('if (k === "__proto__") continue;'),y&&S.write(`if (${y}.has(k)) continue;`),h==="passthrough")S.write(`${b}[k] = ${n}[k];`);else{let k=te(t);S.write(`const ${k} = ${n}[k];`);let R=Tt(S,t,g,k);S.write(`${b}[k] = ${R};`)}}),e.write("}")}return b}function KG(e,t,r,n,s=!0){let o=r._zod.def;if(JG(r))return Ve(e,t,o.innerType,n,s);if(o.innerType._zod.optin==="defaulted"){let a=te(t),c=te(t);return e.write(`let ${a};`),e.write(`if (${n} === undefined) {`),e.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(d=>{let p=Ve(d,t,o.innerType,n);d.write(`return ${p};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${a} = ${c};`)}),e.write("} else {"),e.indented(u=>{let d=Ve(u,t,o.innerType,n);u.write(`${a} = ${d};`)}),e.write("}"),a}let i=s?te(t):null;return i&&e.write(`let ${i};`),e.write(`if (${n} !== undefined) {`),e.indented(a=>{let c=Ve(a,t,o.innerType,n,s);i&&c!==null&&a.write(`${i} = ${c};`)}),e.write("}"),i}function JG(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function YG(e){return e._zod.optin===void 0&&Ms(e)}function Ms(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?Ms(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?Ms(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(Ms):!0;case"intersection":return!t.left||!t.right?!0:Ms(t.left)&&Ms(t.right);case"pipe":return t.in?Ms(t.in):!0;default:return!0}}function Ob(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function mP(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&di(e)}function di(e){let t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?di(t.innerType):!0;case"union":return t.options?t.options.some(di):!0;case"intersection":return!t.left||!t.right||di(t.left)||di(t.right);case"pipe":return t.out?di(t.out):!0;default:return!0}}function QG(e,t,r,n,s=!0){let o=r._zod.def,i=s?te(t):null;return i&&e.write(`let ${i} = null;`),e.write(`if (${n} !== null) {`),e.indented(a=>{let c=Ve(a,t,o.innerType,n,s);i&&c!==null&&a.write(`${i} = ${c};`)}),e.write("}"),i}function Db(e,t,r){for(let[n,s]of ti(t._zod.def.checks))e.write(`if (${r} > ${Bn(n,s._zod.def.check)}) return INVALID;`)}function XG(e,t,r,n,s=!0){let o=r._zod.def;e.write(`if (!Array.isArray(${n})) return INVALID;`),Db(e,r,`${n}.length`);let i=s?te(t):null,a=te(t),c=te(t);return i&&e.write(`const ${i} = new Array(${n}.length);`),e.write(`for (let ${a} = 0; ${a} < ${n}.length; ${a}++) {`),e.indented(u=>{u.write(`const ${c} = ${n}[${a}];`);let d=Tt(u,t,o.element,c,s);i&&d!==null&&u.write(`${i}[${a}] = ${d};`)}),e.write("}"),i}function eU(e,t,r,n){let o=r._zod.def.values;if(o.length!==1){let a=ue(t,new Set(o));return e.write(`if (!${a}.has(${n})) return INVALID;`),n}let i=o[0];if(typeof i=="number"&&Number.isNaN(i)){let a=ue(t,new Set(o));return e.write(`if (!${a}.has(${n})) return INVALID;`),n}if(typeof i=="string")e.write(`if (${n} !== ${Dt(i)}) return INVALID;`);else if(typeof i=="number"||typeof i=="boolean")e.write(`if (${n} !== ${i}) return INVALID;`);else if(i===null)e.write(`if (${n} !== null) return INVALID;`);else if(i===void 0)e.write(`if (${n} !== undefined) return INVALID;`);else if(typeof i=="bigint")e.write(`if (${n} !== ${i}n) return INVALID;`);else throw new Se(`literal type ${typeof i}`);return n}function tU(e,t,r,n){let s=r._zod.values;if(!s)throw new Se("enum schema without enumerated values");let o=ue(t,s);return e.write(`if (!${o}.has(${n})) return INVALID;`),n}function fP(e,t,r,n){let s=r._zod.def;return Ve(e,t,s.innerType,n)}function rU(e,t,r,n){let s=r._zod.def,i=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!i)return Ve(e,t,s.innerType,n);let c=ue(t,i),u=te(t);return e.write(`let ${u} = ${n};`),e.write(`if (${n} === undefined) ${u} = ${c}();`),Ve(e,t,s.innerType,u)}let a=te(t);if(i){let c=ue(t,i),u=ue(t,ic);e.write(`let ${a};`),e.write(`if (${n} === undefined) {`),e.indented(d=>{d.write(`${a} = ${u}(${c}());`)}),e.write("} else {"),e.indented(d=>{let p=Ve(d,t,s.innerType,n);d.write(`${a} = ${p} === undefined ? ${u}(${c}()) : ${p};`)}),e.write("}")}else e.write(`let ${a};`),e.write(`if (${n} !== undefined) {`),e.indented(c=>{let u=Ve(c,t,s.innerType,n);c.write(`${a} = ${u};`)}),e.write("}");return a}function nU(e,t,r,n){let s=r._zod.def,o=Ve(e,t,s.innerType,n),i=te(t);return e.write(`const ${i} = ${o};`),e.write(`if (${i} === undefined) return INVALID;`),i}function sU(e,t,r,n){let s=r._zod.def,o=s.items,i=s.rest;e.write(`if (!Array.isArray(${n})) return INVALID;`);let a=gP(o,"optin"),c=gP(o,"optout");i?e.write(`if (${n}.length < ${a}) return INVALID;`):e.write(`if (${n}.length < ${a} || ${n}.length > ${o.length}) return INVALID;`);let u=te(t);e.write(`const ${u} = [];`);for(let d=0;d<o.length;d++){let p=o[d];if(d>=c)e.write(`if (${u}.length === ${d}) {`),e.indented(m=>{m.write(`if (${d} < ${n}.length) {`),m.indented(f=>{let g=te(t);f.write(`const ${g} = ${n}[${d}];`);let h=Tt(f,t,p,g);f.write(`${u}[${d}] = ${h};`)}),m.write("} else {"),m.indented(f=>{if(Ob(p)){f.write(`${u}.length = ${d};`);return}let g=te(t),h=te(t);f.write(`const ${g} = undefined;`),f.write(`const ${h} = (() => {`),f.indented(b=>{let w=Tt(b,t,p,g);b.write(`return ${w};`)}),f.write("})();"),f.write(`if (${h} === INVALID || ${h} === undefined) ${u}.length = ${d};`),f.write(`else ${u}[${d}] = ${h};`)}),m.write("}")}),e.write("}");else{let m=te(t);e.write(`const ${m} = ${n}[${d}];`);let f=Tt(e,t,p,m);e.write(`${u}[${d}] = ${f};`)}}if(i){let d=te(t),p=te(t);e.write(`for (let ${d} = ${o.length}; ${d} < ${n}.length; ${d}++) {`),e.indented(m=>{m.write(`const ${p} = ${n}[${d}];`);let f=Tt(m,t,i,p);m.write(`${u}[${d}] = ${f};`)}),e.write("}")}return u}function gP(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function oU(e,t,r,n){let s=r._zod.def,o=s.options;if(s.discriminator)return iU(e,t,s,n);if(s.inclusive===!1)throw new Se("exclusive unions (z.xor)");if(o.length===0)return e.write("return INVALID;"),n;if(o.length===1)return Ve(e,t,o[0],n);if(o.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(o.flatMap(d=>d._zod.def.values)),u=ue(t,c);return e.write(`if (!${u}.has(${n})) return INVALID;`),n}let a=te(t);e.write(`let ${a};`);for(let c=0;c<o.length;c++){let u=o[c];c===0?e.write(`${a} = (() => {`):e.write(`if (${a} === INVALID) ${a} = (() => {`),e.indented(d=>{let p=Ve(d,t,u,n);d.write(`return ${p};`)}),e.write("})();")}return e.write(`if (${a} === INVALID) return INVALID;`),a}function iU(e,t,r,n){if(r.unionFallback)throw new Se("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),n;let s=te(t),o=te(t);e.write(`const ${s} = ${n}?.[${Dt(r.discriminator)}];`),e.write(`let ${o};`);let i=!0,a=new Set;for(let c of r.options){let u=c._zod.propValues?.[r.discriminator];if(!u||u.size===0)throw new Se("discriminated union option without static discriminator values");for(let m of u){if(a.has(m))throw new Se(`duplicate discriminator value ${String(m)}`);a.add(m)}let d=Array.from(u,m=>aU(t,s,m)),p=i?"if":"else if";e.write(`${p} (${d.join(" || ")}) {`),e.indented(m=>{let f=Ve(m,t,c,n);m.write(`${o} = ${f};`)}),e.write("}"),i=!1}return e.write("else { return INVALID; }"),o}function aU(e,t,r){if(typeof r=="string")return`${t} === ${Dt(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${t})`:`${t} === ${r}`;if(typeof r=="boolean")return`${t} === ${r}`;if(r===null)return`${t} === null`;if(r===void 0)return`${t} === undefined`;if(typeof r=="bigint")return`${t} === ${r}n`;if(typeof r=="symbol"){let n=ue(e,r);return`${t} === ${n}`}throw new Se(`literal discriminator value ${String(r)}`)}function cU(e,t,r,n){let s=r._zod.def;t.definite=!1;let o=Tt(e,t,s.left,n),i=Tt(e,t,s.right,n),a=ue(t,ci),c=te(t);return e.write(`const ${c} = ${a}(${o}, ${i});`),e.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function uU(e,t,r,n){let s=r._zod.def,o=ue(t,br);e.write(`if (!${o}(${n})) return INVALID;`);let i=te(t),a=te(t),c=te(t);e.write(`const ${i} = {};`);let u=s,d=u.partial?void 0:s.keyType._zod.values;if(d){let f=[];for(let h of d){if(!(typeof h=="string"||typeof h=="number"||typeof h=="symbol"))throw new Se(`record key value ${String(h)}`);let b=typeof h=="number"?h.toString():h;if(b==="__proto__")throw new Se('record key "__proto__"');f.push(b);let w=ue(t,h),y=Ve(e,t,s.keyType,w),S=te(t);e.write(`const ${S} = ${n}[${lU(t,b)}];`);let k=Tt(e,t,s.valueType,S);e.write(`${i}[${y}] = ${k};`)}let g=ue(t,new Set(f));return e.write(`for (const ${a} in ${n}) {`),e.indented(h=>{h.write(`if (${g}.has(${a})) continue;`),u.mode==="loose"?h.write(`if (${a} !== "__proto__") ${i}[${a}] = ${n}[${a}];`):h.write("return INVALID;")}),e.write("}"),i}let p=s.keyType._zod.def;if(!(p.type==="string"&&p.format===void 0&&!p.coerce&&(p.checks?.length??0)===0)){let f=s.mode==="loose",g=Dd(s.keyType);g.definite===!1&&(t.definite=!1);let h=ue(t,g),b=ue(t,pn),w=te(t);return hP(e,t,n,a,y=>{y.write(`let ${w} = ${h}(${a});`),y.write(`if (${w} === INVALID && typeof ${a} === "string" && ${b}.test(${a})) ${w} = ${h}(Number(${a}));`),f?y.write(`if (${w} === INVALID) { ${i}[${a}] = ${n}[${a}]; continue; }`):y.write(`if (${w} === INVALID) return INVALID;`),y.write(`if (${w} === "__proto__") continue;`);let S=te(t);y.write(`const ${S} = ${n}[${a}];`);let k=Tt(y,t,s.valueType,S);y.write(`${i}[${w}] = ${k};`)}),i}return hP(e,t,n,a,f=>{f.write(`const ${c} = ${n}[${a}];`);let g=Tt(f,t,s.valueType,c);f.write(`${i}[${a}] = ${g};`)},"return INVALID;"),i}function hP(e,t,r,n,s,o){let i=ue(t,Object.prototype.propertyIsEnumerable),a=te(t),c=te(t),u=te(t);e.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),e.write(`const ${c} = Object.getOwnPropertyNames(${r});`),e.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),e.indented(d=>{d.write(`const ${n} = ${c}[${u}];`),d.write(`if (${n} === "__proto__" || !${i}.call(${r}, ${n})) continue;`),s(d)}),e.write("}"),e.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),e.indented(d=>{d.write(`const ${n} = ${a}[${u}];`),d.write(`if (!${i}.call(${r}, ${n})) continue;`),o?d.write(o):s(d)}),e.write("}")}function lU(e,t){return typeof t=="string"?Dt(t):ue(e,t)}function dU(e,t,r,n){let s=r._zod.def;e.write(`if (!(${n} instanceof Map)) return INVALID;`),Db(e,r,`${n}.size`);let o=te(t),i=te(t),a=te(t);return e.write(`const ${o} = new Map();`),e.write(`for (const [${i}, ${a}] of ${n}) {`),e.indented(c=>{let u=Ve(c,t,s.keyType,i),d=Ve(c,t,s.valueType,a);c.write(`${o}.set(${u}, ${d});`)}),e.write("}"),o}function pU(e,t,r,n){let s=r._zod.def;e.write(`if (!(${n} instanceof Set)) return INVALID;`),Db(e,r,`${n}.size`);let o=te(t),i=te(t);return e.write(`const ${o} = new Set();`),e.write(`for (const ${i} of ${n}) {`),e.indented(a=>{let c=Ve(a,t,s.valueType,i);a.write(`${o}.add(${c});`)}),e.write("}"),o}function mU(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function fU(e,t,r,n){e.write(`if (typeof ${n} !== "string") return INVALID;`);let s=r._zod.pattern;if(s){let o=ue(t,s);e.write(`${o}.lastIndex = 0;`),e.write(`if (!${o}.test(${n})) return INVALID;`)}return n}function gU(e,t,r,n){let s=r._zod.def,o=Fs(t,s.getter),i=ue(t,{parser:null});e.write(`if (!${i}.parser) {`),e.indented(c=>{c.write(`const inner = ${o}();`),c.write(`${i}.parser = function(input) {`),c.indented(u=>{u.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),u.write("return result.issues.length === 0 ? result.value : INVALID;")}),c.write("};")}),e.write("}");let a=te(t);return e.write(`const ${a} = ${i}.parser(${n});`),e.write(`if (${a} === INVALID) return INVALID;`),a}function hU(e,t,r,n){let s=r._zod.def,o=Ve(e,t,s.in,n);if(s.transform){if(Ns(s.transform))throw new Pr("z.compile: async transforms in pipes are not supported");let i=s.transform,c=Fs(t,d=>{let p={value:d,issues:[],addIssue:xb},m=i(d,p);return m instanceof Promise?Mt:p.issues.length===0?m:Mt}),u=te(t);return e.write(`const ${u} = ${c}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),Ve(e,t,s.out,u)}else return Ve(e,t,s.out,o)}function Ns(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function yU(e,t,r,n){let s=r._zod.def;if(s.fn){if(Ns(s.fn))throw new Pr("z.compile: async custom predicates are not supported");let o=Fs(t,s.fn),i=ue(t,$b),a=te(t);e.write(`const ${a} = ${o}(${n});`),e.write(`if (${a} instanceof Promise) ${i}();`),e.write(`if (!${a}) return INVALID;`)}else throw new Se("custom schema without a predicate function");return n}function bU(e,t,r){let n=e._zod.run({value:r,issues:[]},{});if(n&&typeof n.then=="function")return Mt;let s=n;return s.issues.length===0?s.value:t()}function wU(e,t,r,n){let s=r._zod.def;if(!s.catchValue[Gl])throw new Se("catch with a callback (only a constant catch value compiles)",!1);let o=te(t);e.write(`let ${o} = (() => {`),e.indented(u=>{let d=Tt(u,t,s.innerType,n);u.write(`return ${d};`)}),e.write("})();");let i=ue(t,s.innerType),a=Fs(t,s.catchValue),c=ue(t,bU);return e.write(`if (${o} === INVALID) {`),e.indented(u=>{u.write(`${o} = ${c}(${i}, ${a}, ${n});`),u.write(`if (${o} === INVALID) return INVALID;`)}),e.write("}"),o}function RU(e,t,r,n){let s=r._zod.def;if(s.transform){if(Ns(s.transform))throw new Pr("z.compile: async transforms are not supported");let o=s.transform,a=Fs(t,u=>{let d={value:u,issues:[],addIssue:xb},p=o(u,d);return p instanceof Promise?Mt:d.issues.length===0?p:Mt}),c=te(t);return e.write(`const ${c} = ${a}(${n});`),e.write(`if (${c} === INVALID) return INVALID;`),c}return n}var Mt,pP,Pr,Se,PG,FG,RP=A(()=>{jn();sd();kb();xs();ui();rt();Mt=Symbol.for("zod.compile.invalid"),pP=Symbol.for("zod.compile.fallback"),Pr=class extends Error{constructor(t="z.compile does not support async refinements, transforms, or checks"){super(t),this.name="ZodCompileAsyncError"}},Se=class extends Error{constructor(t,r=!0){super(`z.compile does not support ${t}; this schema must use the runtime parser`),this.name="ZodCompileUnsupportedError",this.islandable=r}};PG=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);FG=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"])});function Ld(e){return e.checks&&(e.checks=[...e.checks]),e}function Lb(e,t){return new e(Ld({type:"string",...U(t)}))}function Mb(e,t){return new e(Ld({type:"string",coerce:!0,...U(t)}))}function Md(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...U(t)})}function Fd(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...U(t)})}function Nd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...U(t)})}function Gd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...U(t)})}function Ud(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...U(t)})}function jd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...U(t)})}function Mc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...U(t)})}function zd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...U(t)})}function Bd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...U(t)})}function Hd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...U(t)})}function Wd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...U(t)})}function Vd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...U(t)})}function qd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...U(t)})}function Zd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...U(t)})}function Kd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...U(t)})}function Jd(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...U(t)})}function Fb(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...U(t)})}function Yd(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...U(t)})}function Qd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...U(t)})}function Xd(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...U(t)})}function ep(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...U(t)})}function tp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...U(t)})}function Nb(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...U(t)})}function Gb(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...U(t)})}function rp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...U(t)})}function Fc(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...U(t)})}function Nc(e,t){return new e({type:"string",format:"date",check:"string_format",...U(t)})}function Gc(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...U(t)})}function Uc(e,t){return new e({type:"string",format:"duration",check:"string_format",...U(t)})}function jb(e,t){return new e(Ld({type:"number",checks:[],...U(t)}))}function zb(e,t){return new e(Ld({type:"number",coerce:!0,checks:[],...U(t)}))}function Bb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...U(t)})}function Hb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...U(t)})}function Wb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...U(t)})}function Vb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...U(t)})}function qb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...U(t)})}function Zb(e,t){return new e({type:"boolean",...U(t)})}function Kb(e,t){return new e({type:"boolean",coerce:!0,...U(t)})}function Jb(e,t){return new e({type:"bigint",...U(t)})}function Yb(e,t){return new e({type:"bigint",coerce:!0,...U(t)})}function Qb(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...U(t)})}function Xb(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...U(t)})}function ew(e,t){return new e({type:"symbol",...U(t)})}function tw(e,t){return new e({type:"undefined",...U(t)})}function rw(e,t){return new e({type:"null",...U(t)})}function nw(e){return new e({type:"any"})}function sw(e){return new e({type:"unknown"})}function ow(e,t){return new e({type:"never",...U(t)})}function iw(e,t){return new e({type:"void",...U(t)})}function aw(e,t){return new e({type:"date",...U(t)})}function cw(e,t){return new e({type:"date",coerce:!0,...U(t)})}function uw(e,t){return new e({type:"nan",...U(t)})}function Ur(e,t){return new td({check:"less_than",...U(t),value:e,inclusive:!1})}function or(e,t){return new td({check:"less_than",...U(t),value:e,inclusive:!0})}function jr(e,t){return new rd({check:"greater_than",...U(t),value:e,inclusive:!1})}function ir(e,t){return new rd({check:"greater_than",...U(t),value:e,inclusive:!0})}function np(e){return jr(0,e)}function sp(e){return Ur(0,e)}function op(e){return or(0,e)}function ip(e){return ir(0,e)}function Hn(e,t){return new jh({check:"multiple_of",...U(t),value:e})}function Wn(e,t){return new Hh({check:"max_size",...U(t),maximum:e})}function zr(e,t){return new Wh({check:"min_size",...U(t),minimum:e})}function Gs(e,t){return new Vh({check:"size_equals",...U(t),size:e})}function Us(e,t){return new qh({check:"max_length",...U(t),maximum:e})}function mn(e,t){return new Zh({check:"min_length",...U(t),minimum:e})}function js(e,t){return new Kh({check:"length_equals",...U(t),length:e})}function pi(e,t){return new Jh({check:"string_format",format:"regex",...U(t),pattern:e})}function mi(e){return new Yh({check:"string_format",format:"lowercase",...U(e)})}function fi(e){return new Qh({check:"string_format",format:"uppercase",...U(e)})}function gi(e,t){return new Xh({check:"string_format",format:"includes",...U(t),includes:e})}function hi(e,t){return new ey({check:"string_format",format:"starts_with",...U(t),prefix:e})}function yi(e,t){return new ty({check:"string_format",format:"ends_with",...U(t),suffix:e})}function ap(e,t,r){return new ry({check:"property",property:e,schema:t,...U(r)})}function bi(e,t){return new ny({check:"properties",shape:e,...U(t)})}function wi(e,t){return new sy({check:"mime_type",mime:e,...U(t)})}function Er(e){return new oy({check:"overwrite",tx:e})}function Ri(e){return Er(t=>t.normalize(e))}function Si(){return Er(e=>e.trim())}function _i(){return Er(e=>e.toLowerCase())}function vi(){return Er(e=>e.toUpperCase())}function ki(){return Er(e=>Ug(e))}function lw(e,t,r){return new e({type:"array",element:t,...U(r)})}function SU(e,t,r){return new e({type:"union",options:t,...U(r)})}function _U(e,t,r){return new e({type:"union",options:t,inclusive:!1,...U(r)})}function vU(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...U(n)})}function kU(e,t,r){return new e({type:"intersection",left:t,right:r})}function CU(e,t,r,n){let s=r instanceof pe,o=s?n:r,i=s?r:null;return new e({type:"tuple",items:t,rest:i,...U(o)})}function PU(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...U(n)})}function EU(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...U(n)})}function AU(e,t,r){return new e({type:"set",valueType:t,...U(r)})}function TU(e,t,r){let n=Array.isArray(t)?Object.fromEntries(t.map(s=>[s,s])):t;return new e({type:"enum",entries:n,...U(r)})}function $U(e,t,r){return new e({type:"enum",entries:t,...U(r)})}function OU(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...U(r)})}function dw(e,t){return new e({type:"file",...U(t)})}function IU(e,t){return new e({type:"transform",transform:t})}function xU(e,t){return new e({type:"optional",innerType:t})}function DU(e,t){return new e({type:"nullable",innerType:t})}function LU(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():ic(r)}})}function MU(e,t,r){return new e({type:"nonoptional",innerType:t,...U(r)})}function FU(e,t){return new e({type:"success",innerType:t})}function NU(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:qg(r)})}function GU(e,t,r){return new e({type:"pipe",in:t,out:r})}function UU(e,t){return new e({type:"readonly",innerType:t})}function jU(e,t,r){return new e({type:"template_literal",parts:t,...U(r)})}function zU(e,t){return new e({type:"lazy",getter:t})}function BU(e,t){return new e({type:"promise",innerType:t})}function pw(e,t,r){let n=U(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function mw(e,t,r){return new e({type:"custom",check:"custom",fn:t,...U(r)})}function fw(e,t){let r=SP(n=>(n.addIssue=s=>{if(typeof s=="string")n.issues.push(ri(s,n.value,r._zod.def));else{let o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),"input"in o||(o.input=n.value),o.inst??(o.inst=r),o.continue??(o.continue=!r._zod.def.abort),n.issues.push(ri(o))}},e(n.value,n)),t);return r}function SP(e,t){let r=new Ne({check:"custom",...U(t)});return r._zod.check=e,r}function gw(e){let t=new Ne({check:"describe"});return t._zod.onattach=[r=>{let n=_t.get(r)??{};_t.add(r,{...n,description:e})}],t._zod.check=()=>{},t}function hw(e){let t=new Ne({check:"meta"});return t._zod.onattach=[r=>{let n=_t.get(r)??{};_t.add(r,{...n,...e})}],t._zod.check=()=>{},t}function yw(e,t){let r=U(t),n=r.truthy??["true","1","yes","on","y","enabled"],s=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(n=n.map(f=>typeof f=="string"?f.toLowerCase():f),s=s.map(f=>typeof f=="string"?f.toLowerCase():f));let o=new Set(n),i=new Set(s),a=e.Codec??Tc,c=e.Boolean??Ec,u=e.String??Ls,d=new u({type:"string",error:r.error}),p=new c({type:"boolean",error:r.error}),m=new a({type:"pipe",in:d,out:p,transform:((f,g)=>{let h=f;return r.case!=="sensitive"&&(h=h.toLowerCase()),o.has(h)?!0:i.has(h)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...i],input:g.value,inst:m,continue:!1}),{})}),reverseTransform:((f,g)=>f===!0?n[0]||"true":s[0]||"false"),error:r.error});return m._zod.bag.truthy=n,m._zod.bag.falsy=s,m._zod.bag.case=r.case??"insensitive",m}function zs(e,t,r,n={}){let s=U(n),o={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...s};return r instanceof RegExp&&(o.pattern=r),new e(o)}var Ub,_P=A(()=>{nd();Lc();ui();rt();Ub={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function jc(e,...t){for(let r of t)for(let n of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,n)&&St(e,n,r[n]);return e}function Vn(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??_t,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function ut(e,t,r,n,s){let o=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:n.path,message:s}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw new Error(s);return Object.assign(r,o),!0}function xe(e,t,r={path:[],schemaPath:[]}){var n;let s=e._zod.def,o=t.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let m=i.schema,f=t.processors[s.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);f(e,t,m,d)}let p=e._zod.parent;p&&(i.ref||(i.ref=p),xe(p,t,d),t.seen.get(p).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&jc(i.schema,c),t.io==="input"&&Ft(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function vP(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function qn(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let n=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let s=i=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(i[0])?.id,m=e.external.uri??(g=>g);if(p)return{ref:m(p)};let f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${m("__shared")}#/${a}/${vP(f)}`}}let c="#",u=`${c}/${a}/`;if(i[1]===r&&!i[1].schema.id)return{ref:c};let d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+vP(d)}},o=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=s(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let p in d)delete d[p];d.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
62
62
 
63
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){o(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){o(i);continue}}if(e.metadataRegistry.get(i[0])?.id){o(i);continue}if(a.cycle){o(i);continue}a.count>1&&e.reused==="ref"&&o(i)}e.external&&(e.sharedDefsExtractedFor=e.external)}function PP(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!="object")return;PP(n);let s=Object.keys(n);if(s.length!==1||s[0]!=="type")return;let o=n.type;for(let i of Array.isArray(o)?o:[o]){if(typeof i!="string")return;r.includes(i)||r.push(i)}}delete e.anyOf,e.type=r.length===1?r[0]:r}function CP(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function bw(e){let t=[];for(let o of e){if(typeof o!="object"||o.type!=="object")return null;for(let i in o)if(!EP.has(i))return null;t.push(o)}let r={},n=new Set;for(let o of t){for(let i in o.properties){if(Object.prototype.hasOwnProperty.call(r,i))continue;let a=[];for(let u of t){let d=u.properties?.[i]??CP(u);d!=null&&(a.some(p=>JSON.stringify(p)===JSON.stringify(d))||a.push(d))}let c=a.length===1?a[0]:bw(a)??{allOf:a};St(r,i,c)}for(let i of o.required??[])n.add(i)}let s={type:"object",properties:r};if(n.size&&(s.required=[...n]),t.every(o=>o.additionalProperties===!1))s.additionalProperties=!1;else{let o=[];for(let i of t){let a=CP(i);a&&!o.some(c=>JSON.stringify(c)===JSON.stringify(a))&&o.push(a)}o.length===1?s.additionalProperties=o[0]:o.length>1&&(s.additionalProperties={allOf:o})}return s}function HU(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let s of EP)if(s in e)return;let r=t.filter(s=>kP.some(o=>Array.isArray(s[o]))),n=null;if(!r.length)n=bw(t);else{let s=r[0],o=kP.find(c=>Array.isArray(s[c]));if(Object.keys(s).length!==1)return;let i=t.filter(c=>c!==s),a=s[o].map(c=>bw([...i,c]));if(a.some(c=>!c))return;n={[o]:a}}n&&(delete e.allOf,jc(e,n))}function Zn(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},p=c.ref;if(c.ref=null,p){n(p);let f=e.seen.get(p),g=f.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(g)):jc(u,g),jc(u,d),a._zod.parent===p)for(let b in u)b==="$ref"||b==="allOf"||b in d||delete u[b];if(g.$ref&&f.def)for(let b in u)b==="$ref"||b==="allOf"||b in f.def&&JSON.stringify(u[b])===JSON.stringify(f.def[b])&&delete u[b]}let m=a._zod.parent;if(m&&m!==p){n(m);let f=e.seen.get(m);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let g in u)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(u[g])===JSON.stringify(f.def[g])&&delete u[g]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())PP(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let u of[c.schema,c.def]){let d=u?.allOf;if(!Array.isArray(d))continue;let p=a.get(d);p?p.push(u):a.set(d,[u])}for(let c of e.intersections)for(let u of a.get(c)??[])HU(u)}}let s={};if(e.target==="draft-2020-12"?s.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?s.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?s.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");s.$id=e.external.uri(a)}jc(s,r.defId?r.schema:r.def??r.schema);let o=e.metadataRegistry.get(t)?.id;o!==void 0&&s.id===o&&delete s.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,St(i,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?s.$defs=i:s.definitions=i);try{let a=JSON.parse(JSON.stringify(s));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ci(t,"input",e.processors),output:Ci(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ft(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Ft(n.element,r);if(n.type==="set")return Ft(n.valueType,r);if(n.type==="lazy")return Ft(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return Ft(n.innerType,r);if(n.type==="intersection")return Ft(n.left,r)||Ft(n.right,r);if(n.type==="record"||n.type==="map")return Ft(n.keyType,r)||Ft(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ft(n.in,r)||Ft(n.out,r);if(n.type==="object"){for(let s in n.shape)if(Ft(n.shape[s],r))return!0;return!1}if(n.type==="union"){for(let s of n.options)if(Ft(s,r))return!0;return!1}if(n.type==="tuple"){for(let s of n.items)if(Ft(s,r))return!0;return!!(n.rest&&Ft(n.rest,r))}return!1}var EP,kP,ww,Ci,zc=A(()=>{Lc();rt();EP=new Set(["type","properties","required","additionalProperties"]),kP=["oneOf","anyOf"];ww=(e,t={})=>r=>{let n=Vn({...r,processors:t});return xe(e,n),qn(n,e),Zn(n,e)},Ci=(e,t,r={})=>n=>{let{libraryOptions:s,target:o}=n??{},i=Vn({...s??{},target:o,io:t,processors:r});return xe(e,i),qn(i,e),Zn(i,e)}});function lt(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let o of n)WU[o._zod.def.check]?.(t,o._zod.def);let s=e._zod.bag;s.minimum!==void 0&&Pi(t,"minimum",s.minimum),s.exclusiveMinimum!==void 0&&Pi(t,"exclusiveMinimum",s.exclusiveMinimum),s.maximum!==void 0&&Ei(t,"maximum",s.maximum),s.exclusiveMaximum!==void 0&&Ei(t,"exclusiveMaximum",s.exclusiveMaximum),s.multipleOf!==void 0&&IP(t,s.multipleOf),s.format!==void 0&&(t.format??(t.format=s.format),s.format.includes("int")&&(t.isInt=!0)),s.mime&&DP(t,s.mime);for(let o of s.patterns??[])xP(t,o);return t}function Bc(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Bc(t.out):t.type==="catch"?Bc(t.innerType):e._zod.optin}function Rw(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let g=e.get(t)?.def;if(!g)return t;let h=Rw(e,g,r);return h===g?t:h}for(let g of["anyOf","oneOf"]){let h=t[g];if(!Array.isArray(h))continue;let b=h.map(w=>Rw(e,w,r));b.some((w,y)=>w!==h[y])&&(t={...t,[g]:b})}let n=Array.isArray(t.type)?t.type:[t.type],s=!n.includes("string")&&n.some(g=>g==="number"||g==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!s&&!o?.some(g=>typeof g=="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:d,format:p,id:m,...f}=t;return f.enum?f.enum=f.enum.map(g=>typeof g=="number"?String(g):g):typeof f.const=="number"&&(f.const=String(f.const)),s&&(f.type="string",o||(f.pattern=(n.includes("number")?pn:wc).source)),f}function ZU(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let r=new Map;for(let n of Sw.get(e)??[]){let s=e.seen.get(n),o=(s?.def??s?.schema)?.propertyNames;if(!o||o===!0||r.has(o))continue;let i=Rw(t,o,new Set);i!==o&&r.set(o,i)}if(r.size)for(let n of e.seen.values())for(let s of[n.schema,n.def]){let o=s&&r.get(s.propertyNames);o&&(s.propertyNames=o)}}function FP(e,t,r,n,s){let o=!1,i=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(o=!0,null));return o?(ut(t,r,n,s,"BigInt defaults cannot be represented in JSON Schema"),Qw):JSON.parse(i)}function dp(e,t){if("_idmap"in e){let n=e,s=Vn({...t,processors:cp}),o={};for(let c of n._idmap.entries()){let[u,d]=c;xe(d,s)}let i={},a={registry:n,uri:t?.uri,defs:o};s.external=a;for(let c of n._idmap.entries()){let[u,d]=c;qn(s,d),St(i,u,Zn(s,d))}if(Object.keys(o).length>0){let c=s.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[c]:o}}return{schemas:i}}let r=Vn({...t,processors:cp});return xe(e,r),qn(r,e),Zn(r,e)}var Pi,Ei,AP,IP,xP,DP,LP,TP,$P,OP,WU,VU,qU,MP,_w,vw,kw,Cw,Pw,Ew,Aw,Tw,$w,Ow,Iw,xw,Dw,Lw,Mw,Fw,Nw,Gw,Uw,jw,zw,Bw,Hw,Ww,Vw,up,qw,Zw,Sw,Kw,Jw,Yw,Qw,Xw,eR,tR,rR,nR,sR,lp,oR,cp,Hc=A(()=>{xs();ui();zc();rt();Pi=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Ei=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},AP=(e,t)=>{Pi(e,"minimum",t),Ei(e,"maximum",t)},IP=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},xP=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},DP=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},LP=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},TP=(e,t)=>Pi(e,"minimum",t.minimum),$P=(e,t)=>Ei(e,"maximum",t.maximum),OP=e=>(t,r)=>{LP(t,r.format);let[n,s]=e[r.format];Pi(t,"minimum",n),Ei(t,"maximum",s)},WU={greater_than:(e,t)=>Pi(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Ei(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>IP(e,t.value),number_format:OP(cc),bigint_format:OP(uc),min_length:TP,max_length:$P,length_equals:(e,t)=>AP(e,t.length),min_size:TP,max_size:$P,size_equals:(e,t)=>AP(e,t.size),string_format:(e,t)=>{LP(e,t.format),t.pattern&&xP(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>DP(e,t.mime)};VU={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},qU=new Map([[fd,Sh],[Pc,_h]]),MP=e=>qU.get(e)??e,_w=(e,t,r,n)=>{let s=r;s.type="string";let{minimum:o,maximum:i,format:a,patterns:c,contentEncoding:u,laxFormat:d}=lt(e);if(typeof o=="number"&&(s.minLength=o),typeof i=="number"&&(s.maxLength=i),a&&(s.format=VU[a]??a,s.format===""&&delete s.format,(a==="time"||d)&&delete s.format),u&&(s.contentEncoding=u),c&&c.size>0){let p=[...c].map(MP);p.length===1?s.pattern=p[0].source:p.length>1&&(s.allOf=[...p.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},vw=(e,t,r,n)=>{let s=r,{minimum:o,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:d}=lt(e);s.type=d?"integer":"number";let p=typeof u=="number"&&u>=(o??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(p?f?(s.minimum=u,s.exclusiveMinimum=!0):s.exclusiveMinimum=u:typeof o=="number"&&(s.minimum=o),m?f?(s.maximum=c,s.exclusiveMaximum=!0):s.exclusiveMaximum=c:typeof i=="number"&&(s.maximum=i),a){let g=new Set;for(let w of a)Number.isFinite(w)&&w!==0?g.add(Math.abs(w)):ut(e,t,s,n,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[h,...b]=g;h!==void 0&&(s.multipleOf=h),b.length&&(s.allOf=[...s.allOf??[],...b.map(w=>({multipleOf:w}))])}},kw=(e,t,r,n)=>{r.type="boolean"},Cw=(e,t,r,n)=>{ut(e,t,r,n,"BigInt cannot be represented in JSON Schema")},Pw=(e,t,r,n)=>{ut(e,t,r,n,"Symbols cannot be represented in JSON Schema")},Ew=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Aw=(e,t,r,n)=>{ut(e,t,r,n,"Undefined cannot be represented in JSON Schema")},Tw=(e,t,r,n)=>{ut(e,t,r,n,"Void cannot be represented in JSON Schema")},$w=(e,t,r,n)=>{r.not={}},Ow=(e,t,r,n)=>{},Iw=(e,t,r,n)=>{},xw=(e,t,r,n)=>{ut(e,t,r,n,"Date cannot be represented in JSON Schema")},Dw=(e,t,r,n)=>{let s=e._zod.def,o=Yo(s.entries);if(o.length===0){r.not={};return}o.every(i=>typeof i=="number")&&(r.type="number"),o.every(i=>typeof i=="string")&&(r.type="string"),r.enum=o},Lw=(e,t,r,n)=>{let s=e._zod.def;if(s.values.length===0){r.not={};return}let o=[];for(let i of s.values)if(i===void 0){if(ut(e,t,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i=="bigint"){if(ut(e,t,r,n,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(i))}else o.push(i);if(o.length!==0)if(o.length===1){let i=o[0];r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[i]:r.const=i}else o.every(i=>typeof i=="number")&&(r.type="number"),o.every(i=>typeof i=="string")&&(r.type="string"),o.every(i=>typeof i=="boolean")&&(r.type="boolean"),o.every(i=>i===null)&&(r.type="null"),r.enum=o},Mw=(e,t,r,n)=>{ut(e,t,r,n,"NaN cannot be represented in JSON Schema")},Fw=(e,t,r,n)=>{let s=r,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");s.type="string",s.pattern=o.source},Nw=(e,t,r,n)=>{let s=r;s.type="string",s.format="binary",s.contentEncoding="binary";let{minimum:o,maximum:i,mime:a}=lt(e);o!==void 0&&(s.minLength=o),i!==void 0&&(s.maxLength=i),a&&(a.length===0?s.not={}:a.length===1?s.contentMediaType=a[0]:s.anyOf=a.map(c=>({contentMediaType:c})))},Gw=(e,t,r,n)=>{r.type="boolean"},Uw=(e,t,r,n)=>{ut(e,t,r,n,"Custom types cannot be represented in JSON Schema")},jw=(e,t,r,n)=>{ut(e,t,r,n,"Function types cannot be represented in JSON Schema")},zw=(e,t,r,n)=>{ut(e,t,r,n,"Transforms cannot be represented in JSON Schema")},Bw=(e,t,r,n)=>{ut(e,t,r,n,"Map cannot be represented in JSON Schema")},Hw=(e,t,r,n)=>{ut(e,t,r,n,"Set cannot be represented in JSON Schema")},Ww=(e,t,r,n)=>{let s=r,o=e._zod.def,{minimum:i,maximum:a}=lt(e);typeof i=="number"&&(s.minItems=i),typeof a=="number"&&(s.maxItems=a),s.type="array",s.items=xe(o.element,t,{...n,path:[...n.path,"items"]})};Vw=(e,t,r,n)=>{let s=r,o=e._zod.def,i=o.shape;if(Object.getOwnPropertySymbols(i).length&&ut(e,t,s,n,"Symbol keys cannot be represented in JSON Schema"))return;s.type="object",s.properties={};for(let u in i)St(s.properties,u,xe(i[u],t,{...n,path:[...n.path,"properties",u]}));let c=[];for(let u of Object.keys(i)){let d=o.shape[u];(t.io==="input"?Bc(d)===void 0:d._zod.optout===void 0)&&c.push(u)}c.length>0&&(s.required=c),o.catchall?._zod.def.type==="never"?s.additionalProperties=!1:o.catchall?o.catchall&&(s.additionalProperties=xe(o.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(s.additionalProperties=!1)},up=(e,t,r,n)=>{let s=e._zod.def,o=s.inclusive===!1,i=s.options.map((a,c)=>xe(a,t,{...n,path:[...n.path,o?"oneOf":"anyOf",c]}));o?r.oneOf=i:r.anyOf=i},qw=(e,t,r,n)=>{let s=e._zod.def,o=xe(s.left,t,{...n,path:[...n.path,"allOf",0]}),i=xe(s.right,t,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(i)?i.allOf:[i]];r.allOf=c,t.intersections.push(c)},Zw=(e,t,r,n)=>{let s=r,o=e._zod.def;s.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((h,b)=>xe(h,t,{...n,path:[...n.path,i,b]})),u=o.rest?xe(o.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null,d=o.items.length;for(;d>0;){let h=o.items[d-1];if(!(t.io==="input"?Bc(h)!==void 0:h._zod.optout==="optional"))break;d--}let p=o.items.length,m=!o.rest;t.target==="draft-2020-12"?(s.prefixItems=c,m?s.items=!1:u&&(s.items=u),d>0&&(s.minItems=d),m&&(s.maxItems=p)):t.target==="openapi-3.0"?(s.items={anyOf:c},u&&s.items.anyOf.push(u),d>0&&(s.minItems=d),m&&(s.maxItems=p)):(s.items=c,m?s.additionalItems=!1:u&&(s.additionalItems=u),d>0&&(s.minItems=d),m&&(s.maxItems=p));let{minimum:f,maximum:g}=lt(e);typeof f=="number"&&(s.minItems=f),typeof g=="number"&&(s.maxItems=g)};Sw=new WeakMap;Kw=(e,t,r,n)=>{let s=r,o=e._zod.def;s.type="object";let i=o.keyType,a=lt(i).patterns;if(o.mode==="loose"&&a&&a.size>0){let d=xe(o.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});s.patternProperties={};for(let p of a)St(s.patternProperties,MP(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){s.propertyNames=xe(o.keyType,t,{...n,path:[...n.path,"propertyNames"]});let d=Sw.get(t);d||(d=[],Sw.set(t,d),t.deferred.push(()=>ZU(t))),d.push(e)}s.additionalProperties=xe(o.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=i._zod.values,u=t.io==="input"&&Bc(o.valueType)!==void 0;if(c&&!o.partial&&!u){let d=[...c].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(s.required=d.map(String))}},Jw=(e,t,r,n)=>{let s=e._zod.def,o=xe(s.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=s.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},Yw=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},Qw=Symbol();Xw=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType;let i=FP(s.defaultValue,e,t,r,n);i!==Qw&&(r.default=i)},eR=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);if(o.ref=s.innerType,t.io!=="input")return;let i=FP(s.defaultValue,e,t,r,n);i!==Qw&&(r._prefault=i)},tR=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType;let i;try{i=s.catchValue(void 0)}catch{ut(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=i},rR=(e,t,r,n)=>{let s=e._zod.def,o=s.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?o?s.out:s.in:s.out;xe(i,t,n);let a=t.seen.get(e);a.ref=i},nR=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType,r.readOnly=!0},sR=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},lp=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},oR=(e,t,r,n)=>{let s=e._zod.innerType;xe(s,t,n);let o=t.seen.get(e);o.ref=s},cp={string:_w,number:vw,boolean:kw,bigint:Cw,symbol:Pw,null:Ew,undefined:Aw,void:Tw,never:$w,any:Ow,unknown:Iw,date:xw,enum:Dw,literal:Lw,nan:Mw,template_literal:Fw,file:Nw,success:Gw,custom:Uw,function:jw,transform:zw,map:Bw,set:Hw,array:Ww,object:Vw,union:up,intersection:qw,tuple:Zw,record:Kw,nullable:Jw,nonoptional:Yw,default:Xw,prefault:eR,catch:tR,pipe:rR,readonly:nR,promise:sR,optional:lp,lazy:oR}});var pp,NP=A(()=>{Hc();zc();pp=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Vn({processors:cp,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return xe(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,qn(this.ctx,t);let n=Zn(this.ctx,t),{"~standard":s,...o}=n;return o}}});var GP={};var UP=A(()=>{});var fn={};re(fn,{$ZodAny:()=>By,$ZodArray:()=>Ky,$ZodAsyncError:()=>Zt,$ZodBase64:()=>Oy,$ZodBase64URL:()=>Iy,$ZodBigInt:()=>Rd,$ZodBigIntFormat:()=>Gy,$ZodBoolean:()=>Ec,$ZodCIDRv4:()=>Ty,$ZodCIDRv6:()=>$y,$ZodCUID:()=>yy,$ZodCUID2:()=>by,$ZodCatch:()=>fb,$ZodCheck:()=>Fe,$ZodCheckBigIntFormat:()=>Bh,$ZodCheckEndsWith:()=>ty,$ZodCheckGreaterThan:()=>rd,$ZodCheckIncludes:()=>Xh,$ZodCheckLengthEquals:()=>Kh,$ZodCheckLessThan:()=>td,$ZodCheckLowerCase:()=>Yh,$ZodCheckMaxLength:()=>qh,$ZodCheckMaxSize:()=>Hh,$ZodCheckMimeType:()=>sy,$ZodCheckMinLength:()=>Zh,$ZodCheckMinSize:()=>Wh,$ZodCheckMultipleOf:()=>jh,$ZodCheckNumberFormat:()=>zh,$ZodCheckOverwrite:()=>oy,$ZodCheckProperties:()=>ny,$ZodCheckProperty:()=>ry,$ZodCheckRegex:()=>Jh,$ZodCheckSizeEquals:()=>Vh,$ZodCheckStartsWith:()=>ey,$ZodCheckStringFormat:()=>ai,$ZodCheckUpperCase:()=>Qh,$ZodCodec:()=>Tc,$ZodCreditCard:()=>Dy,$ZodCustom:()=>Sb,$ZodCustomStringFormat:()=>Fy,$ZodCyclicError:()=>Ed,$ZodDate:()=>qy,$ZodDefault:()=>lb,$ZodDiscriminatedUnion:()=>Xy,$ZodE164:()=>xy,$ZodEmail:()=>dy,$ZodEmoji:()=>gy,$ZodEncodeError:()=>zn,$ZodEnum:()=>sb,$ZodError:()=>Xg,$ZodExactOptional:()=>cb,$ZodFile:()=>ib,$ZodFunction:()=>wb,$ZodGUID:()=>uy,$ZodIBAN:()=>Ly,$ZodIPv4:()=>Py,$ZodIPv6:()=>Ey,$ZodISODate:()=>vy,$ZodISODateTime:()=>_y,$ZodISODuration:()=>Cy,$ZodISOTime:()=>ky,$ZodIntersection:()=>eb,$ZodJWT:()=>My,$ZodKSUID:()=>Sy,$ZodLazy:()=>$c,$ZodLiteral:()=>ob,$ZodMAC:()=>Ay,$ZodMap:()=>rb,$ZodNaN:()=>gb,$ZodNanoID:()=>hy,$ZodNever:()=>Wy,$ZodNonOptional:()=>pb,$ZodNull:()=>zy,$ZodNullable:()=>ub,$ZodNumber:()=>wd,$ZodNumberFormat:()=>Ny,$ZodObject:()=>oP,$ZodObjectJIT:()=>Jy,$ZodOptional:()=>_d,$ZodPipe:()=>vd,$ZodPrefault:()=>db,$ZodPreprocess:()=>hb,$ZodPromise:()=>Rb,$ZodReadonly:()=>yb,$ZodRealError:()=>Kt,$ZodRecord:()=>tb,$ZodRegistry:()=>Od,$ZodSet:()=>nb,$ZodString:()=>Ls,$ZodStringFormat:()=>Ie,$ZodSuccess:()=>mb,$ZodSymbol:()=>Uy,$ZodTemplateLiteral:()=>bb,$ZodTransform:()=>ab,$ZodTuple:()=>Sd,$ZodType:()=>pe,$ZodULID:()=>wy,$ZodURL:()=>fy,$ZodUUID:()=>ly,$ZodUndefined:()=>jy,$ZodUnion:()=>Ac,$ZodUnknown:()=>Hy,$ZodVoid:()=>Vy,$ZodXID:()=>Ry,$ZodXor:()=>Yy,$brand:()=>Jg,$constructor:()=>$,$input:()=>Ab,$output:()=>Eb,Doc:()=>Ds,INVALID:()=>Mt,JSONSchema:()=>GP,JSONSchemaGenerator:()=>pp,NEVER:()=>Kg,TimePrecision:()=>Ub,URL_BAD_FORMAT:()=>py,URL_UNPARSEABLE:()=>_c,ZodCompileAsyncError:()=>Pr,ZodCompileUnsupportedError:()=>Se,_any:()=>nw,_array:()=>lw,_base64:()=>Xd,_base64url:()=>ep,_bigint:()=>Jb,_boolean:()=>Zb,_catch:()=>NU,_check:()=>SP,_cidrv4:()=>Yd,_cidrv6:()=>Qd,_coercedBigint:()=>Yb,_coercedBoolean:()=>Kb,_coercedDate:()=>cw,_coercedNumber:()=>zb,_coercedString:()=>Mb,_creditCard:()=>Nb,_cuid:()=>Hd,_cuid2:()=>Wd,_custom:()=>pw,_date:()=>aw,_decode:()=>Hl,_decodeAsync:()=>Vl,_default:()=>LU,_discriminatedUnion:()=>vU,_e164:()=>tp,_email:()=>Md,_emoji:()=>zd,_encode:()=>Bl,_encodeAsync:()=>Wl,_endsWith:()=>yi,_enum:()=>TU,_file:()=>dw,_float32:()=>Hb,_float64:()=>Wb,_gt:()=>jr,_gte:()=>ir,_guid:()=>Fd,_iban:()=>Gb,_includes:()=>gi,_int:()=>Bb,_int32:()=>Vb,_int64:()=>Qb,_intersection:()=>kU,_ipv4:()=>Kd,_ipv6:()=>Jd,_isoDate:()=>Nc,_isoDateTime:()=>Fc,_isoDuration:()=>Uc,_isoTime:()=>Gc,_jwt:()=>rp,_ksuid:()=>Zd,_lazy:()=>zU,_length:()=>js,_literal:()=>OU,_lowercase:()=>mi,_lt:()=>Ur,_lte:()=>or,_mac:()=>Fb,_map:()=>EU,_max:()=>or,_maxLength:()=>Us,_maxSize:()=>Wn,_mime:()=>wi,_min:()=>ir,_minLength:()=>mn,_minSize:()=>zr,_multipleOf:()=>Hn,_nan:()=>uw,_nanoid:()=>Bd,_nativeEnum:()=>$U,_negative:()=>sp,_never:()=>ow,_nonnegative:()=>ip,_nonoptional:()=>MU,_nonpositive:()=>op,_normalize:()=>Ri,_null:()=>rw,_nullable:()=>DU,_number:()=>jb,_optional:()=>xU,_overwrite:()=>Er,_parse:()=>ni,_parseAsync:()=>si,_pipe:()=>GU,_positive:()=>np,_promise:()=>BU,_properties:()=>bi,_property:()=>ap,_readonly:()=>UU,_record:()=>PU,_refine:()=>mw,_regex:()=>pi,_safeDecode:()=>Zl,_safeDecodeAsync:()=>Jl,_safeEncode:()=>ql,_safeEncodeAsync:()=>Kl,_safeParse:()=>oi,_safeParseAsync:()=>ii,_set:()=>AU,_size:()=>Gs,_slugify:()=>ki,_startsWith:()=>hi,_string:()=>Lb,_stringFormat:()=>zs,_stringbool:()=>yw,_success:()=>FU,_superRefine:()=>fw,_symbol:()=>ew,_templateLiteral:()=>jU,_toLowerCase:()=>_i,_toUpperCase:()=>vi,_transform:()=>IU,_trim:()=>Si,_tuple:()=>CU,_uint32:()=>qb,_uint64:()=>Xb,_ulid:()=>Vd,_undefined:()=>tw,_union:()=>SU,_unknown:()=>sw,_uppercase:()=>fi,_url:()=>Mc,_uuid:()=>Nd,_uuidv4:()=>Gd,_uuidv6:()=>Ud,_uuidv7:()=>jd,_void:()=>iw,_xid:()=>qd,_xor:()=>_U,base64Charset:()=>fd,base64urlCharset:()=>Pc,canParseURL:()=>my,clone:()=>Oe,compile:()=>Ib,compileFn:()=>Dd,config:()=>Ye,createStandardJSONSchemaMethod:()=>Ci,createToJSONSchemaMethod:()=>ww,decode:()=>AN,decodeAsync:()=>$N,describe:()=>gw,encode:()=>EN,encodeAsync:()=>TN,extractDefs:()=>qn,finalize:()=>Zn,flattenError:()=>fc,formatError:()=>gc,getDiscriminatedOption:()=>Qy,globalConfig:()=>ht,globalRegistry:()=>_t,handleUnrepresentable:()=>ut,initializeContext:()=>Vn,isBackEdge:()=>Td,isRecursiveSchema:()=>Ad,isValidBase64:()=>Cc,isValidBase64URL:()=>gd,isValidCIDRv6:()=>md,isValidCreditCard:()=>hd,isValidIBAN:()=>yd,isValidIPv6:()=>kc,isValidJWT:()=>bd,locales:()=>Dc,memoizer:()=>xc,mergeValues:()=>ci,meta:()=>hw,parse:()=>jl,parseAsync:()=>zl,parseURLObject:()=>rP,prettifyError:()=>th,process:()=>xe,processSchema:()=>xe,regexes:()=>Rr,registry:()=>Id,safeDecode:()=>IN,safeDecodeAsync:()=>DN,safeEncode:()=>ON,safeEncodeAsync:()=>xN,safeParse:()=>_N,safeParseAsync:()=>vN,standardProps:()=>ud,stripTabAndNewline:()=>vc,toDotPath:()=>LC,toJSONSchema:()=>dp,toZod:()=>sc,treeifyError:()=>eh,urlHostnameOk:()=>dd,urlProtocolOk:()=>pd,util:()=>V,validate:()=>hc,validateAsync:()=>yc,validateURL:()=>ld,version:()=>iy,withParser:()=>xd});var ar=A(()=>{jn();nh();rh();ui();kb();nd();ay();rt();rt();xs();Pb();Lc();sd();RP();_P();zc();Hc();NP();UP()});var mp={};re(mp,{endsWith:()=>yi,gt:()=>jr,gte:()=>ir,includes:()=>gi,length:()=>js,lowercase:()=>mi,lt:()=>Ur,lte:()=>or,maxLength:()=>Us,maxSize:()=>Wn,mime:()=>wi,minLength:()=>mn,minSize:()=>zr,multipleOf:()=>Hn,negative:()=>sp,nonnegative:()=>ip,nonpositive:()=>op,normalize:()=>Ri,overwrite:()=>Er,positive:()=>np,properties:()=>bi,property:()=>ap,regex:()=>pi,size:()=>Gs,slugify:()=>ki,startsWith:()=>hi,toLowerCase:()=>_i,toUpperCase:()=>vi,trim:()=>Si,uppercase:()=>fi});var fp=A(()=>{ar()});function gp(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var jP,zP,JU,Jt,iR=A(()=>{ar();ar();rt();jP=new WeakSet([Object.prototype,Error.prototype]);zP=(e,t)=>{Xg.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);jP.has(r)||(jP.add(r),gp(r,"format",n=>s=>gc(n,s)),gp(r,"flatten",n=>s=>fc(n,s)),gp(r,"addIssue",n=>s=>{n.issues.push(s),n.message=JSON.stringify(n.issues,Qo,2)}),gp(r,"addIssues",n=>s=>{n.issues.push(...s),n.message=JSON.stringify(n.issues,Qo,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},JU=$("ZodError",zP),Jt=$("ZodError",zP,void 0,{Parent:Error})});var aR,cR,uR,lR,dR,pR,mR,fR,gR,hR,yR,bR,wR=A(()=>{ar();iR();ar();aR=ni(Jt),cR=si(Jt),uR=oi(Jt),lR=ii(Jt),dR=Bl(Jt),pR=Hl(Jt),mR=Wl(Jt),fR=Vl(Jt),gR=ql(Jt),hR=Zl(Jt),yR=Kl(Jt),bR=Jl(Jt)});var Li={};re(Li,{ZodAny:()=>TR,ZodArray:()=>xR,ZodBase64:()=>Ip,ZodBase64URL:()=>xp,ZodBigInt:()=>xi,ZodBigIntFormat:()=>Mp,ZodBoolean:()=>Ii,ZodCIDRv4:()=>$p,ZodCIDRv6:()=>Op,ZodCUID:()=>vp,ZodCUID2:()=>kp,ZodCatch:()=>eS,ZodCodec:()=>eu,ZodCreditCard:()=>SR,ZodCustom:()=>tu,ZodCustomStringFormat:()=>Vs,ZodDate:()=>Zc,ZodDefault:()=>ZR,ZodDiscriminatedUnion:()=>LR,ZodE164:()=>Dp,ZodEmail:()=>wp,ZodEmoji:()=>Sp,ZodEnum:()=>Ti,ZodExactOptional:()=>Up,ZodFile:()=>HR,ZodFunction:()=>lS,ZodGUID:()=>Rp,ZodIBAN:()=>_R,ZodIPv4:()=>Ap,ZodIPv6:()=>Tp,ZodISODate:()=>Jn,ZodISODateTime:()=>Kn,ZodISODuration:()=>Qn,ZodISOTime:()=>Yn,ZodInstanceOf:()=>mS,ZodIntersection:()=>MR,ZodJWT:()=>Lp,ZodKSUID:()=>Ep,ZodLazy:()=>aS,ZodLiteral:()=>BR,ZodMAC:()=>RR,ZodMap:()=>jR,ZodNaN:()=>rS,ZodNanoID:()=>_p,ZodNever:()=>OR,ZodNonOptional:()=>jp,ZodNull:()=>ER,ZodNullable:()=>qR,ZodNumber:()=>Oi,ZodNumberFormat:()=>qs,ZodObject:()=>Jc,ZodOptional:()=>Qc,ZodPipe:()=>Xc,ZodPrefault:()=>JR,ZodPreprocess:()=>nS,ZodPromise:()=>uS,ZodReadonly:()=>sS,ZodRecord:()=>Ai,ZodSet:()=>zR,ZodString:()=>$i,ZodStringFormat:()=>Le,ZodSuccess:()=>XR,ZodSymbol:()=>CR,ZodTemplateLiteral:()=>iS,ZodTransform:()=>WR,ZodTuple:()=>NR,ZodType:()=>ge,ZodULID:()=>Cp,ZodURL:()=>qc,ZodUUID:()=>Br,ZodUndefined:()=>PR,ZodUnion:()=>Yc,ZodUnknown:()=>$R,ZodVoid:()=>IR,ZodXID:()=>Pp,ZodXor:()=>DR,_ZodString:()=>bp,_default:()=>KR,_function:()=>QE,any:()=>TE,array:()=>Kc,base64:()=>uE,base64url:()=>lE,bigint:()=>kE,boolean:()=>kR,catch:()=>tS,check:()=>XE,cidrv4:()=>aE,cidrv6:()=>cE,codec:()=>ZE,creditCard:()=>pE,cuid:()=>XP,cuid2:()=>eE,currencyCode:()=>bE,custom:()=>eA,date:()=>OE,describe:()=>tA,discriminatedUnion:()=>FE,e164:()=>dE,email:()=>BP,emoji:()=>YP,enum:()=>Np,exactOptional:()=>VR,file:()=>HE,float32:()=>RE,float64:()=>SE,function:()=>QE,guid:()=>HP,hash:()=>wE,hex:()=>yE,hostname:()=>hE,httpUrl:()=>JP,iban:()=>mE,instanceof:()=>nA,int:()=>hp,int32:()=>_E,int64:()=>CE,intersection:()=>FR,invertCodec:()=>KE,ipv4:()=>sE,ipv6:()=>iE,json:()=>oA,jwt:()=>fE,keyof:()=>IE,ksuid:()=>nE,lazy:()=>cS,literal:()=>BE,looseObject:()=>LE,looseRecord:()=>GE,mac:()=>oE,map:()=>UE,meta:()=>rA,nan:()=>qE,nanoid:()=>QP,nativeEnum:()=>zE,never:()=>Fp,nonoptional:()=>QR,null:()=>AR,nullable:()=>Vc,nullish:()=>WE,number:()=>vR,object:()=>xE,optional:()=>Hs,partialRecord:()=>NE,pipe:()=>yp,prefault:()=>YR,preprocess:()=>iA,promise:()=>YE,readonly:()=>oS,record:()=>UR,refine:()=>dS,set:()=>jE,strictObject:()=>DE,string:()=>Wc,stringFormat:()=>gE,stringbool:()=>sA,success:()=>VE,superRefine:()=>pS,symbol:()=>EE,templateLiteral:()=>JE,transform:()=>Gp,tuple:()=>GR,uint32:()=>vE,uint64:()=>PE,ulid:()=>tE,undefined:()=>AE,union:()=>Di,unknown:()=>Bs,url:()=>KP,uuid:()=>WP,uuidv4:()=>VP,uuidv6:()=>qP,uuidv7:()=>ZP,void:()=>$E,xid:()=>rE,xor:()=>ME});function QU(){ht.localeError||Ye($d())}function Ws(){ht.memoizer||Ye({memoizer:xc()})}function Wc(e){return Lb($i,e)}function BP(e){return Md(wp,e)}function HP(e){return Fd(Rp,e)}function WP(e){return Nd(Br,e)}function VP(e){return Gd(Br,e)}function qP(e){return Ud(Br,e)}function ZP(e){return jd(Br,e)}function KP(e){return Mc(qc,e)}function JP(e){return Mc(qc,{protocol:bc,hostname:kh,...V.normalizeParams(e)})}function YP(e){return zd(Sp,e)}function QP(e){return Bd(_p,e)}function XP(e){return Hd(vp,e)}function eE(e){return Wd(kp,e)}function tE(e){return Vd(Cp,e)}function rE(e){return qd(Pp,e)}function nE(e){return Zd(Ep,e)}function sE(e){return Kd(Ap,e)}function oE(e){return Fb(RR,e)}function iE(e){return Jd(Tp,e)}function aE(e){return Yd($p,e)}function cE(e){return Qd(Op,e)}function uE(e){return Xd(Ip,e)}function lE(e){return ep(xp,e)}function dE(e){return tp(Dp,e)}function pE(e){return Nb(SR,e)}function mE(e){return Gb(_R,e)}function fE(e){return rp(Lp,e)}function gE(e,t,r={}){return zs(Vs,e,t,r)}function hE(e){return zs(Vs,"hostname",vh,e)}function yE(e){return zs(Vs,"hex",Nh,e)}function bE(e){return zs(Vs,"currency_code",Ph,e)}function wE(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,s=Rr[n];if(!s)throw new Error(`Unrecognized hash format: ${n}`);return zs(Vs,n,s,t)}function vR(e){return jb(Oi,e)}function hp(e){return Bb(qs,e)}function RE(e){return Hb(qs,e)}function SE(e){return Wb(qs,e)}function _E(e){return Vb(qs,e)}function vE(e){return qb(qs,e)}function kR(e){return Zb(Ii,e)}function kE(e){return Jb(xi,e)}function CE(e){return Qb(Mp,e)}function PE(e){return Xb(Mp,e)}function EE(e){return ew(CR,e)}function AE(e){return tw(PR,e)}function AR(e){return rw(ER,e)}function TE(){return nw(TR)}function Bs(){return sw($R)}function Fp(e){return ow(OR,e)}function $E(e){return iw(IR,e)}function OE(e){return aw(Zc,e)}function Kc(e,t){return lw(xR,e,t)}function IE(e){let t=e._zod.def.shape;return Np(Object.keys(t))}function xE(e,t){let r={type:"object",shape:e??{},...V.normalizeParams(t)};return new Jc(r)}function DE(e,t){return new Jc({type:"object",shape:e,catchall:Fp(),...V.normalizeParams(t)})}function LE(e,t){return new Jc({type:"object",shape:e,catchall:Bs(),...V.normalizeParams(t)})}function Di(e,t){return new Yc({type:"union",options:e,...V.normalizeParams(t)})}function ME(e,t){return new DR({type:"union",options:e,inclusive:!1,...V.normalizeParams(t)})}function FE(e,t,r){return new LR({type:"union",options:t,discriminator:e,...V.normalizeParams(r)})}function FR(e,t){return new MR({type:"intersection",left:e,right:t})}function GR(e,t,r){let n=t instanceof pe,s=n?r:t,o=n?t:null;return new NR({type:"tuple",items:e,rest:o,...V.normalizeParams(s)})}function UR(e,t,r){return!t||!t._zod?new Ai({type:"record",keyType:Wc(),valueType:e,...V.normalizeParams(t)}):new Ai({type:"record",keyType:e,valueType:t,...V.normalizeParams(r)})}function NE(e,t,r){return new Ai({type:"record",keyType:e,valueType:t,...V.normalizeParams(r),partial:!0})}function GE(e,t,r){return new Ai({type:"record",keyType:e,valueType:t,mode:"loose",...V.normalizeParams(r)})}function UE(e,t,r){return new jR({type:"map",keyType:e,valueType:t,...V.normalizeParams(r)})}function jE(e,t){return new zR({type:"set",valueType:e,...V.normalizeParams(t)})}function Np(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ti({type:"enum",entries:r,...V.normalizeParams(t)})}function zE(e,t){return new Ti({type:"enum",entries:e,...V.normalizeParams(t)})}function BE(e,t){return new BR({type:"literal",values:Array.isArray(e)?e:[e],...V.normalizeParams(t)})}function HE(e){return dw(HR,e)}function Gp(e){return new WR({type:"transform",transform:e})}function Hs(e){return new Qc({type:"optional",innerType:e})}function VR(e){return new Up({type:"optional",innerType:e})}function Vc(e){return new qR({type:"nullable",innerType:e})}function WE(e){return Hs(Vc(e))}function KR(e,t){return new ZR({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():V.shallowClone(t)}})}function YR(e,t){return new JR({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():V.shallowClone(t)}})}function QR(e,t){return new jp({type:"nonoptional",innerType:e,...V.normalizeParams(t)})}function VE(e){return new XR({type:"success",innerType:e})}function tS(e,t){return new eS({type:"catch",innerType:e,catchValue:typeof t=="function"?t:V.constantCatch(t)})}function qE(e){return uw(rS,e)}function yp(e,t){return new Xc({type:"pipe",in:e,out:t})}function ZE(e,t,r){return new eu({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function KE(e){let t=e._zod.def;return new eu({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}function oS(e){return new sS({type:"readonly",innerType:e})}function JE(e,t){return new iS({type:"template_literal",parts:e,...V.normalizeParams(t)})}function cS(e){return new aS({type:"lazy",getter:e})}function YE(e){return new uS({type:"promise",innerType:e})}function QE(e){return new lS({type:"function",input:Array.isArray(e?.input)?GR(e?.input):e?.input??Kc(Bs()),output:e?.output??Bs()})}function XE(e){let t=new Fe({check:"custom"});return t._zod.check=e,t}function eA(e,t){return pw(tu,e??(()=>!0),t)}function dS(e,t={}){return mw(tu,e,t)}function pS(e,t){return fw(e,t)}function nA(e,t={}){let r=new mS({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...V.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=n=>{n.value instanceof e||n.issues.push({code:"invalid_type",expected:e.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}function oA(e){let t=cS(()=>Di([Wc(e),vR(),kR(),AR(),Kc(t),UR(Wc(),t)]));return t}function iA(e,t){return new nS({type:"pipe",in:Gp(e),out:t})}var ge,bp,$i,Le,Kn,Jn,Yn,Qn,wp,Rp,Br,qc,Sp,_p,vp,kp,Cp,Pp,Ep,Ap,RR,Tp,$p,Op,Ip,xp,Dp,SR,_R,Lp,Vs,Oi,qs,Ii,xi,Mp,CR,PR,ER,TR,$R,OR,IR,Zc,xR,Jc,Yc,DR,LR,MR,NR,Ai,jR,zR,Ti,BR,HR,WR,Qc,Up,qR,ZR,JR,jp,XR,eS,rS,Xc,eu,nS,sS,iS,aS,uS,lS,tu,tA,rA,mS,sA,Xn=A(()=>{ar();ar();Hc();xs();zc();Cb();fp();wR();ge=$("ZodType",(e,t)=>(QU(),pe.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(V.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Oe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(dS(e,t))},superRefine(e,t){return this.check(pS(e,t))},overwrite(e){return this.check(Er(e))},optional(){return Hs(this)},exactOptional(){return VR(this)},nullable(){return Vc(this)},nullish(){return Hs(Vc(this))},nonoptional(e){return QR(this,e)},array(){return Kc(this)},or(e){return Di([this,e])},and(e){return FR(this,e)},transform(e){return yp(this,Gp(e))},default(e){return KR(this,e)},prefault(e){return YR(this,e)},catch(e){return tS(this,e)},pipe(e){return yp(this,e)},readonly(){return oS(this)},describe(e){let t=this.clone();return _t.add(t,{description:e}),t},meta(...e){if(e.length===0)return _t.get(this);let t=this.clone();return _t.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return V.hide(this,"~standard",{...ud(this),jsonSchema:{input:Ci(this,"input"),output:Ci(this,"output")}})},set"~standard"(e){V.own(this,"~standard",e)},parse:function e(t,r){return aR(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await cR(this,t,r,{callee:e})},safeParse(e,t){return uR(this,e,t)},async safeParseAsync(e,t){return lR(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){V.own(this,"spa",e)},validate(e,t){return hc(this,e,t)},validateAsync(e,t){return yc(this,e,t)},encode:function e(t,r){return dR(this,t,r,{callee:e})},decode:function e(t,r){return pR(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await mR(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await fR(this,t,r,{callee:e})},safeEncode(e,t){return gR(this,e,t)},safeDecode(e,t){return hR(this,e,t)},async safeEncodeAsync(e,t){return yR(this,e,t)},async safeDecodeAsync(e,t){return bR(this,e,t)},toJSONSchema(e){return ww(this,{})(e)},get description(){return _t.get(this)?.description},get _def(){return this._zod.def}}),bp=$("_ZodString",(e,t)=>{Ls.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>_w(e,r,n,s)},V.derived({format:e=>lt(e).format??null,minLength:e=>lt(e).minimum??null,maxLength:e=>lt(e).maximum??null},{regex(...e){return this.check(pi(...e))},includes(...e){return this.check(gi(...e))},startsWith(...e){return this.check(hi(...e))},endsWith(...e){return this.check(yi(...e))},min(...e){return this.check(mn(...e))},max(...e){return this.check(Us(...e))},length(...e){return this.check(js(...e))},nonempty(...e){return this.check(mn(1,...e))},lowercase(e){return this.check(mi(e))},uppercase(e){return this.check(fi(e))},trim(){return this.check(Si())},normalize(...e){return this.check(Ri(...e))},toLowerCase(){return this.check(_i())},toUpperCase(){return this.check(vi())},slugify(){return this.check(ki())}})),$i=$("ZodString",(e,t)=>{Ls.init(e,t),bp.init(e,t)},{email(e){return this.check(Md(wp,e))},url(e){return this.check(Mc(qc,e))},jwt(e){return this.check(rp(Lp,e))},emoji(e){return this.check(zd(Sp,e))},guid(e){return this.check(Fd(Rp,e))},uuid(e){return this.check(Nd(Br,e))},uuidv4(e){return this.check(Gd(Br,e))},uuidv6(e){return this.check(Ud(Br,e))},uuidv7(e){return this.check(jd(Br,e))},nanoid(e){return this.check(Bd(_p,e))},cuid(e){return this.check(Hd(vp,e))},cuid2(e){return this.check(Wd(kp,e))},ulid(e){return this.check(Vd(Cp,e))},base64(e){return this.check(Xd(Ip,e))},base64url(e){return this.check(ep(xp,e))},xid(e){return this.check(qd(Pp,e))},ksuid(e){return this.check(Zd(Ep,e))},ipv4(e){return this.check(Kd(Ap,e))},ipv6(e){return this.check(Jd(Tp,e))},cidrv4(e){return this.check(Yd($p,e))},cidrv6(e){return this.check(Qd(Op,e))},e164(e){return this.check(tp(Dp,e))},datetime(e){return this.check(Fc(Kn,e))},date(e){return this.check(Nc(Jn,e))},time(e){return this.check(Gc(Yn,e))},duration(e){return this.check(Uc(Qn,e))}});Le=$("ZodStringFormat",(e,t)=>{Ie.init(e,t),bp.init(e,t)}),Kn=$("ZodISODateTime",(e,t)=>{_y.init(e,t),Le.init(e,t)}),Jn=$("ZodISODate",(e,t)=>{vy.init(e,t),Le.init(e,t)}),Yn=$("ZodISOTime",(e,t)=>{ky.init(e,t),Le.init(e,t)}),Qn=$("ZodISODuration",(e,t)=>{Cy.init(e,t),Le.init(e,t)}),wp=$("ZodEmail",(e,t)=>{dy.init(e,t),Le.init(e,t)});Rp=$("ZodGUID",(e,t)=>{uy.init(e,t),Le.init(e,t)});Br=$("ZodUUID",(e,t)=>{ly.init(e,t),Le.init(e,t)});qc=$("ZodURL",(e,t)=>{fy.init(e,t),Le.init(e,t)});Sp=$("ZodEmoji",(e,t)=>{gy.init(e,t),Le.init(e,t)});_p=$("ZodNanoID",(e,t)=>{hy.init(e,t),Le.init(e,t)});vp=$("ZodCUID",(e,t)=>{yy.init(e,t),Le.init(e,t)});kp=$("ZodCUID2",(e,t)=>{by.init(e,t),Le.init(e,t)});Cp=$("ZodULID",(e,t)=>{wy.init(e,t),Le.init(e,t)});Pp=$("ZodXID",(e,t)=>{Ry.init(e,t),Le.init(e,t)});Ep=$("ZodKSUID",(e,t)=>{Sy.init(e,t),Le.init(e,t)});Ap=$("ZodIPv4",(e,t)=>{Py.init(e,t),Le.init(e,t)});RR=$("ZodMAC",(e,t)=>{Ay.init(e,t),Le.init(e,t)});Tp=$("ZodIPv6",(e,t)=>{Ey.init(e,t),Le.init(e,t)});$p=$("ZodCIDRv4",(e,t)=>{Ty.init(e,t),Le.init(e,t)});Op=$("ZodCIDRv6",(e,t)=>{$y.init(e,t),Le.init(e,t)});Ip=$("ZodBase64",(e,t)=>{Oy.init(e,t),Le.init(e,t)});xp=$("ZodBase64URL",(e,t)=>{Iy.init(e,t),Le.init(e,t)});Dp=$("ZodE164",(e,t)=>{xy.init(e,t),Le.init(e,t)});SR=$("ZodCreditCard",(e,t)=>{Dy.init(e,t),Le.init(e,t)});_R=$("ZodIBAN",(e,t)=>{Ly.init(e,t),Le.init(e,t)});Lp=$("ZodJWT",(e,t)=>{My.init(e,t),Le.init(e,t)});Vs=$("ZodCustomStringFormat",(e,t)=>{Fy.init(e,t),Le.init(e,t)});Oi=$("ZodNumber",(e,t)=>{wd.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>vw(e,r,n,s),e.isFinite=!0},V.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=lt(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=lt(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=lt(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>lt(e).format??null},{gt(e,t){return this.check(jr(e,t))},gte(e,t){return this.check(ir(e,t))},min(e,t){return this.check(ir(e,t))},lt(e,t){return this.check(Ur(e,t))},lte(e,t){return this.check(or(e,t))},max(e,t){return this.check(or(e,t))},int(e){return this.check(hp(e))},safe(e){return this.check(hp(e))},positive(e){return this.check(jr(0,e))},nonnegative(e){return this.check(ir(0,e))},negative(e){return this.check(Ur(0,e))},nonpositive(e){return this.check(or(0,e))},multipleOf(e,t){return this.check(Hn(e,t))},step(e,t){return this.check(Hn(e,t))},finite(){return this}}));qs=$("ZodNumberFormat",(e,t)=>{Ny.init(e,t),Oi.init(e,t)});Ii=$("ZodBoolean",(e,t)=>{Ec.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>kw(e,r,n,s)});xi=$("ZodBigInt",(e,t)=>{Rd.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Cw(e,r,n,s)},V.derived({minValue:e=>lt(e).minimum??null,maxValue:e=>lt(e).maximum??null,format:e=>lt(e).format??null},{gte(e,t){return this.check(ir(e,t))},min(e,t){return this.check(ir(e,t))},gt(e,t){return this.check(jr(e,t))},lt(e,t){return this.check(Ur(e,t))},lte(e,t){return this.check(or(e,t))},max(e,t){return this.check(or(e,t))},positive(e){return this.check(jr(BigInt(0),e))},negative(e){return this.check(Ur(BigInt(0),e))},nonpositive(e){return this.check(or(BigInt(0),e))},nonnegative(e){return this.check(ir(BigInt(0),e))},multipleOf(e,t){return this.check(Hn(e,t))}}));Mp=$("ZodBigIntFormat",(e,t)=>{Gy.init(e,t),xi.init(e,t)});CR=$("ZodSymbol",(e,t)=>{Uy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Pw(e,r,n,s)});PR=$("ZodUndefined",(e,t)=>{jy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Aw(e,r,n,s)});ER=$("ZodNull",(e,t)=>{zy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Ew(e,r,n,s)});TR=$("ZodAny",(e,t)=>{By.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Ow(e,r,n,s)});$R=$("ZodUnknown",(e,t)=>{Hy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Iw(e,r,n,s)});OR=$("ZodNever",(e,t)=>{Wy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>$w(e,r,n,s)});IR=$("ZodVoid",(e,t)=>{Vy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Tw(e,r,n,s)});Zc=$("ZodDate",(e,t)=>{qy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>xw(e,r,n,s),e.min=(r,n)=>e.check(ir(r,n)),e.max=(r,n)=>e.check(or(r,n))},V.derived({minDate:e=>{let{minimum:t}=lt(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=lt(e);return t?new Date(t):null}},{}));xR=$("ZodArray",(e,t)=>{Ws(),Ky.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Ww(e,r,n,s),e.element=t.element},{min(e,t){return this.check(mn(e,t))},nonempty(e){return this.check(mn(1,e))},max(e,t){return this.check(Us(e,t))},length(e,t){return this.check(js(e,t))},unwrap(){return this.element}});Jc=$("ZodObject",(e,t)=>{Ws(),Jy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Vw(e,r,n,s),V.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Np(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(V.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Bs()}))},loose(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Bs()}))},strict(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Fp()}))},strip(){return this.clone(V.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return V.extend(this,e)},safeExtend(e){return V.safeExtend(this,e)},merge(e){return V.merge(this,e)},pick(e){return V.pick(this,e)},omit(e){return V.omit(this,e)},partial(...e){return V.partial(Qc,this,e[0])},exactPartial(...e){return V.partial(Up,this,e[0],"exactPartial")},required(...e){return V.required(jp,this,e[0])}});Yc=$("ZodUnion",(e,t)=>{Ac.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>up(e,r,n,s),e.options=t.options});DR=$("ZodXor",(e,t)=>{Yc.init(e,t),Yy.init(e,t),e._zod.processJSONSchema=(r,n,s)=>up(e,r,n,s),e.options=t.options});LR=$("ZodDiscriminatedUnion",(e,t)=>{Yc.init(e,t),Xy.init(e,t)});MR=$("ZodIntersection",(e,t)=>{eb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>qw(e,r,n,s)});NR=$("ZodTuple",(e,t)=>{Ws(),Sd.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Zw(e,r,n,s)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Qc({type:"optional",innerType:t}))})}});Ai=$("ZodRecord",(e,t)=>{Ws(),tb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Kw(e,r,n,s),e.keyType=t.keyType,e.valueType=t.valueType});jR=$("ZodMap",(e,t)=>{Ws(),rb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Bw(e,r,n,s),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(zr(...r)),e.nonempty=r=>e.check(zr(1,r)),e.max=(...r)=>e.check(Wn(...r)),e.size=(...r)=>e.check(Gs(...r))});zR=$("ZodSet",(e,t)=>{Ws(),nb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Hw(e,r,n,s),e.min=(...r)=>e.check(zr(...r)),e.nonempty=r=>e.check(zr(1,r)),e.max=(...r)=>e.check(Wn(...r)),e.size=(...r)=>e.check(Gs(...r))});Ti=$("ZodEnum",(e,t)=>{sb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(n,s,o)=>Dw(e,n,s,o),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ti({...t,checks:[],...V.normalizeParams(s),entries:o})},e.exclude=(n,s)=>{let o={...t.entries};for(let i of n)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Ti({...t,checks:[],...V.normalizeParams(s),entries:o})}});BR=$("ZodLiteral",(e,t)=>{ob.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Lw(e,r,n,s),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});HR=$("ZodFile",(e,t)=>{ib.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Nw(e,r,n,s),e.min=(r,n)=>e.check(zr(r,n)),e.max=(r,n)=>e.check(Wn(r,n)),e.mime=(r,n)=>e.check(wi(Array.isArray(r)?r:[r],n))});WR=$("ZodTransform",(e,t)=>{Ws(),ab.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>zw(e,r,n,s),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new zn(e.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(V.issue(o,r.value,t));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=r.value),i.inst??(i.inst=e),r.issues.push(V.issue(i))}};let s=t.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});Qc=$("ZodOptional",(e,t)=>{_d.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>lp(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});Up=$("ZodExactOptional",(e,t)=>{cb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>lp(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});qR=$("ZodNullable",(e,t)=>{ub.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Jw(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});ZR=$("ZodDefault",(e,t)=>{lb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Xw(e,r,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});JR=$("ZodPrefault",(e,t)=>{db.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>eR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});jp=$("ZodNonOptional",(e,t)=>{pb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Yw(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});XR=$("ZodSuccess",(e,t)=>{mb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Gw(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});eS=$("ZodCatch",(e,t)=>{fb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>tR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});rS=$("ZodNaN",(e,t)=>{gb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Mw(e,r,n,s)});Xc=$("ZodPipe",(e,t)=>{vd.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>rR(e,r,n,s),e.in=t.in,e.out=t.out});eu=$("ZodCodec",(e,t)=>{Xc.init(e,t),Tc.init(e,t)});nS=$("ZodPreprocess",(e,t)=>{Xc.init(e,t),hb.init(e,t)}),sS=$("ZodReadonly",(e,t)=>{yb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>nR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});iS=$("ZodTemplateLiteral",(e,t)=>{bb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Fw(e,r,n,s)});aS=$("ZodLazy",(e,t)=>{$c.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>oR(e,r,n,s),e.unwrap=()=>e._zod.def.getter()});uS=$("ZodPromise",(e,t)=>{Rb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>sR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});lS=$("ZodFunction",(e,t)=>{wb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>jw(e,r,n,s)});tu=$("ZodCustom",(e,t)=>{Sb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Uw(e,r,n,s)});tA=gw,rA=hw,mS=$("ZodInstanceOf",(e,t)=>{tu.init(e,t)},{properties(e,t){return this.check(bi(e,t))}});sA=(...e)=>yw({Codec:eu,Boolean:Ii,String:$i},...e)});function ej(e){Ye({customError:e})}function tj(){return Ye().customError}var XU,fS,aA=A(()=>{ar();XU={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};fS||(fS={})});var ru={};re(ru,{ZodISODate:()=>Jn,ZodISODateTime:()=>Kn,ZodISODuration:()=>Qn,ZodISOTime:()=>Yn,date:()=>nj,datetime:()=>rj,duration:()=>oj,time:()=>sj});function rj(e){return Fc(Kn,e)}function nj(e){return Nc(Jn,e)}function sj(e){return Gc(Yn,e)}function oj(e){return Uc(Qn,e)}var zp=A(()=>{ar();Xn();Xn()});function aj(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function cA(e,t){return e.map((r,n)=>n<t?r:r.optional())}function cj(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function uj(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let n=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===n){let s=r[1]===void 0?void 0:cj(r[1]);if(!s||!t.defs[s])throw new Error(`Reference not found: ${e}`);return t.defs[s]}throw new Error(`Reference not found: ${e}`)}function lj(e,t){return W.transform(n=>n).check(n=>{let s=n.value;if(typeof s!="object"||s===null||Array.isArray(s))return;let o=Object.getOwnPropertyNames(s);if(t.minProperties!==void 0&&o.length<t.minProperties&&n.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:s,inst:e,continue:!0}),t.maxProperties!==void 0&&o.length>t.maxProperties&&n.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:s,inst:e,continue:!0}),t.keySchema)for(let i of o){let a=t.keySchema.safeParse(i);a.success||n.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:i,path:[i],continue:!0})}}).pipe(e)}function gS(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let n=String(e);return`${r[0]}${n.length}:${n}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let o=[];for(let i of e){let a=gS(i,t);if(a===null)return null;o.push(a)}return`a${o.length}:[${o.join(",")}]`}let n=Object.keys(e).sort(),s=[];for(let o of n){let i=gS(e[o],t);if(i===null)return null;s.push(`${o.length}:${o}=${i}`)}return`o${s.length}:{${s.join(",")}}`}finally{t.delete(e)}}function nu(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(nu):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>dj.has(t)?nu(r):!pj.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(nu))}function uA(e){return e===1?"element":"elements"}function mj(e,t){return W.transform(n=>n).check(n=>{let s=n.value;if(Array.isArray(s)){if(t.uniqueItems===!0){let o=new Map;for(let i=0;i<s.length;i++){let a=gS(s[i],new Set);if(a===null)continue;let c=o.get(a);if(c===void 0){o.set(a,i);continue}n.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${c}`,input:s,path:[i],continue:!0})}}if(t.containsSchema){let o=t.minContains??1,i=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of s)if(t.containsSchema.safeParse(c).success&&++a>=i)break;a<o&&n.issues.push({code:"custom",message:`Array must contain at least ${o} matching ${uA(o)}; found ${a}`,input:s,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&n.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${uA(t.maxContains)}`,input:s,continue:!0})}}}).pipe(e)}function lA(e,t){if(e!==!1)return e===void 0||e===!0?W.any():Nt(e,t)}function dA(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return W.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let s=e.$ref;if(t.refs.has(s))return t.refs.get(s);if(t.processing.has(s))return W.lazy(()=>{if(!t.refs.has(s))throw new Error(`Circular reference not resolved: ${s}`);return t.refs.get(s)});t.processing.add(s);let o=uj(s,t),i=Nt(o,t);return t.refs.set(s,i),t.processing.delete(s),i}if(e.enum!==void 0){let s=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&s.length===1&&s[0]===null)return W.null();if(s.length===0)return W.never();if(s.length===1)return W.literal(s[0]);if(s.every(i=>typeof i=="string"))return W.enum(s);let o=s.map(i=>W.literal(i));return o.length<2?o[0]:W.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return W.literal(e.const);let r=e.type;if(Array.isArray(r)){let s=r.map(o=>{let i={...e,type:o};return dA(i,t)});return s.length===0?W.never():s.length===1?s[0]:W.union(s)}if(!r)return W.any();let n;switch(r){case"string":{let s=W.string();if(e.format){let o=e.format;o==="email"?s=s.check(W.email()):o==="uri"||o==="uri-reference"?s=s.check(W.url()):o==="uuid"||o==="guid"?s=s.check(W.uuid()):o==="date-time"?s=s.check(W.iso.datetime({offset:!0})):o==="date"?s=s.check(W.iso.date()):o==="time"?s=s.check(W.regex(fj)):o==="duration"?s=s.check(W.iso.duration()):o==="hostname"?s=s.check(W.hostname()):o==="ipv4"?s=s.check(W.ipv4()):o==="ipv6"?s=s.check(W.ipv6()):o==="mac"?s=s.check(W.mac()):o==="cidr"?s=s.check(W.cidrv4()):o==="cidr-v6"?s=s.check(W.cidrv6()):o==="base64"?s=s.check(W.base64()):o==="base64url"?s=s.check(W.base64url()):o==="e164"?s=s.check(W.e164()):o==="credit_card"?s=s.check(W.creditCard()):o==="iban"?s=s.check(W.iban()):o==="jwt"?s=s.check(W.jwt()):o==="emoji"?s=s.check(W.emoji()):o==="nanoid"?s=s.check(W.nanoid()):o==="cuid"?s=s.check(W.cuid()):o==="cuid2"?s=s.check(W.cuid2()):o==="ulid"?s=s.check(W.ulid()):o==="xid"?s=s.check(W.xid()):o==="ksuid"&&(s=s.check(W.ksuid()))}typeof e.minLength=="number"&&(s=s.min(e.minLength)),typeof e.maxLength=="number"&&(s=s.max(e.maxLength)),e.pattern&&(s=s.regex(new RegExp(e.pattern))),n=s;break}case"number":case"integer":{let s=r==="integer"?W.number().int():W.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(s=s.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(s=s.max(e.maximum)),typeof e.exclusiveMinimum=="number"?s=s.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(s=s.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?s=s.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(s=s.lt(e.maximum)),typeof e.multipleOf=="number"&&(s=s.multipleOf(e.multipleOf)),n=s;break}case"boolean":{n=W.boolean();break}case"null":{n=W.null();break}case"object":{let s={},o=e.properties||{},i=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?Nt(e.additionalProperties,t):void 0;for(let[p,m]of Object.entries(o)){let f=Nt(m,t);St(s,p,i.has(p)?f:f.optional())}if(e.patternProperties){let p=e.patternProperties,m=Object.keys(p),f=[];for(let h of m){let b=Nt(p[h],t),w=W.string().regex(new RegExp(h));f.push(W.looseRecord(w,b))}let g=[];if(Object.keys(s).length>0&&g.push(W.object(s).passthrough()),g.push(...f),g.length===0)n=W.object({}).passthrough();else if(g.length===1)n=g[0];else{let h=W.intersection(g[0],g[1]);for(let b=2;b<g.length;b++)h=W.intersection(h,g[b]);n=h}if(e.additionalProperties===!1){let h=Object.keys(s),b=m.map(y=>new RegExp(y)),w=n;n=n.check(y=>{if(!br(y.value))return;let S=[];for(let k of Object.keys(y.value))h.includes(k)||b.some(R=>R.test(k))||S.push(k);S.length&&y.issues.push({code:"unrecognized_keys",keys:S,input:y.value,inst:w})})}}else{let p=W.object(s);e.additionalProperties===!1?n=p.strict():a?n=p.catchall(a):n=p.passthrough()}let c=e.propertyNames!==void 0&&e.propertyNames!==!0,u=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(c||u!==void 0||d!==void 0){let p;if(c){let m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=Nt(m,t)}n=lj(n,{keySchema:p,minProperties:u,maxProperties:d})}break}case"array":{let s=e.prefixItems,o=e.items;if(s&&Array.isArray(s)){let i=typeof e.minItems=="number"?e.minItems:0,a=s.map(p=>Nt(p,t)),c=cA(a,i),u=Array.isArray(o)?void 0:lA(o,t),d=W.tuple(c);n=u?d.rest(u):d,typeof e.minItems=="number"&&(n=n.check(W.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(W.maxLength(e.maxItems)))}else if(Array.isArray(o)){let i=typeof e.minItems=="number"?e.minItems:0,a=o.map(p=>Nt(p,t)),c=cA(a,i),u=lA(e.additionalItems,t),d=W.tuple(c);n=u?d.rest(u):d,typeof e.minItems=="number"&&(n=n.check(W.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(W.maxLength(e.maxItems)))}else if(o!==void 0){let i=Nt(o,t),a=W.array(i);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),n=a}else n=W.array(W.any());(e.uniqueItems===!0||e.contains!==void 0)&&(n=mj(n,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?Nt(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return n}function Nt(e,t){if(typeof e=="boolean")return e?W.any():W.never();let r=dA(e,t),n=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(u=>Nt(u,t)),c=W.union(a);r=n?W.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(u=>Nt(u,t)),c=W.xor(a);r=n?W.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=n?r:W.any();else{let a=n?r:Nt(e.allOf[0],t),c=n?0:1;for(let u=c;u<e.allOf.length;u++)a=W.intersection(a,Nt(e.allOf[u],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=W.nullable(r)),e.readOnly===!0&&(r=W.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let s={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of o)a in e&&(s[a]=e[a]);let i=["contentEncoding","contentMediaType","contentSchema"];for(let a of i)a in e&&(s[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!nu(e.propertyNames)&&(s.propertyNames=e.propertyNames);for(let a of["minProperties","maxProperties"])e[a]!==void 0&&(s[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!nu(e.contains)&&(s.contains=e.contains);for(let a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(s[a]=e[a])}for(let a of Object.keys(e))ij.has(a)||St(s,a,e[a]);return Object.keys(s).length>0&&t.registry.add(r,s),e.description&&(r=r.describe(e.description)),r}function pA(e,t){if(typeof e=="boolean")return e?W.any():W.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let n=aj(r,t?.defaultTarget),s=r.$defs||r.definitions||{},o={version:n,defs:s,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??_t};return Nt(r,o)}var W,ij,dj,pj,fj,mA=A(()=>{Lc();rt();fp();zp();Xn();W={...Li,...mp,iso:ru},ij=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);dj=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),pj=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);fj=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/});function su(e,t){let r=typeof t=="function"?t:(i,a)=>{let c=t[i._zod.def.type];return c?c(i,a):i},n=new Map;function s(i){let a=n.get(i);if(a===fA)return new $c({type:"lazy",getter:()=>n.get(i)});if(a!==void 0)return a;n.set(i,fA);let c=o(i),u=r(c,c!==i);return n.set(i,u),u}function o(i){let a=i._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,d=Object.keys(u),p=!1,m={};for(let g of d){let h=s(u[g]);h!==u[g]&&(p=!0),m[g]=h}let f=a.catchall;return a.catchall&&(f=s(a.catchall),f!==a.catchall&&(p=!0)),p?Oe(i,{...a,shape:m,catchall:f}):i}case"array":{let u=s(a.element);return u===a.element?i:Oe(i,{...a,element:u})}case"tuple":{let u=a.items,d=!1,p=[];for(let f of u){let g=s(f);g!==f&&(d=!0),p.push(g)}let m=a.rest;return a.rest&&(m=s(a.rest),m!==a.rest&&(d=!0)),d?Oe(i,{...a,items:p,rest:m}):i}case"record":case"map":{let u=s(a.keyType),d=s(a.valueType);return u===a.keyType&&d===a.valueType?i:Oe(i,{...a,keyType:u,valueType:d})}case"set":{let u=s(a.valueType);return u===a.valueType?i:Oe(i,{...a,valueType:u})}case"union":{let u=a.options,d=!1,p=[];for(let m of u){let f=s(m);f!==m&&(d=!0),p.push(f)}return d?Oe(i,{...a,options:p}):i}case"intersection":{let u=s(a.left),d=s(a.right);return u===a.left&&d===a.right?i:Oe(i,{...a,left:u,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=s(a.innerType);return u===a.innerType?i:Oe(i,{...a,innerType:u})}case"pipe":{let u=s(a.in),d=s(a.out);return u===a.in&&d===a.out?i:Oe(i,{...a,in:u,out:d})}case"function":{let u=s(a.input),d=s(a.output);return u===a.input&&d===a.output?i:Oe(i,{...a,input:u,output:d})}case"lazy":{let u=a.getter,{_cachedInner:d,...p}=a;return Oe(i,{...p,getter:()=>s(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return i;default:return i}}return s(e)}var fA,hS=A(()=>{ui();rt();fA=Symbol("z.visit/resolving")});function gA(e){return su(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:Di(r.options)}})}var hA=A(()=>{hS();Xn()});function gj(e,t){if(!t?.length)return e;let r=e._zod.def;return Oe(e,Cr(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function yA(e){return gj(e.out,e.checks)}function hj(e){return e.in._zod.traits.has("$ZodTransform")?yA(e):e.in}function bA(e){return su(e,{pipe:t=>hj(t._zod.def),default:(t,r)=>r?Hs(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function wA(e){return su(e,{pipe:t=>yA(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var RA=A(()=>{rt();hS();Xn()});var yS={};re(yS,{bigint:()=>Rj,boolean:()=>wj,date:()=>Sj,number:()=>bj,string:()=>yj});function yj(e){return Mb($i,e)}function bj(e){return zb(Oi,e)}function wj(e){return Kb(Ii,e)}function Rj(e){return Yb(xi,e)}function Sj(e){return cw(Zc,e)}var SA=A(()=>{ar();Xn()});var l={};re(l,{$brand:()=>Jg,$input:()=>Ab,$output:()=>Eb,INVALID:()=>Mt,NEVER:()=>Kg,TimePrecision:()=>Ub,ZodAny:()=>TR,ZodArray:()=>xR,ZodBase64:()=>Ip,ZodBase64URL:()=>xp,ZodBigInt:()=>xi,ZodBigIntFormat:()=>Mp,ZodBoolean:()=>Ii,ZodCIDRv4:()=>$p,ZodCIDRv6:()=>Op,ZodCUID:()=>vp,ZodCUID2:()=>kp,ZodCatch:()=>eS,ZodCodec:()=>eu,ZodCompileAsyncError:()=>Pr,ZodCompileUnsupportedError:()=>Se,ZodCreditCard:()=>SR,ZodCustom:()=>tu,ZodCustomStringFormat:()=>Vs,ZodDate:()=>Zc,ZodDefault:()=>ZR,ZodDiscriminatedUnion:()=>LR,ZodE164:()=>Dp,ZodEmail:()=>wp,ZodEmoji:()=>Sp,ZodEnum:()=>Ti,ZodError:()=>JU,ZodExactOptional:()=>Up,ZodFile:()=>HR,ZodFirstPartyTypeKind:()=>fS,ZodFunction:()=>lS,ZodGUID:()=>Rp,ZodIBAN:()=>_R,ZodIPv4:()=>Ap,ZodIPv6:()=>Tp,ZodISODate:()=>Jn,ZodISODateTime:()=>Kn,ZodISODuration:()=>Qn,ZodISOTime:()=>Yn,ZodInstanceOf:()=>mS,ZodIntersection:()=>MR,ZodIssueCode:()=>XU,ZodJWT:()=>Lp,ZodKSUID:()=>Ep,ZodLazy:()=>aS,ZodLiteral:()=>BR,ZodMAC:()=>RR,ZodMap:()=>jR,ZodNaN:()=>rS,ZodNanoID:()=>_p,ZodNever:()=>OR,ZodNonOptional:()=>jp,ZodNull:()=>ER,ZodNullable:()=>qR,ZodNumber:()=>Oi,ZodNumberFormat:()=>qs,ZodObject:()=>Jc,ZodOptional:()=>Qc,ZodPipe:()=>Xc,ZodPrefault:()=>JR,ZodPreprocess:()=>nS,ZodPromise:()=>uS,ZodReadonly:()=>sS,ZodRealError:()=>Jt,ZodRecord:()=>Ai,ZodSet:()=>zR,ZodString:()=>$i,ZodStringFormat:()=>Le,ZodSuccess:()=>XR,ZodSymbol:()=>CR,ZodTemplateLiteral:()=>iS,ZodTransform:()=>WR,ZodTuple:()=>NR,ZodType:()=>ge,ZodULID:()=>Cp,ZodURL:()=>qc,ZodUUID:()=>Br,ZodUndefined:()=>PR,ZodUnion:()=>Yc,ZodUnknown:()=>$R,ZodVoid:()=>IR,ZodXID:()=>Pp,ZodXor:()=>DR,_ZodString:()=>bp,_default:()=>KR,_function:()=>QE,any:()=>TE,array:()=>Kc,base64:()=>uE,base64url:()=>lE,bigint:()=>kE,boolean:()=>kR,catch:()=>tS,check:()=>XE,cidrv4:()=>aE,cidrv6:()=>cE,clone:()=>Oe,codec:()=>ZE,coerce:()=>yS,compile:()=>Ib,config:()=>Ye,core:()=>fn,creditCard:()=>pE,cuid:()=>XP,cuid2:()=>eE,currencyCode:()=>bE,custom:()=>eA,date:()=>OE,decode:()=>pR,decodeAsync:()=>fR,deepPartial:()=>gA,describe:()=>tA,discriminatedUnion:()=>FE,e164:()=>dE,email:()=>BP,emoji:()=>YP,encode:()=>dR,encodeAsync:()=>mR,endsWith:()=>yi,enum:()=>Np,exactOptional:()=>VR,file:()=>HE,flattenError:()=>fc,float32:()=>RE,float64:()=>SE,formatError:()=>gc,fromJSONSchema:()=>pA,function:()=>QE,getDiscriminatedOption:()=>Qy,getErrorMap:()=>tj,globalRegistry:()=>_t,gt:()=>jr,gte:()=>ir,guid:()=>HP,hash:()=>wE,hex:()=>yE,hostname:()=>hE,httpUrl:()=>JP,iban:()=>mE,includes:()=>gi,input:()=>bA,instanceof:()=>nA,int:()=>hp,int32:()=>_E,int64:()=>CE,intersection:()=>FR,invertCodec:()=>KE,ipv4:()=>sE,ipv6:()=>iE,iso:()=>ru,json:()=>oA,jwt:()=>fE,keyof:()=>IE,ksuid:()=>nE,lazy:()=>cS,length:()=>js,literal:()=>BE,locales:()=>Dc,looseObject:()=>LE,looseRecord:()=>GE,lowercase:()=>mi,lt:()=>Ur,lte:()=>or,mac:()=>oE,map:()=>UE,maxLength:()=>Us,maxSize:()=>Wn,memoizer:()=>xc,meta:()=>rA,mime:()=>wi,minLength:()=>mn,minSize:()=>zr,multipleOf:()=>Hn,nan:()=>qE,nanoid:()=>QP,nativeEnum:()=>zE,negative:()=>sp,never:()=>Fp,nonnegative:()=>ip,nonoptional:()=>QR,nonpositive:()=>op,normalize:()=>Ri,null:()=>AR,nullable:()=>Vc,nullish:()=>WE,number:()=>vR,object:()=>xE,optional:()=>Hs,output:()=>wA,overwrite:()=>Er,parse:()=>aR,parseAsync:()=>cR,partialRecord:()=>NE,pipe:()=>yp,positive:()=>np,prefault:()=>YR,preprocess:()=>iA,prettifyError:()=>th,promise:()=>YE,properties:()=>bi,property:()=>ap,readonly:()=>oS,record:()=>UR,refine:()=>dS,regex:()=>pi,regexes:()=>Rr,registry:()=>Id,safeDecode:()=>hR,safeDecodeAsync:()=>bR,safeEncode:()=>gR,safeEncodeAsync:()=>yR,safeParse:()=>uR,safeParseAsync:()=>lR,set:()=>jE,setErrorMap:()=>ej,size:()=>Gs,slugify:()=>ki,startsWith:()=>hi,strictObject:()=>DE,string:()=>Wc,stringFormat:()=>gE,stringbool:()=>sA,success:()=>VE,superRefine:()=>pS,symbol:()=>EE,templateLiteral:()=>JE,toJSONSchema:()=>dp,toLowerCase:()=>_i,toUpperCase:()=>vi,toZod:()=>sc,transform:()=>Gp,treeifyError:()=>eh,trim:()=>Si,tuple:()=>GR,uint32:()=>vE,uint64:()=>PE,ulid:()=>tE,undefined:()=>AE,union:()=>Di,unknown:()=>Bs,uppercase:()=>fi,url:()=>KP,util:()=>V,uuid:()=>WP,uuidv4:()=>VP,uuidv6:()=>qP,uuidv7:()=>ZP,validate:()=>hc,validateAsync:()=>yc,void:()=>$E,withParser:()=>xd,xid:()=>rE,xor:()=>ME});var bS=A(()=>{ar();Xn();fp();iR();wR();aA();ar();Hc();mA();hA();RA();Pb();zp();zp();SA()});var ou=A(()=>{bS();bS()});function kA({author:e,comments:t}){let r=t.filter(n=>!n.isBot&&n.author===e).map(n=>n.body);return r.some(n=>Cj.some(s=>s.test(n)))?"superseded":r.some(n=>Pj.test(n))?"no-traction":t.some(n=>!n.isBot&&n.author!==e)?"after-feedback":"no-response"}function CA({author:e,closer:t,closerIsBot:r,comments:n}){let s=n.filter(o=>!o.isBot&&o.author!==e).map(o=>o.body);return s.some(o=>_j.test(o))?"ai-policy":s.some(o=>vj.test(o))?"superseded":r||s.some(o=>kj.test(o))?"stale":t?t===e?"self-closed":"rejected":"unknown"}var _A,vA,_j,vj,kj,Cj,Pj,wS=A(()=>{"use strict";_A=["ai-policy","superseded","stale","self-closed","rejected","unknown"],vA=["superseded","no-traction","after-feedback","no-response"],_j=/\b(?:AI|LLM)[- ](?:generated|written|authored|slop|polic(?:y|ies))|(?:generated|written) (?:by|with) (?:an? )?(?:AI|LLM|ChatGPT|Copilot)\b|vibe[- ]?cod|machine[- ]generated/i,vj=/clos(?:e|ing) (?:this )?as (?:a )?duplicate|duplicate of #\d+|superseded by|already (?:been )?(?:fixed|merged|addressed|resolved|implemented)|fixed (?:in|by|via) #\d+|in favou?r of #\d+/i,kj=/marked as stale|clos(?:e|ing) (?:this )?(?:as|due to) (?:stale|inactiv)|no activity (?:for|in)/i,Cj=[/already (?:been )?(?:fixed|merged|addressed|resolved|implemented|landed|applied|several)/i,/cover(?:s|ed) (?:this|everything|the same)|same (?:one-line )?fix|(?:landed|fixed|ships?) the same/i,/has (?:landed|shipped)|is in and|(?:fixed|addressed|resolved|landed|applied) (?:upstream|elsewhere)/i,/upstream (?:upgrade|commit|fix)|supersed|in favou?r of|replaced by|duplicate/i,/no longer (?:needed|relevant|reproduc|applies)/i],Pj=/traction|(?:been )?quiet|unmaintained|actively (?:reviewing|maintained)|not maintained|no (?:response|activity)|keep the queue tidy|sitting in (?:your|the) queue|stale/i});function Mi(e){return l.custom(t=>typeof t=="string")}function Hj(e){let t=e?.openPRs;return!Array.isArray(t)||t.length===0?e:{...e,needsAddressingPRs:t.filter(r=>r?.status==="needs_addressing"),waitingOnMaintainerPRs:t.filter(r=>r?.status==="waiting_on_maintainer")}}function TA(e,t){let r=e!==null&&typeof e=="object"?e.workClaims:void 0;return Array.isArray(r)?Math.max(0,r.length-t.workClaims.length):0}function Hp(e){if(!e||typeof e!="object")return[];let t=new Set(Object.keys(Gt.shape));return Object.keys(e).filter(r=>!t.has(r))}var Ej,SS,_S,vS,kS,Aj,Tj,EA,AA,$j,Oj,Ij,xj,Dj,Lj,Mj,Fj,PA,Nj,Bp,Gj,Uj,jj,zj,Bj,RS,Wj,Vj,qj,Zj,Kj,CS,PS,Zs,Jj,Gt,Wp,gn=A(()=>{"use strict";ou();wS();Ej=l.enum(["candidate","claimed","in_progress","pr_submitted"]),SS=l.enum(["needs_addressing","waiting_on_maintainer"]),_S=l.enum(["nonprofit","devtools","infrastructure","web-frameworks","data-ml","education"]),vS=l.enum(["beginner","intermediate","advanced"]),kS=l.enum(["inline","sourcetree","vscode","custom"]),Aj=l.object({hasActiveMaintainers:l.boolean(),isResponsive:l.boolean(),hasHostileComments:l.boolean()}),Tj=l.object({repo:l.string(),score:l.number(),mergedPRCount:l.number(),closedWithoutMergeCount:l.number(),avgResponseDays:l.number().nullable(),lastMergedAt:l.string().optional(),lastEvaluatedAt:l.string(),signals:Aj,stargazersCount:l.number().optional(),language:l.string().nullable().optional()}).passthrough(),EA=l.object({issueUrl:l.string(),grade:l.number(),recommendation:l.string(),stargazersCount:l.number().optional(),source:Mi(["vet","vet-list","list"]),capturedAt:l.string().optional(),labels:l.array(l.string()).optional(),issueAuthorAssociation:Mi(["OWNER","MEMBER","COLLABORATOR","CONTRIBUTOR","FIRST_TIMER","FIRST_TIME_CONTRIBUTOR","MANNEQUIN","NONE"]).optional(),issueAuthorIsBot:l.boolean().optional(),competingPRs:l.number().optional(),mentioningPRs:l.number().optional(),firstInRepo:l.boolean().optional(),commentCount:l.number().optional()}).passthrough(),AA={issueUrl:l.string().optional(),pick:EA.optional(),lastReviewDecision:l.string().optional(),lastCiStatus:l.string().optional(),backfilledAt:l.string().optional(),responseRule:l.number().int().optional()},$j=l.object({url:l.string(),title:l.string(),mergedAt:l.string(),openedAt:l.string().optional(),firstMaintainerResponseAt:l.string().optional(),commentsFetchedAt:l.string().datetime().optional(),learningsExtractedAt:l.string().datetime().optional(),...AA}).passthrough(),Oj=l.object({url:l.string(),title:l.string(),closedAt:l.string(),openedAt:l.string().optional(),firstMaintainerResponseAt:l.string().optional(),commentsFetchedAt:l.string().datetime().optional(),learningsExtractedAt:l.string().datetime().optional(),...AA,closeReason:Mi(_A).optional(),selfCloseReason:Mi(vA).optional()}).passthrough(),Ij=l.object({url:l.string(),repo:l.string(),analyzedAt:l.string()}),xj=l.object({tier:l.enum(["light_check_in","direct_check_in","final_check_in"]),timestamp:l.string().datetime(),draftPath:l.string().optional()}),Dj=l.object({workflowName:l.enum(["draft-first","work-through-issues","pre-commit-review"]),currentStep:l.string(),branchName:l.string().optional(),issueContext:l.object({title:l.string(),url:l.string()}).optional(),completedSteps:l.array(l.string()).default([]),stepData:l.record(l.string(),l.unknown()).default({}),lastUpdatedAt:l.string().datetime()}),Lj=l.object({branchNamingConvention:l.string().optional(),commitMessageFormat:l.string().optional(),prTitleFormat:l.string().optional(),requiredChecks:l.array(l.string()).optional(),testFramework:l.string().optional(),testCoverageRequired:l.boolean().optional(),testFileNaming:l.string().optional(),linter:l.string().optional(),formatter:l.string().optional(),styleGuideUrl:l.string().optional(),issueClaimProcess:l.string().optional(),reviewProcess:l.string().optional(),claRequired:l.boolean().optional(),rawContent:l.string().optional()}),Mj=l.object({passedAllChecks:l.boolean(),checks:l.object({noExistingPR:l.boolean(),notClaimed:l.boolean(),projectActive:l.boolean(),clearRequirements:l.boolean(),contributionGuidelinesFound:l.boolean()}),contributionGuidelines:Lj.optional(),notes:l.array(l.string())}),Fj=l.object({id:l.number(),url:l.string(),repo:l.string(),number:l.number(),title:l.string(),status:Ej,labels:l.array(l.string()),createdAt:l.string(),updatedAt:l.string(),vetted:l.boolean(),vettingResult:Mj.optional()}),PA=l.object({number:l.number(),url:l.string(),title:l.string(),repo:l.string(),daysSinceActivity:l.number(),status:SS}),Nj=l.object({status:SS,setAt:l.string(),lastActivityAt:l.string()}),Bp=l.object({setupComplete:l.boolean().default(!1),setupCompletedAt:l.string().optional(),persistence:l.enum(["local","gist"]).default("local"),maxActivePRs:l.number().default(10),maxOpenPRsPerRepo:l.number().int().min(0).default(0),maxOpenPRsColdRepo:l.number().int().min(0).default(1),maxConcurrentImplementations:l.number().int().min(0).default(2),dormantThresholdDays:l.number().default(30),approachingDormantDays:l.number().default(25),maxIssueAgeDays:l.number().default(90),skipBroadWhenSufficientResults:l.number().min(0).default(8),languages:l.array(l.string()).default(["typescript","javascript"]),labels:l.array(l.string()).default(["good first issue","help wanted"]),scope:l.array(vS).optional(),excludeRepos:l.array(l.string()).default([]),excludeOrgs:l.array(l.string()).optional(),untrackedOrgs:l.array(l.string()).default([]),avoidRepos:l.array(l.string()).default([]),boostIssueTypes:l.array(l.string()).default([]),trustedProjects:l.array(l.string()).default([]),githubUsername:l.string().default(""),minRepoScoreThreshold:l.number().default(4),starredRepos:l.array(l.string()).default([]),starredReposLastFetched:l.string().optional(),squashByDefault:l.union([l.boolean(),l.literal("ask")]).default(!0),localRepoScanPaths:l.array(l.string()).optional(),minStars:l.number().default(50),includeDocIssues:l.boolean().default(!0),aiPolicyBlocklist:l.array(l.string()).default(["matplotlib/matplotlib"]),shelvedPRUrls:l.array(l.string()).default([]),dismissedIssues:l.record(l.string(),l.string()).default({}),dismissedPRHeads:l.record(l.string(),l.string()).default({}),statusOverrides:l.record(l.string(),Nj).optional(),issueListPath:l.string().optional(),skippedIssuesPath:l.string().optional(),projectCategories:l.array(_S).default([]),preferredOrgs:l.array(l.string()).default([]),diffTool:kS.default("inline"),diffToolCustomCommand:l.string().optional(),autoExtractLearnings:l.boolean().default(!0),autoFormatBeforePush:l.boolean().default(!1),trustOwnRepoWrites:l.boolean().default(!1),healthCheckFreshnessMinutes:l.number().int().positive().default(30),reviewMaxPasses:l.number().int().positive().optional(),slmTriageModel:l.string().default(""),slmTriageHost:l.string().default("")}).passthrough().transform(({snoozedPRs:e,...t})=>t),Gj=l.object({repos:l.record(l.string(),l.object({path:l.string(),exists:l.boolean(),currentBranch:l.string().nullable()})),scanPaths:l.array(l.string()),cachedAt:l.string()}),Uj=l.object({url:l.string(),repo:l.string(),number:l.number(),title:l.string(),closedAt:l.string(),closedBy:l.string().optional(),openedAt:l.string().optional(),issueUrl:l.string().optional()}),jj=l.object({url:l.string(),repo:l.string(),number:l.number(),title:l.string(),mergedAt:l.string(),openedAt:l.string().optional(),issueUrl:l.string().optional()}),zj=l.object({totalActivePRs:l.number(),totalNeedingAttention:l.number(),totalMergedAllTime:l.number(),mergeRate:l.number()}),Bj=l.object({url:l.string(),repo:l.string(),number:l.number(),status:SS}).passthrough(),RS=l.array(Bj);Wj=l.object({generatedAt:l.string(),openPRs:RS,needsAddressingPRs:RS,waitingOnMaintainerPRs:RS,recentlyClosedPRs:l.array(Uj),recentlyMergedPRs:l.array(jj),shelvedPRs:l.array(PA),autoUnshelvedPRs:l.array(PA),summary:zj}),Vj=l.preprocess(Hj,Wj),qj=l.object({url:l.string(),lastSeenAt:l.string()}),Zj=l.object({url:l.string(),branch:l.string(),worktree:l.string().optional(),note:l.string().optional(),recordedAt:l.string(),pushedRef:l.string().optional(),pushedAt:l.string().optional(),compareUrl:l.string().optional(),pushProblem:l.string().optional()}).passthrough(),Kj=l.object({url:l.string(),attemptedAt:l.string(),outcome:l.enum(["prepared","blocked"]),note:l.string().optional()}).passthrough(),CS=l.object({runAt:l.string(),reportPath:l.string(),prepareCount:l.number().int().nonnegative(),judgmentCount:l.number().int().nonnegative(),prepared:l.array(Zj).default([]),implementUrl:l.string().optional(),implementAttempts:l.array(Kj).optional()}).passthrough(),PS=l.object({languageOffset:l.number().int().nonnegative().default(0),phase0Offset:l.number().int().nonnegative().default(0),starredOffset:l.number().int().nonnegative().default(0),maintainedOffset:l.number().int().nonnegative().default(0),strategyOffset:l.number().int().nonnegative().default(0),lastRotatedAt:l.string().optional()}).passthrough(),Zs=l.object({kind:Mi(["implementation","pr"]),url:l.string(),session:l.string(),startedAt:l.string(),expiresAt:l.string(),status:Mi(["running","finished"]),branch:l.string().optional(),worktree:l.string().optional(),host:l.string().optional(),machineId:l.string().optional(),runId:l.string().optional(),finishedAt:l.string().optional()}).loose(),Jj=l.array(l.unknown()).default([]).transform(e=>e.flatMap(t=>{let r=Zs.safeParse(t);return r.success?[r.data]:[]}));Gt=l.object({version:l.literal(4),gistId:l.string().optional(),repoScores:l.record(l.string(),Tj).default({}),config:Bp.default(()=>Bp.parse({})),lastRunAt:l.string().default(()=>new Date().toISOString()),lastDigestAt:l.string().optional(),lastStrategyAt:l.string().optional(),lastDigest:Vj.optional(),monthlyMergedCounts:l.record(l.string(),l.number()).optional(),monthlyClosedCounts:l.record(l.string(),l.number()).optional(),monthlyOpenedCounts:l.record(l.string(),l.number()).optional(),localRepoCache:Gj.optional(),mergedPRs:l.array($j).optional(),closedPRs:l.array(Oj).optional(),analyzedIssueConversations:l.array(Ij).optional(),activeIssues:l.array(Fj).default([]),prFollowUpHistory:l.record(l.string(),l.array(xj)).optional(),workflowState:Dj.optional(),searchSeen:l.array(qj).default([]),pickSnapshots:l.array(EA).default([]),lastOvernight:CS.optional(),searchRotation:PS.optional(),workClaims:Jj}).passthrough();Wp="was written by a different oss-autopilot release (usually a newer one); this version keeps those fields but cannot use them. If you are not on the latest release, update with `claude plugin update oss-autopilot@oss-autopilot` and restart Claude Code."});function ES(e,t){return Yj.test(e)&&Qj.test(t)}function q(e){if(!e.startsWith("https://github.com/"))return null;let t=e.match(/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/);if(t){let n=t[1],s=t[2];return ES(n,s)?{owner:n,repo:s,number:parseInt(t[3],10),type:"pull"}:null}let r=e.match(/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+)/);if(r){let n=r[1],s=r[2];return ES(n,s)?{owner:n,repo:s,number:parseInt(r[3],10),type:"issues"}:null}return null}function We(e){let t=q(e);return t?`${t.owner.toLowerCase()}/${t.repo.toLowerCase()}#${t.number}`:null}function Hr(e){if(!e.startsWith("https://github.com/"))return null;let t=e.match(/github\.com\/([^/]+)\/([^/]+)/);if(!t)return null;let r=t[1],n=t[2];return ES(r,n)?{owner:r,repo:n}:null}function Ks(e){let[t,r]=e.split("/",2);if(!t||!r)throw new Error(`Invalid repo format: expected "owner/repo", got "${e}"`);return{owner:t,repo:r}}function Sr(e,t){return e.toLowerCase()===t.toLowerCase()}function Fi(e,t=[]){let r=e.toLowerCase();return t.some(n=>n.toLowerCase()===r)}var Yj,Qj,nt=A(()=>{"use strict";Yj=/^[\w-]+$/,Qj=/^[\w.-]+$/});function Yt(e){return We(e)??e.trim().toLowerCase()}function AS(e,t=Date.now()){let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&r>t}function cr(e,t=Date.now()){return e.filter(r=>AS(r,t))}function Js(e,t,r=Date.now()){let n=Yt(t);return cr(e,r).find(s=>Yt(s.url)===n)}function qp(e,t,r,n=Date.now()){let s=Js(e,t,n);if(!(s===void 0||s.session===r))return s}function Zp(e,t){let r=new Date(Date.parse(t)+au*36e5),n=Date.parse(e.expiresAt),s=Number.isFinite(n)&&n>r.getTime()?e.expiresAt:r.toISOString();return{...e,status:"finished",finishedAt:t,expiresAt:s}}function Kp(e,t=Date.now()){return cr(e,t).filter(r=>r.kind==="implementation"&&r.status==="finished")}function xA(e,t=Date.now()){return cr(e,t).filter(r=>r.kind==="implementation"&&r.status==="running")}function Ni(e){return IA.default.resolve(e.trim())}function Xj(e,t){return e===void 0||t===void 0||e===t}function $A(e){try{return OA.realpathSync(e)}catch{return e}}function ez(e,t,r){if(!e.worktree)return!1;let n=Ni(e.worktree);return e.machineId!==void 0&&r.machineId!==void 0?e.machineId!==r.machineId?!1:$A(n)===$A(t):Xj(e.host,r.host)&&n===t}function Jp(e,t,r,n=Date.now()){let s=Yt(t.url),o=cr(e,n).filter(a=>a.kind==="implementation"&&Yt(a.url)!==s);if(t.worktree!==void 0){let a=Ni(t.worktree),c=o.filter(u=>ez(u,a,t));if(c.length>0){let u=c[0];return{reason:"worktree",blocking:c,message:`Checkout ${a} already hosts an implementation of ${u.url} (session ${u.session}, ${u.status}). Use a separate worktree, or finish or release that claim first.`}}}let i=o.filter(a=>a.status==="running");if(r>0&&i.length>=r){let a=i.map(c=>`${c.url} (session ${c.session})`).join(", ");return{reason:"cap",blocking:i,message:`Implementation cap reached: ${i.length} of ${r} running (${a}). Collect or release one, or raise it with \`setup --set maxConcurrentImplementations=N\`.`}}return null}function TS(e,t=Date.now()){let r=Date.parse(e.startedAt),n=Number.isFinite(r)?Math.max(0,Math.floor((t-r)/6e4)):0;return n<60?`${n} min`:n<1440?`${Math.floor(n/60)} h`:`${Math.floor(n/1440)} d`}function cu(e,t=Date.now()){return`${e.kind} claimed in session ${e.session} (${TS(e,t)}, ${e.status})`}function Gi(e,t,r=Date.now()){let n=Js(e,t,r);return!n||n.kind!=="implementation"?null:{recommendation:"skip",reasonsToSkip:[`Already being implemented: ${cu(n,r)}`],workClaim:n}}var OA,IA,Vp,iu,au,$S=A(()=>{"use strict";OA=B(require("node:fs"),1),IA=B(require("node:path"),1);nt();Vp={implementation:24,pr:12},iu=168,au=168});function rz(e){let t=e.lastDigest,r=[...t?.openPRs??[],...t?.shelvedPRs??[],...e.activeIssues].map(i=>i.repo),s=[...(e.mergedPRs??[]).map(i=>i.url),...(e.closedPRs??[]).map(i=>i.url),...e.config.shelvedPRUrls??[]].flatMap(i=>{let a=q(i);return a?[`${a.owner}/${a.repo}`]:[]}),o=new Set(r);for(let i of s)o.add(i);return o}function nz(e,t=Date.now()){let r=t-uu*DA,n=e.searchSeen.filter(c=>Date.parse(c.lastSeenAt)>=r),s=t-tz*DA,o=rz(e),i=Object.fromEntries(Object.entries(e.repoScores).filter(([c,u])=>{let d=u.mergedPRCount>0||u.closedWithoutMergeCount>0,p=Date.parse(u.lastEvaluatedAt),m=Number.isNaN(p)||p>=s;return d||o.has(c)||m})),a=e.lastDigest&&{...e.lastDigest,needsAddressingPRs:[],waitingOnMaintainerPRs:[]};return{...e,searchSeen:n,repoScores:i,lastDigest:a}}function Ar(e){return JSON.stringify(nz(e))}var DA,OS,uu,tz,Ui=A(()=>{"use strict";nt();DA=1440*60*1e3,OS=7,uu=OS+1,tz=14});function sz(){try{return Yp.userInfo().homedir}catch{return null}}function Qp(){let e=Yp.homedir(),t=process.env.VITEST?sz():null;if(t!==null&&yt.resolve(e)===yt.resolve(t))throw new Error(`Refusing to use the real home directory (${e}) under vitest`);return yt.join(e,".oss-autopilot")}function ur(){let e=Qp();return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function jt(){return yt.join(ur(),"state.json")}function LA(){return yt.join(process.cwd(),"data","state.json")}function MA(){return yt.join(process.cwd(),"data","backups")}function Ys(){let e=yt.join(ur(),"backups");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function Xp(){let e=yt.join(ur(),"cache");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function ji(){let e=yt.join(ur(),"reports");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function Qs(){return yt.join(ur(),"gist-id")}function FA(){return yt.join(ur(),"machine-id")}function es(){return yt.join(ur(),"state-cache.json")}function em(){return Ut.existsSync(yt.join(Qp(),"state.json"))}function Wr(){return"3.40.1"}var Ut,yt,Yp,Vr=A(()=>{"use strict";Ut=B(require("node:fs"),1),yt=B(require("node:path"),1),Yp=B(require("node:os"),1)});function rm(){tm=!0}function NA(){return tm}function O(e,t,...r){if(!tm)return;let n=new Date().toISOString();console.error(`[${n}] [DEBUG] [${e}] ${t}`,...r)}function GA(e,t,...r){let n=new Date().toISOString();console.error(`[${n}] [INFO] [${e}] ${t}`,...r)}function v(e,t,...r){let n=new Date().toISOString();console.error(`[${n}] [WARN] [${e}] ${t}`,...r)}async function nm(e,t,r){if(!tm)return r();let n=performance.now();try{let s=await r(),o=(performance.now()-n).toFixed(0);return O(e,`${t} completed in ${o}ms`),s}catch(s){let o=(performance.now()-n).toFixed(0);throw O(e,`${t} failed after ${o}ms`),s}}var tm,ce=A(()=>{"use strict";tm=!1});function du(e){if(process.env[sm]!==void 0)throw new Te(`Refusing to ${e} during an unattended run (${sm} is set). Run it yourself in an interactive session.`)}function I(e){return e instanceof Error?e.message:String(e)}function Ue(e){if(e&&typeof e=="object"&&"status"in e){let t=e.status;return typeof t=="number"&&Number.isFinite(t)?t:void 0}}function hn(e){let t=Ue(e);return t===void 0?void 0:`HTTP ${t}`}function Xt(e){let t=hn(e);return t?`${t}: ${I(e)}`:I(e)}function zt(e){let t=Ue(e);return t===429?!0:t===403?I(e).toLowerCase().includes("rate limit"):!1}function UA(e){if(Ue(e)!==422)return!1;let t=e?.response?.data,r=t&&typeof t=="object"?t.errors:void 0;return Array.isArray(r)?r.some(n=>{if(!n||typeof n!="object")return!1;let s=n;return s.resource!=="Search"||s.code!=="invalid"?!1:typeof s.message=="string"?IS.test(s.message):IS.test(I(e))}):IS.test(I(e))}function de(e){let t=Ue(e);if(t===401||t===429)return!0;if(t===403){let r=I(e).toLowerCase();return r.includes("rate limit")||r.includes("abuse detection")}return!1}function im(e){if(!e||typeof e!="object")return!1;let t=Ue(e);if(typeof t=="number"&&t>=500&&t<600)return!0;let r=e.code;if(typeof r=="string"&&(r==="ECONNRESET"||r==="ETIMEDOUT"||r==="ENETUNREACH"||r==="ENOTFOUND"||r==="ECONNREFUSED"||r==="EAI_AGAIN"))return!0;let n=e.name;return typeof n=="string"&&(n==="AbortError"||n==="TimeoutError")}function jA(e){return t=>{if(de(t))throw t;return v(e.module,`Failed to ${e.label}: ${I(t)}`),e.fallback}}function am(e){if(e instanceof Te)return"CONFIGURATION";if(e instanceof j)return"VALIDATION";if(e instanceof Tr||e instanceof Qt)return"CONCURRENCY";let t=Ue(e);if(t===401)return"AUTH_REQUIRED";if(t===403){let n=I(e).toLowerCase();return n.includes("rate limit")||n.includes("abuse detection")?"RATE_LIMITED":"AUTH_REQUIRED"}if(t===404)return"NOT_FOUND";if(t===429)return"RATE_LIMITED";let r=I(e).toLowerCase();return r.includes("enotfound")||r.includes("econnrefused")||r.includes("econnreset")||r.includes("etimedout")||r.includes("fetch failed")?"NETWORK":r.includes("state")&&(r.includes("corrupt")||r.includes("invalid"))?"STATE_CORRUPTED":"UNKNOWN"}var _r,Te,sm,j,zi,lu,Tr,Qt,om,$r,IS,ee=A(()=>{"use strict";ce();_r=class extends Error{constructor(r,n){super(r);this.code=n;this.name="OssAutopilotError"}code},Te=class extends _r{constructor(t){super(t,"CONFIGURATION_ERROR"),this.name="ConfigurationError"}},sm="OSS_AUTOPILOT_UNATTENDED";j=class extends _r{constructor(t){super(t,"VALIDATION_ERROR"),this.name="ValidationError"}},zi=class extends Te{constructor(t){super(t??'Your GitHub token does not have Gist permissions. Run `gh auth refresh -s gist` to add the required scope, or create a token with the "gist" scope.'),this.name="GistPermissionError"}},lu=class extends Te{constructor(r,n,s){let o=s instanceof Error?s.message:String(s),i=n?`
63
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){o(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){o(i);continue}}if(e.metadataRegistry.get(i[0])?.id){o(i);continue}if(a.cycle){o(i);continue}a.count>1&&e.reused==="ref"&&o(i)}e.external&&(e.sharedDefsExtractedFor=e.external)}function PP(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!="object")return;PP(n);let s=Object.keys(n);if(s.length!==1||s[0]!=="type")return;let o=n.type;for(let i of Array.isArray(o)?o:[o]){if(typeof i!="string")return;r.includes(i)||r.push(i)}}delete e.anyOf,e.type=r.length===1?r[0]:r}function CP(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function bw(e){let t=[];for(let o of e){if(typeof o!="object"||o.type!=="object")return null;for(let i in o)if(!EP.has(i))return null;t.push(o)}let r={},n=new Set;for(let o of t){for(let i in o.properties){if(Object.prototype.hasOwnProperty.call(r,i))continue;let a=[];for(let u of t){let d=u.properties?.[i]??CP(u);d!=null&&(a.some(p=>JSON.stringify(p)===JSON.stringify(d))||a.push(d))}let c=a.length===1?a[0]:bw(a)??{allOf:a};St(r,i,c)}for(let i of o.required??[])n.add(i)}let s={type:"object",properties:r};if(n.size&&(s.required=[...n]),t.every(o=>o.additionalProperties===!1))s.additionalProperties=!1;else{let o=[];for(let i of t){let a=CP(i);a&&!o.some(c=>JSON.stringify(c)===JSON.stringify(a))&&o.push(a)}o.length===1?s.additionalProperties=o[0]:o.length>1&&(s.additionalProperties={allOf:o})}return s}function HU(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let s of EP)if(s in e)return;let r=t.filter(s=>kP.some(o=>Array.isArray(s[o]))),n=null;if(!r.length)n=bw(t);else{let s=r[0],o=kP.find(c=>Array.isArray(s[c]));if(Object.keys(s).length!==1)return;let i=t.filter(c=>c!==s),a=s[o].map(c=>bw([...i,c]));if(a.some(c=>!c))return;n={[o]:a}}n&&(delete e.allOf,jc(e,n))}function Zn(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},p=c.ref;if(c.ref=null,p){n(p);let f=e.seen.get(p),g=f.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(g)):jc(u,g),jc(u,d),a._zod.parent===p)for(let b in u)b==="$ref"||b==="allOf"||b in d||delete u[b];if(g.$ref&&f.def)for(let b in u)b==="$ref"||b==="allOf"||b in f.def&&JSON.stringify(u[b])===JSON.stringify(f.def[b])&&delete u[b]}let m=a._zod.parent;if(m&&m!==p){n(m);let f=e.seen.get(m);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let g in u)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(u[g])===JSON.stringify(f.def[g])&&delete u[g]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())PP(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let u of[c.schema,c.def]){let d=u?.allOf;if(!Array.isArray(d))continue;let p=a.get(d);p?p.push(u):a.set(d,[u])}for(let c of e.intersections)for(let u of a.get(c)??[])HU(u)}}let s={};if(e.target==="draft-2020-12"?s.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?s.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?s.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");s.$id=e.external.uri(a)}jc(s,r.defId?r.schema:r.def??r.schema);let o=e.metadataRegistry.get(t)?.id;o!==void 0&&s.id===o&&delete s.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,St(i,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?s.$defs=i:s.definitions=i);try{let a=JSON.parse(JSON.stringify(s));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ci(t,"input",e.processors),output:Ci(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ft(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Ft(n.element,r);if(n.type==="set")return Ft(n.valueType,r);if(n.type==="lazy")return Ft(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return Ft(n.innerType,r);if(n.type==="intersection")return Ft(n.left,r)||Ft(n.right,r);if(n.type==="record"||n.type==="map")return Ft(n.keyType,r)||Ft(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ft(n.in,r)||Ft(n.out,r);if(n.type==="object"){for(let s in n.shape)if(Ft(n.shape[s],r))return!0;return!1}if(n.type==="union"){for(let s of n.options)if(Ft(s,r))return!0;return!1}if(n.type==="tuple"){for(let s of n.items)if(Ft(s,r))return!0;return!!(n.rest&&Ft(n.rest,r))}return!1}var EP,kP,ww,Ci,zc=A(()=>{Lc();rt();EP=new Set(["type","properties","required","additionalProperties"]),kP=["oneOf","anyOf"];ww=(e,t={})=>r=>{let n=Vn({...r,processors:t});return xe(e,n),qn(n,e),Zn(n,e)},Ci=(e,t,r={})=>n=>{let{libraryOptions:s,target:o}=n??{},i=Vn({...s??{},target:o,io:t,processors:r});return xe(e,i),qn(i,e),Zn(i,e)}});function lt(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let o of n)WU[o._zod.def.check]?.(t,o._zod.def);let s=e._zod.bag;s.minimum!==void 0&&Pi(t,"minimum",s.minimum),s.exclusiveMinimum!==void 0&&Pi(t,"exclusiveMinimum",s.exclusiveMinimum),s.maximum!==void 0&&Ei(t,"maximum",s.maximum),s.exclusiveMaximum!==void 0&&Ei(t,"exclusiveMaximum",s.exclusiveMaximum),s.multipleOf!==void 0&&IP(t,s.multipleOf),s.format!==void 0&&(t.format??(t.format=s.format),s.format.includes("int")&&(t.isInt=!0)),s.mime&&DP(t,s.mime);for(let o of s.patterns??[])xP(t,o);return t}function Bc(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Bc(t.out):t.type==="catch"?Bc(t.innerType):e._zod.optin}function Rw(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let g=e.get(t)?.def;if(!g)return t;let h=Rw(e,g,r);return h===g?t:h}for(let g of["anyOf","oneOf"]){let h=t[g];if(!Array.isArray(h))continue;let b=h.map(w=>Rw(e,w,r));b.some((w,y)=>w!==h[y])&&(t={...t,[g]:b})}let n=Array.isArray(t.type)?t.type:[t.type],s=!n.includes("string")&&n.some(g=>g==="number"||g==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!s&&!o?.some(g=>typeof g=="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:d,format:p,id:m,...f}=t;return f.enum?f.enum=f.enum.map(g=>typeof g=="number"?String(g):g):typeof f.const=="number"&&(f.const=String(f.const)),s&&(f.type="string",o||(f.pattern=(n.includes("number")?pn:wc).source)),f}function ZU(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let r=new Map;for(let n of Sw.get(e)??[]){let s=e.seen.get(n),o=(s?.def??s?.schema)?.propertyNames;if(!o||o===!0||r.has(o))continue;let i=Rw(t,o,new Set);i!==o&&r.set(o,i)}if(r.size)for(let n of e.seen.values())for(let s of[n.schema,n.def]){let o=s&&r.get(s.propertyNames);o&&(s.propertyNames=o)}}function FP(e,t,r,n,s){let o=!1,i=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(o=!0,null));return o?(ut(t,r,n,s,"BigInt defaults cannot be represented in JSON Schema"),Qw):JSON.parse(i)}function dp(e,t){if("_idmap"in e){let n=e,s=Vn({...t,processors:cp}),o={};for(let c of n._idmap.entries()){let[u,d]=c;xe(d,s)}let i={},a={registry:n,uri:t?.uri,defs:o};s.external=a;for(let c of n._idmap.entries()){let[u,d]=c;qn(s,d),St(i,u,Zn(s,d))}if(Object.keys(o).length>0){let c=s.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[c]:o}}return{schemas:i}}let r=Vn({...t,processors:cp});return xe(e,r),qn(r,e),Zn(r,e)}var Pi,Ei,AP,IP,xP,DP,LP,TP,$P,OP,WU,VU,qU,MP,_w,vw,kw,Cw,Pw,Ew,Aw,Tw,$w,Ow,Iw,xw,Dw,Lw,Mw,Fw,Nw,Gw,Uw,jw,zw,Bw,Hw,Ww,Vw,up,qw,Zw,Sw,Kw,Jw,Yw,Qw,Xw,eR,tR,rR,nR,sR,lp,oR,cp,Hc=A(()=>{xs();ui();zc();rt();Pi=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Ei=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},AP=(e,t)=>{Pi(e,"minimum",t),Ei(e,"maximum",t)},IP=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},xP=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},DP=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},LP=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},TP=(e,t)=>Pi(e,"minimum",t.minimum),$P=(e,t)=>Ei(e,"maximum",t.maximum),OP=e=>(t,r)=>{LP(t,r.format);let[n,s]=e[r.format];Pi(t,"minimum",n),Ei(t,"maximum",s)},WU={greater_than:(e,t)=>Pi(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Ei(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>IP(e,t.value),number_format:OP(cc),bigint_format:OP(uc),min_length:TP,max_length:$P,length_equals:(e,t)=>AP(e,t.length),min_size:TP,max_size:$P,size_equals:(e,t)=>AP(e,t.size),string_format:(e,t)=>{LP(e,t.format),t.pattern&&xP(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>DP(e,t.mime)};VU={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},qU=new Map([[fd,Sh],[Pc,_h]]),MP=e=>qU.get(e)??e,_w=(e,t,r,n)=>{let s=r;s.type="string";let{minimum:o,maximum:i,format:a,patterns:c,contentEncoding:u,laxFormat:d}=lt(e);if(typeof o=="number"&&(s.minLength=o),typeof i=="number"&&(s.maxLength=i),a&&(s.format=VU[a]??a,s.format===""&&delete s.format,(a==="time"||d)&&delete s.format),u&&(s.contentEncoding=u),c&&c.size>0){let p=[...c].map(MP);p.length===1?s.pattern=p[0].source:p.length>1&&(s.allOf=[...p.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},vw=(e,t,r,n)=>{let s=r,{minimum:o,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:d}=lt(e);s.type=d?"integer":"number";let p=typeof u=="number"&&u>=(o??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(p?f?(s.minimum=u,s.exclusiveMinimum=!0):s.exclusiveMinimum=u:typeof o=="number"&&(s.minimum=o),m?f?(s.maximum=c,s.exclusiveMaximum=!0):s.exclusiveMaximum=c:typeof i=="number"&&(s.maximum=i),a){let g=new Set;for(let w of a)Number.isFinite(w)&&w!==0?g.add(Math.abs(w)):ut(e,t,s,n,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[h,...b]=g;h!==void 0&&(s.multipleOf=h),b.length&&(s.allOf=[...s.allOf??[],...b.map(w=>({multipleOf:w}))])}},kw=(e,t,r,n)=>{r.type="boolean"},Cw=(e,t,r,n)=>{ut(e,t,r,n,"BigInt cannot be represented in JSON Schema")},Pw=(e,t,r,n)=>{ut(e,t,r,n,"Symbols cannot be represented in JSON Schema")},Ew=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Aw=(e,t,r,n)=>{ut(e,t,r,n,"Undefined cannot be represented in JSON Schema")},Tw=(e,t,r,n)=>{ut(e,t,r,n,"Void cannot be represented in JSON Schema")},$w=(e,t,r,n)=>{r.not={}},Ow=(e,t,r,n)=>{},Iw=(e,t,r,n)=>{},xw=(e,t,r,n)=>{ut(e,t,r,n,"Date cannot be represented in JSON Schema")},Dw=(e,t,r,n)=>{let s=e._zod.def,o=Yo(s.entries);if(o.length===0){r.not={};return}o.every(i=>typeof i=="number")&&(r.type="number"),o.every(i=>typeof i=="string")&&(r.type="string"),r.enum=o},Lw=(e,t,r,n)=>{let s=e._zod.def;if(s.values.length===0){r.not={};return}let o=[];for(let i of s.values)if(i===void 0){if(ut(e,t,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i=="bigint"){if(ut(e,t,r,n,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(i))}else o.push(i);if(o.length!==0)if(o.length===1){let i=o[0];r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[i]:r.const=i}else o.every(i=>typeof i=="number")&&(r.type="number"),o.every(i=>typeof i=="string")&&(r.type="string"),o.every(i=>typeof i=="boolean")&&(r.type="boolean"),o.every(i=>i===null)&&(r.type="null"),r.enum=o},Mw=(e,t,r,n)=>{ut(e,t,r,n,"NaN cannot be represented in JSON Schema")},Fw=(e,t,r,n)=>{let s=r,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");s.type="string",s.pattern=o.source},Nw=(e,t,r,n)=>{let s=r;s.type="string",s.format="binary",s.contentEncoding="binary";let{minimum:o,maximum:i,mime:a}=lt(e);o!==void 0&&(s.minLength=o),i!==void 0&&(s.maxLength=i),a&&(a.length===0?s.not={}:a.length===1?s.contentMediaType=a[0]:s.anyOf=a.map(c=>({contentMediaType:c})))},Gw=(e,t,r,n)=>{r.type="boolean"},Uw=(e,t,r,n)=>{ut(e,t,r,n,"Custom types cannot be represented in JSON Schema")},jw=(e,t,r,n)=>{ut(e,t,r,n,"Function types cannot be represented in JSON Schema")},zw=(e,t,r,n)=>{ut(e,t,r,n,"Transforms cannot be represented in JSON Schema")},Bw=(e,t,r,n)=>{ut(e,t,r,n,"Map cannot be represented in JSON Schema")},Hw=(e,t,r,n)=>{ut(e,t,r,n,"Set cannot be represented in JSON Schema")},Ww=(e,t,r,n)=>{let s=r,o=e._zod.def,{minimum:i,maximum:a}=lt(e);typeof i=="number"&&(s.minItems=i),typeof a=="number"&&(s.maxItems=a),s.type="array",s.items=xe(o.element,t,{...n,path:[...n.path,"items"]})};Vw=(e,t,r,n)=>{let s=r,o=e._zod.def,i=o.shape;if(Object.getOwnPropertySymbols(i).length&&ut(e,t,s,n,"Symbol keys cannot be represented in JSON Schema"))return;s.type="object",s.properties={};for(let u in i)St(s.properties,u,xe(i[u],t,{...n,path:[...n.path,"properties",u]}));let c=[];for(let u of Object.keys(i)){let d=o.shape[u];(t.io==="input"?Bc(d)===void 0:d._zod.optout===void 0)&&c.push(u)}c.length>0&&(s.required=c),o.catchall?._zod.def.type==="never"?s.additionalProperties=!1:o.catchall?o.catchall&&(s.additionalProperties=xe(o.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(s.additionalProperties=!1)},up=(e,t,r,n)=>{let s=e._zod.def,o=s.inclusive===!1,i=s.options.map((a,c)=>xe(a,t,{...n,path:[...n.path,o?"oneOf":"anyOf",c]}));o?r.oneOf=i:r.anyOf=i},qw=(e,t,r,n)=>{let s=e._zod.def,o=xe(s.left,t,{...n,path:[...n.path,"allOf",0]}),i=xe(s.right,t,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(i)?i.allOf:[i]];r.allOf=c,t.intersections.push(c)},Zw=(e,t,r,n)=>{let s=r,o=e._zod.def;s.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((h,b)=>xe(h,t,{...n,path:[...n.path,i,b]})),u=o.rest?xe(o.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null,d=o.items.length;for(;d>0;){let h=o.items[d-1];if(!(t.io==="input"?Bc(h)!==void 0:h._zod.optout==="optional"))break;d--}let p=o.items.length,m=!o.rest;t.target==="draft-2020-12"?(s.prefixItems=c,m?s.items=!1:u&&(s.items=u),d>0&&(s.minItems=d),m&&(s.maxItems=p)):t.target==="openapi-3.0"?(s.items={anyOf:c},u&&s.items.anyOf.push(u),d>0&&(s.minItems=d),m&&(s.maxItems=p)):(s.items=c,m?s.additionalItems=!1:u&&(s.additionalItems=u),d>0&&(s.minItems=d),m&&(s.maxItems=p));let{minimum:f,maximum:g}=lt(e);typeof f=="number"&&(s.minItems=f),typeof g=="number"&&(s.maxItems=g)};Sw=new WeakMap;Kw=(e,t,r,n)=>{let s=r,o=e._zod.def;s.type="object";let i=o.keyType,a=lt(i).patterns;if(o.mode==="loose"&&a&&a.size>0){let d=xe(o.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});s.patternProperties={};for(let p of a)St(s.patternProperties,MP(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){s.propertyNames=xe(o.keyType,t,{...n,path:[...n.path,"propertyNames"]});let d=Sw.get(t);d||(d=[],Sw.set(t,d),t.deferred.push(()=>ZU(t))),d.push(e)}s.additionalProperties=xe(o.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=i._zod.values,u=t.io==="input"&&Bc(o.valueType)!==void 0;if(c&&!o.partial&&!u){let d=[...c].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(s.required=d.map(String))}},Jw=(e,t,r,n)=>{let s=e._zod.def,o=xe(s.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=s.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},Yw=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},Qw=Symbol();Xw=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType;let i=FP(s.defaultValue,e,t,r,n);i!==Qw&&(r.default=i)},eR=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);if(o.ref=s.innerType,t.io!=="input")return;let i=FP(s.defaultValue,e,t,r,n);i!==Qw&&(r._prefault=i)},tR=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType;let i;try{i=s.catchValue(void 0)}catch{ut(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=i},rR=(e,t,r,n)=>{let s=e._zod.def,o=s.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?o?s.out:s.in:s.out;xe(i,t,n);let a=t.seen.get(e);a.ref=i},nR=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType,r.readOnly=!0},sR=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},lp=(e,t,r,n)=>{let s=e._zod.def;xe(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},oR=(e,t,r,n)=>{let s=e._zod.innerType;xe(s,t,n);let o=t.seen.get(e);o.ref=s},cp={string:_w,number:vw,boolean:kw,bigint:Cw,symbol:Pw,null:Ew,undefined:Aw,void:Tw,never:$w,any:Ow,unknown:Iw,date:xw,enum:Dw,literal:Lw,nan:Mw,template_literal:Fw,file:Nw,success:Gw,custom:Uw,function:jw,transform:zw,map:Bw,set:Hw,array:Ww,object:Vw,union:up,intersection:qw,tuple:Zw,record:Kw,nullable:Jw,nonoptional:Yw,default:Xw,prefault:eR,catch:tR,pipe:rR,readonly:nR,promise:sR,optional:lp,lazy:oR}});var pp,NP=A(()=>{Hc();zc();pp=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Vn({processors:cp,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return xe(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,qn(this.ctx,t);let n=Zn(this.ctx,t),{"~standard":s,...o}=n;return o}}});var GP={};var UP=A(()=>{});var fn={};re(fn,{$ZodAny:()=>By,$ZodArray:()=>Ky,$ZodAsyncError:()=>Zt,$ZodBase64:()=>Oy,$ZodBase64URL:()=>Iy,$ZodBigInt:()=>Rd,$ZodBigIntFormat:()=>Gy,$ZodBoolean:()=>Ec,$ZodCIDRv4:()=>Ty,$ZodCIDRv6:()=>$y,$ZodCUID:()=>yy,$ZodCUID2:()=>by,$ZodCatch:()=>fb,$ZodCheck:()=>Ne,$ZodCheckBigIntFormat:()=>Bh,$ZodCheckEndsWith:()=>ty,$ZodCheckGreaterThan:()=>rd,$ZodCheckIncludes:()=>Xh,$ZodCheckLengthEquals:()=>Kh,$ZodCheckLessThan:()=>td,$ZodCheckLowerCase:()=>Yh,$ZodCheckMaxLength:()=>qh,$ZodCheckMaxSize:()=>Hh,$ZodCheckMimeType:()=>sy,$ZodCheckMinLength:()=>Zh,$ZodCheckMinSize:()=>Wh,$ZodCheckMultipleOf:()=>jh,$ZodCheckNumberFormat:()=>zh,$ZodCheckOverwrite:()=>oy,$ZodCheckProperties:()=>ny,$ZodCheckProperty:()=>ry,$ZodCheckRegex:()=>Jh,$ZodCheckSizeEquals:()=>Vh,$ZodCheckStartsWith:()=>ey,$ZodCheckStringFormat:()=>ai,$ZodCheckUpperCase:()=>Qh,$ZodCodec:()=>Tc,$ZodCreditCard:()=>Dy,$ZodCustom:()=>Sb,$ZodCustomStringFormat:()=>Fy,$ZodCyclicError:()=>Ed,$ZodDate:()=>qy,$ZodDefault:()=>lb,$ZodDiscriminatedUnion:()=>Xy,$ZodE164:()=>xy,$ZodEmail:()=>dy,$ZodEmoji:()=>gy,$ZodEncodeError:()=>zn,$ZodEnum:()=>sb,$ZodError:()=>Xg,$ZodExactOptional:()=>cb,$ZodFile:()=>ib,$ZodFunction:()=>wb,$ZodGUID:()=>uy,$ZodIBAN:()=>Ly,$ZodIPv4:()=>Py,$ZodIPv6:()=>Ey,$ZodISODate:()=>vy,$ZodISODateTime:()=>_y,$ZodISODuration:()=>Cy,$ZodISOTime:()=>ky,$ZodIntersection:()=>eb,$ZodJWT:()=>My,$ZodKSUID:()=>Sy,$ZodLazy:()=>$c,$ZodLiteral:()=>ob,$ZodMAC:()=>Ay,$ZodMap:()=>rb,$ZodNaN:()=>gb,$ZodNanoID:()=>hy,$ZodNever:()=>Wy,$ZodNonOptional:()=>pb,$ZodNull:()=>zy,$ZodNullable:()=>ub,$ZodNumber:()=>wd,$ZodNumberFormat:()=>Ny,$ZodObject:()=>oP,$ZodObjectJIT:()=>Jy,$ZodOptional:()=>_d,$ZodPipe:()=>vd,$ZodPrefault:()=>db,$ZodPreprocess:()=>hb,$ZodPromise:()=>Rb,$ZodReadonly:()=>yb,$ZodRealError:()=>Kt,$ZodRecord:()=>tb,$ZodRegistry:()=>Od,$ZodSet:()=>nb,$ZodString:()=>Ls,$ZodStringFormat:()=>Ie,$ZodSuccess:()=>mb,$ZodSymbol:()=>Uy,$ZodTemplateLiteral:()=>bb,$ZodTransform:()=>ab,$ZodTuple:()=>Sd,$ZodType:()=>pe,$ZodULID:()=>wy,$ZodURL:()=>fy,$ZodUUID:()=>ly,$ZodUndefined:()=>jy,$ZodUnion:()=>Ac,$ZodUnknown:()=>Hy,$ZodVoid:()=>Vy,$ZodXID:()=>Ry,$ZodXor:()=>Yy,$brand:()=>Jg,$constructor:()=>$,$input:()=>Ab,$output:()=>Eb,Doc:()=>Ds,INVALID:()=>Mt,JSONSchema:()=>GP,JSONSchemaGenerator:()=>pp,NEVER:()=>Kg,TimePrecision:()=>Ub,URL_BAD_FORMAT:()=>py,URL_UNPARSEABLE:()=>_c,ZodCompileAsyncError:()=>Pr,ZodCompileUnsupportedError:()=>Se,_any:()=>nw,_array:()=>lw,_base64:()=>Xd,_base64url:()=>ep,_bigint:()=>Jb,_boolean:()=>Zb,_catch:()=>NU,_check:()=>SP,_cidrv4:()=>Yd,_cidrv6:()=>Qd,_coercedBigint:()=>Yb,_coercedBoolean:()=>Kb,_coercedDate:()=>cw,_coercedNumber:()=>zb,_coercedString:()=>Mb,_creditCard:()=>Nb,_cuid:()=>Hd,_cuid2:()=>Wd,_custom:()=>pw,_date:()=>aw,_decode:()=>Hl,_decodeAsync:()=>Vl,_default:()=>LU,_discriminatedUnion:()=>vU,_e164:()=>tp,_email:()=>Md,_emoji:()=>zd,_encode:()=>Bl,_encodeAsync:()=>Wl,_endsWith:()=>yi,_enum:()=>TU,_file:()=>dw,_float32:()=>Hb,_float64:()=>Wb,_gt:()=>jr,_gte:()=>ir,_guid:()=>Fd,_iban:()=>Gb,_includes:()=>gi,_int:()=>Bb,_int32:()=>Vb,_int64:()=>Qb,_intersection:()=>kU,_ipv4:()=>Kd,_ipv6:()=>Jd,_isoDate:()=>Nc,_isoDateTime:()=>Fc,_isoDuration:()=>Uc,_isoTime:()=>Gc,_jwt:()=>rp,_ksuid:()=>Zd,_lazy:()=>zU,_length:()=>js,_literal:()=>OU,_lowercase:()=>mi,_lt:()=>Ur,_lte:()=>or,_mac:()=>Fb,_map:()=>EU,_max:()=>or,_maxLength:()=>Us,_maxSize:()=>Wn,_mime:()=>wi,_min:()=>ir,_minLength:()=>mn,_minSize:()=>zr,_multipleOf:()=>Hn,_nan:()=>uw,_nanoid:()=>Bd,_nativeEnum:()=>$U,_negative:()=>sp,_never:()=>ow,_nonnegative:()=>ip,_nonoptional:()=>MU,_nonpositive:()=>op,_normalize:()=>Ri,_null:()=>rw,_nullable:()=>DU,_number:()=>jb,_optional:()=>xU,_overwrite:()=>Er,_parse:()=>ni,_parseAsync:()=>si,_pipe:()=>GU,_positive:()=>np,_promise:()=>BU,_properties:()=>bi,_property:()=>ap,_readonly:()=>UU,_record:()=>PU,_refine:()=>mw,_regex:()=>pi,_safeDecode:()=>Zl,_safeDecodeAsync:()=>Jl,_safeEncode:()=>ql,_safeEncodeAsync:()=>Kl,_safeParse:()=>oi,_safeParseAsync:()=>ii,_set:()=>AU,_size:()=>Gs,_slugify:()=>ki,_startsWith:()=>hi,_string:()=>Lb,_stringFormat:()=>zs,_stringbool:()=>yw,_success:()=>FU,_superRefine:()=>fw,_symbol:()=>ew,_templateLiteral:()=>jU,_toLowerCase:()=>_i,_toUpperCase:()=>vi,_transform:()=>IU,_trim:()=>Si,_tuple:()=>CU,_uint32:()=>qb,_uint64:()=>Xb,_ulid:()=>Vd,_undefined:()=>tw,_union:()=>SU,_unknown:()=>sw,_uppercase:()=>fi,_url:()=>Mc,_uuid:()=>Nd,_uuidv4:()=>Gd,_uuidv6:()=>Ud,_uuidv7:()=>jd,_void:()=>iw,_xid:()=>qd,_xor:()=>_U,base64Charset:()=>fd,base64urlCharset:()=>Pc,canParseURL:()=>my,clone:()=>Oe,compile:()=>Ib,compileFn:()=>Dd,config:()=>Ye,createStandardJSONSchemaMethod:()=>Ci,createToJSONSchemaMethod:()=>ww,decode:()=>AN,decodeAsync:()=>$N,describe:()=>gw,encode:()=>EN,encodeAsync:()=>TN,extractDefs:()=>qn,finalize:()=>Zn,flattenError:()=>fc,formatError:()=>gc,getDiscriminatedOption:()=>Qy,globalConfig:()=>ht,globalRegistry:()=>_t,handleUnrepresentable:()=>ut,initializeContext:()=>Vn,isBackEdge:()=>Td,isRecursiveSchema:()=>Ad,isValidBase64:()=>Cc,isValidBase64URL:()=>gd,isValidCIDRv6:()=>md,isValidCreditCard:()=>hd,isValidIBAN:()=>yd,isValidIPv6:()=>kc,isValidJWT:()=>bd,locales:()=>Dc,memoizer:()=>xc,mergeValues:()=>ci,meta:()=>hw,parse:()=>jl,parseAsync:()=>zl,parseURLObject:()=>rP,prettifyError:()=>th,process:()=>xe,processSchema:()=>xe,regexes:()=>Rr,registry:()=>Id,safeDecode:()=>IN,safeDecodeAsync:()=>DN,safeEncode:()=>ON,safeEncodeAsync:()=>xN,safeParse:()=>_N,safeParseAsync:()=>vN,standardProps:()=>ud,stripTabAndNewline:()=>vc,toDotPath:()=>LC,toJSONSchema:()=>dp,toZod:()=>sc,treeifyError:()=>eh,urlHostnameOk:()=>dd,urlProtocolOk:()=>pd,util:()=>V,validate:()=>hc,validateAsync:()=>yc,validateURL:()=>ld,version:()=>iy,withParser:()=>xd});var ar=A(()=>{jn();nh();rh();ui();kb();nd();ay();rt();rt();xs();Pb();Lc();sd();RP();_P();zc();Hc();NP();UP()});var mp={};re(mp,{endsWith:()=>yi,gt:()=>jr,gte:()=>ir,includes:()=>gi,length:()=>js,lowercase:()=>mi,lt:()=>Ur,lte:()=>or,maxLength:()=>Us,maxSize:()=>Wn,mime:()=>wi,minLength:()=>mn,minSize:()=>zr,multipleOf:()=>Hn,negative:()=>sp,nonnegative:()=>ip,nonpositive:()=>op,normalize:()=>Ri,overwrite:()=>Er,positive:()=>np,properties:()=>bi,property:()=>ap,regex:()=>pi,size:()=>Gs,slugify:()=>ki,startsWith:()=>hi,toLowerCase:()=>_i,toUpperCase:()=>vi,trim:()=>Si,uppercase:()=>fi});var fp=A(()=>{ar()});function gp(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var jP,zP,JU,Jt,iR=A(()=>{ar();ar();rt();jP=new WeakSet([Object.prototype,Error.prototype]);zP=(e,t)=>{Xg.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);jP.has(r)||(jP.add(r),gp(r,"format",n=>s=>gc(n,s)),gp(r,"flatten",n=>s=>fc(n,s)),gp(r,"addIssue",n=>s=>{n.issues.push(s),n.message=JSON.stringify(n.issues,Qo,2)}),gp(r,"addIssues",n=>s=>{n.issues.push(...s),n.message=JSON.stringify(n.issues,Qo,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},JU=$("ZodError",zP),Jt=$("ZodError",zP,void 0,{Parent:Error})});var aR,cR,uR,lR,dR,pR,mR,fR,gR,hR,yR,bR,wR=A(()=>{ar();iR();ar();aR=ni(Jt),cR=si(Jt),uR=oi(Jt),lR=ii(Jt),dR=Bl(Jt),pR=Hl(Jt),mR=Wl(Jt),fR=Vl(Jt),gR=ql(Jt),hR=Zl(Jt),yR=Kl(Jt),bR=Jl(Jt)});var Li={};re(Li,{ZodAny:()=>TR,ZodArray:()=>xR,ZodBase64:()=>Ip,ZodBase64URL:()=>xp,ZodBigInt:()=>xi,ZodBigIntFormat:()=>Mp,ZodBoolean:()=>Ii,ZodCIDRv4:()=>$p,ZodCIDRv6:()=>Op,ZodCUID:()=>vp,ZodCUID2:()=>kp,ZodCatch:()=>eS,ZodCodec:()=>eu,ZodCreditCard:()=>SR,ZodCustom:()=>tu,ZodCustomStringFormat:()=>Vs,ZodDate:()=>Zc,ZodDefault:()=>ZR,ZodDiscriminatedUnion:()=>LR,ZodE164:()=>Dp,ZodEmail:()=>wp,ZodEmoji:()=>Sp,ZodEnum:()=>Ti,ZodExactOptional:()=>Up,ZodFile:()=>HR,ZodFunction:()=>lS,ZodGUID:()=>Rp,ZodIBAN:()=>_R,ZodIPv4:()=>Ap,ZodIPv6:()=>Tp,ZodISODate:()=>Jn,ZodISODateTime:()=>Kn,ZodISODuration:()=>Qn,ZodISOTime:()=>Yn,ZodInstanceOf:()=>mS,ZodIntersection:()=>MR,ZodJWT:()=>Lp,ZodKSUID:()=>Ep,ZodLazy:()=>aS,ZodLiteral:()=>BR,ZodMAC:()=>RR,ZodMap:()=>jR,ZodNaN:()=>rS,ZodNanoID:()=>_p,ZodNever:()=>OR,ZodNonOptional:()=>jp,ZodNull:()=>ER,ZodNullable:()=>qR,ZodNumber:()=>Oi,ZodNumberFormat:()=>qs,ZodObject:()=>Jc,ZodOptional:()=>Qc,ZodPipe:()=>Xc,ZodPrefault:()=>JR,ZodPreprocess:()=>nS,ZodPromise:()=>uS,ZodReadonly:()=>sS,ZodRecord:()=>Ai,ZodSet:()=>zR,ZodString:()=>$i,ZodStringFormat:()=>Le,ZodSuccess:()=>XR,ZodSymbol:()=>CR,ZodTemplateLiteral:()=>iS,ZodTransform:()=>WR,ZodTuple:()=>NR,ZodType:()=>ge,ZodULID:()=>Cp,ZodURL:()=>qc,ZodUUID:()=>Br,ZodUndefined:()=>PR,ZodUnion:()=>Yc,ZodUnknown:()=>$R,ZodVoid:()=>IR,ZodXID:()=>Pp,ZodXor:()=>DR,_ZodString:()=>bp,_default:()=>KR,_function:()=>QE,any:()=>TE,array:()=>Kc,base64:()=>uE,base64url:()=>lE,bigint:()=>kE,boolean:()=>kR,catch:()=>tS,check:()=>XE,cidrv4:()=>aE,cidrv6:()=>cE,codec:()=>ZE,creditCard:()=>pE,cuid:()=>XP,cuid2:()=>eE,currencyCode:()=>bE,custom:()=>eA,date:()=>OE,describe:()=>tA,discriminatedUnion:()=>FE,e164:()=>dE,email:()=>BP,emoji:()=>YP,enum:()=>Np,exactOptional:()=>VR,file:()=>HE,float32:()=>RE,float64:()=>SE,function:()=>QE,guid:()=>HP,hash:()=>wE,hex:()=>yE,hostname:()=>hE,httpUrl:()=>JP,iban:()=>mE,instanceof:()=>nA,int:()=>hp,int32:()=>_E,int64:()=>CE,intersection:()=>FR,invertCodec:()=>KE,ipv4:()=>sE,ipv6:()=>iE,json:()=>oA,jwt:()=>fE,keyof:()=>IE,ksuid:()=>nE,lazy:()=>cS,literal:()=>BE,looseObject:()=>LE,looseRecord:()=>GE,mac:()=>oE,map:()=>UE,meta:()=>rA,nan:()=>qE,nanoid:()=>QP,nativeEnum:()=>zE,never:()=>Fp,nonoptional:()=>QR,null:()=>AR,nullable:()=>Vc,nullish:()=>WE,number:()=>vR,object:()=>xE,optional:()=>Hs,partialRecord:()=>NE,pipe:()=>yp,prefault:()=>YR,preprocess:()=>iA,promise:()=>YE,readonly:()=>oS,record:()=>UR,refine:()=>dS,set:()=>jE,strictObject:()=>DE,string:()=>Wc,stringFormat:()=>gE,stringbool:()=>sA,success:()=>VE,superRefine:()=>pS,symbol:()=>EE,templateLiteral:()=>JE,transform:()=>Gp,tuple:()=>GR,uint32:()=>vE,uint64:()=>PE,ulid:()=>tE,undefined:()=>AE,union:()=>Di,unknown:()=>Bs,url:()=>KP,uuid:()=>WP,uuidv4:()=>VP,uuidv6:()=>qP,uuidv7:()=>ZP,void:()=>$E,xid:()=>rE,xor:()=>ME});function QU(){ht.localeError||Ye($d())}function Ws(){ht.memoizer||Ye({memoizer:xc()})}function Wc(e){return Lb($i,e)}function BP(e){return Md(wp,e)}function HP(e){return Fd(Rp,e)}function WP(e){return Nd(Br,e)}function VP(e){return Gd(Br,e)}function qP(e){return Ud(Br,e)}function ZP(e){return jd(Br,e)}function KP(e){return Mc(qc,e)}function JP(e){return Mc(qc,{protocol:bc,hostname:kh,...V.normalizeParams(e)})}function YP(e){return zd(Sp,e)}function QP(e){return Bd(_p,e)}function XP(e){return Hd(vp,e)}function eE(e){return Wd(kp,e)}function tE(e){return Vd(Cp,e)}function rE(e){return qd(Pp,e)}function nE(e){return Zd(Ep,e)}function sE(e){return Kd(Ap,e)}function oE(e){return Fb(RR,e)}function iE(e){return Jd(Tp,e)}function aE(e){return Yd($p,e)}function cE(e){return Qd(Op,e)}function uE(e){return Xd(Ip,e)}function lE(e){return ep(xp,e)}function dE(e){return tp(Dp,e)}function pE(e){return Nb(SR,e)}function mE(e){return Gb(_R,e)}function fE(e){return rp(Lp,e)}function gE(e,t,r={}){return zs(Vs,e,t,r)}function hE(e){return zs(Vs,"hostname",vh,e)}function yE(e){return zs(Vs,"hex",Nh,e)}function bE(e){return zs(Vs,"currency_code",Ph,e)}function wE(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,s=Rr[n];if(!s)throw new Error(`Unrecognized hash format: ${n}`);return zs(Vs,n,s,t)}function vR(e){return jb(Oi,e)}function hp(e){return Bb(qs,e)}function RE(e){return Hb(qs,e)}function SE(e){return Wb(qs,e)}function _E(e){return Vb(qs,e)}function vE(e){return qb(qs,e)}function kR(e){return Zb(Ii,e)}function kE(e){return Jb(xi,e)}function CE(e){return Qb(Mp,e)}function PE(e){return Xb(Mp,e)}function EE(e){return ew(CR,e)}function AE(e){return tw(PR,e)}function AR(e){return rw(ER,e)}function TE(){return nw(TR)}function Bs(){return sw($R)}function Fp(e){return ow(OR,e)}function $E(e){return iw(IR,e)}function OE(e){return aw(Zc,e)}function Kc(e,t){return lw(xR,e,t)}function IE(e){let t=e._zod.def.shape;return Np(Object.keys(t))}function xE(e,t){let r={type:"object",shape:e??{},...V.normalizeParams(t)};return new Jc(r)}function DE(e,t){return new Jc({type:"object",shape:e,catchall:Fp(),...V.normalizeParams(t)})}function LE(e,t){return new Jc({type:"object",shape:e,catchall:Bs(),...V.normalizeParams(t)})}function Di(e,t){return new Yc({type:"union",options:e,...V.normalizeParams(t)})}function ME(e,t){return new DR({type:"union",options:e,inclusive:!1,...V.normalizeParams(t)})}function FE(e,t,r){return new LR({type:"union",options:t,discriminator:e,...V.normalizeParams(r)})}function FR(e,t){return new MR({type:"intersection",left:e,right:t})}function GR(e,t,r){let n=t instanceof pe,s=n?r:t,o=n?t:null;return new NR({type:"tuple",items:e,rest:o,...V.normalizeParams(s)})}function UR(e,t,r){return!t||!t._zod?new Ai({type:"record",keyType:Wc(),valueType:e,...V.normalizeParams(t)}):new Ai({type:"record",keyType:e,valueType:t,...V.normalizeParams(r)})}function NE(e,t,r){return new Ai({type:"record",keyType:e,valueType:t,...V.normalizeParams(r),partial:!0})}function GE(e,t,r){return new Ai({type:"record",keyType:e,valueType:t,mode:"loose",...V.normalizeParams(r)})}function UE(e,t,r){return new jR({type:"map",keyType:e,valueType:t,...V.normalizeParams(r)})}function jE(e,t){return new zR({type:"set",valueType:e,...V.normalizeParams(t)})}function Np(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ti({type:"enum",entries:r,...V.normalizeParams(t)})}function zE(e,t){return new Ti({type:"enum",entries:e,...V.normalizeParams(t)})}function BE(e,t){return new BR({type:"literal",values:Array.isArray(e)?e:[e],...V.normalizeParams(t)})}function HE(e){return dw(HR,e)}function Gp(e){return new WR({type:"transform",transform:e})}function Hs(e){return new Qc({type:"optional",innerType:e})}function VR(e){return new Up({type:"optional",innerType:e})}function Vc(e){return new qR({type:"nullable",innerType:e})}function WE(e){return Hs(Vc(e))}function KR(e,t){return new ZR({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():V.shallowClone(t)}})}function YR(e,t){return new JR({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():V.shallowClone(t)}})}function QR(e,t){return new jp({type:"nonoptional",innerType:e,...V.normalizeParams(t)})}function VE(e){return new XR({type:"success",innerType:e})}function tS(e,t){return new eS({type:"catch",innerType:e,catchValue:typeof t=="function"?t:V.constantCatch(t)})}function qE(e){return uw(rS,e)}function yp(e,t){return new Xc({type:"pipe",in:e,out:t})}function ZE(e,t,r){return new eu({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function KE(e){let t=e._zod.def;return new eu({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}function oS(e){return new sS({type:"readonly",innerType:e})}function JE(e,t){return new iS({type:"template_literal",parts:e,...V.normalizeParams(t)})}function cS(e){return new aS({type:"lazy",getter:e})}function YE(e){return new uS({type:"promise",innerType:e})}function QE(e){return new lS({type:"function",input:Array.isArray(e?.input)?GR(e?.input):e?.input??Kc(Bs()),output:e?.output??Bs()})}function XE(e){let t=new Ne({check:"custom"});return t._zod.check=e,t}function eA(e,t){return pw(tu,e??(()=>!0),t)}function dS(e,t={}){return mw(tu,e,t)}function pS(e,t){return fw(e,t)}function nA(e,t={}){let r=new mS({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...V.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=n=>{n.value instanceof e||n.issues.push({code:"invalid_type",expected:e.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}function oA(e){let t=cS(()=>Di([Wc(e),vR(),kR(),AR(),Kc(t),UR(Wc(),t)]));return t}function iA(e,t){return new nS({type:"pipe",in:Gp(e),out:t})}var ge,bp,$i,Le,Kn,Jn,Yn,Qn,wp,Rp,Br,qc,Sp,_p,vp,kp,Cp,Pp,Ep,Ap,RR,Tp,$p,Op,Ip,xp,Dp,SR,_R,Lp,Vs,Oi,qs,Ii,xi,Mp,CR,PR,ER,TR,$R,OR,IR,Zc,xR,Jc,Yc,DR,LR,MR,NR,Ai,jR,zR,Ti,BR,HR,WR,Qc,Up,qR,ZR,JR,jp,XR,eS,rS,Xc,eu,nS,sS,iS,aS,uS,lS,tu,tA,rA,mS,sA,Xn=A(()=>{ar();ar();Hc();xs();zc();Cb();fp();wR();ge=$("ZodType",(e,t)=>(QU(),pe.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(V.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Oe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(dS(e,t))},superRefine(e,t){return this.check(pS(e,t))},overwrite(e){return this.check(Er(e))},optional(){return Hs(this)},exactOptional(){return VR(this)},nullable(){return Vc(this)},nullish(){return Hs(Vc(this))},nonoptional(e){return QR(this,e)},array(){return Kc(this)},or(e){return Di([this,e])},and(e){return FR(this,e)},transform(e){return yp(this,Gp(e))},default(e){return KR(this,e)},prefault(e){return YR(this,e)},catch(e){return tS(this,e)},pipe(e){return yp(this,e)},readonly(){return oS(this)},describe(e){let t=this.clone();return _t.add(t,{description:e}),t},meta(...e){if(e.length===0)return _t.get(this);let t=this.clone();return _t.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return V.hide(this,"~standard",{...ud(this),jsonSchema:{input:Ci(this,"input"),output:Ci(this,"output")}})},set"~standard"(e){V.own(this,"~standard",e)},parse:function e(t,r){return aR(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await cR(this,t,r,{callee:e})},safeParse(e,t){return uR(this,e,t)},async safeParseAsync(e,t){return lR(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){V.own(this,"spa",e)},validate(e,t){return hc(this,e,t)},validateAsync(e,t){return yc(this,e,t)},encode:function e(t,r){return dR(this,t,r,{callee:e})},decode:function e(t,r){return pR(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await mR(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await fR(this,t,r,{callee:e})},safeEncode(e,t){return gR(this,e,t)},safeDecode(e,t){return hR(this,e,t)},async safeEncodeAsync(e,t){return yR(this,e,t)},async safeDecodeAsync(e,t){return bR(this,e,t)},toJSONSchema(e){return ww(this,{})(e)},get description(){return _t.get(this)?.description},get _def(){return this._zod.def}}),bp=$("_ZodString",(e,t)=>{Ls.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>_w(e,r,n,s)},V.derived({format:e=>lt(e).format??null,minLength:e=>lt(e).minimum??null,maxLength:e=>lt(e).maximum??null},{regex(...e){return this.check(pi(...e))},includes(...e){return this.check(gi(...e))},startsWith(...e){return this.check(hi(...e))},endsWith(...e){return this.check(yi(...e))},min(...e){return this.check(mn(...e))},max(...e){return this.check(Us(...e))},length(...e){return this.check(js(...e))},nonempty(...e){return this.check(mn(1,...e))},lowercase(e){return this.check(mi(e))},uppercase(e){return this.check(fi(e))},trim(){return this.check(Si())},normalize(...e){return this.check(Ri(...e))},toLowerCase(){return this.check(_i())},toUpperCase(){return this.check(vi())},slugify(){return this.check(ki())}})),$i=$("ZodString",(e,t)=>{Ls.init(e,t),bp.init(e,t)},{email(e){return this.check(Md(wp,e))},url(e){return this.check(Mc(qc,e))},jwt(e){return this.check(rp(Lp,e))},emoji(e){return this.check(zd(Sp,e))},guid(e){return this.check(Fd(Rp,e))},uuid(e){return this.check(Nd(Br,e))},uuidv4(e){return this.check(Gd(Br,e))},uuidv6(e){return this.check(Ud(Br,e))},uuidv7(e){return this.check(jd(Br,e))},nanoid(e){return this.check(Bd(_p,e))},cuid(e){return this.check(Hd(vp,e))},cuid2(e){return this.check(Wd(kp,e))},ulid(e){return this.check(Vd(Cp,e))},base64(e){return this.check(Xd(Ip,e))},base64url(e){return this.check(ep(xp,e))},xid(e){return this.check(qd(Pp,e))},ksuid(e){return this.check(Zd(Ep,e))},ipv4(e){return this.check(Kd(Ap,e))},ipv6(e){return this.check(Jd(Tp,e))},cidrv4(e){return this.check(Yd($p,e))},cidrv6(e){return this.check(Qd(Op,e))},e164(e){return this.check(tp(Dp,e))},datetime(e){return this.check(Fc(Kn,e))},date(e){return this.check(Nc(Jn,e))},time(e){return this.check(Gc(Yn,e))},duration(e){return this.check(Uc(Qn,e))}});Le=$("ZodStringFormat",(e,t)=>{Ie.init(e,t),bp.init(e,t)}),Kn=$("ZodISODateTime",(e,t)=>{_y.init(e,t),Le.init(e,t)}),Jn=$("ZodISODate",(e,t)=>{vy.init(e,t),Le.init(e,t)}),Yn=$("ZodISOTime",(e,t)=>{ky.init(e,t),Le.init(e,t)}),Qn=$("ZodISODuration",(e,t)=>{Cy.init(e,t),Le.init(e,t)}),wp=$("ZodEmail",(e,t)=>{dy.init(e,t),Le.init(e,t)});Rp=$("ZodGUID",(e,t)=>{uy.init(e,t),Le.init(e,t)});Br=$("ZodUUID",(e,t)=>{ly.init(e,t),Le.init(e,t)});qc=$("ZodURL",(e,t)=>{fy.init(e,t),Le.init(e,t)});Sp=$("ZodEmoji",(e,t)=>{gy.init(e,t),Le.init(e,t)});_p=$("ZodNanoID",(e,t)=>{hy.init(e,t),Le.init(e,t)});vp=$("ZodCUID",(e,t)=>{yy.init(e,t),Le.init(e,t)});kp=$("ZodCUID2",(e,t)=>{by.init(e,t),Le.init(e,t)});Cp=$("ZodULID",(e,t)=>{wy.init(e,t),Le.init(e,t)});Pp=$("ZodXID",(e,t)=>{Ry.init(e,t),Le.init(e,t)});Ep=$("ZodKSUID",(e,t)=>{Sy.init(e,t),Le.init(e,t)});Ap=$("ZodIPv4",(e,t)=>{Py.init(e,t),Le.init(e,t)});RR=$("ZodMAC",(e,t)=>{Ay.init(e,t),Le.init(e,t)});Tp=$("ZodIPv6",(e,t)=>{Ey.init(e,t),Le.init(e,t)});$p=$("ZodCIDRv4",(e,t)=>{Ty.init(e,t),Le.init(e,t)});Op=$("ZodCIDRv6",(e,t)=>{$y.init(e,t),Le.init(e,t)});Ip=$("ZodBase64",(e,t)=>{Oy.init(e,t),Le.init(e,t)});xp=$("ZodBase64URL",(e,t)=>{Iy.init(e,t),Le.init(e,t)});Dp=$("ZodE164",(e,t)=>{xy.init(e,t),Le.init(e,t)});SR=$("ZodCreditCard",(e,t)=>{Dy.init(e,t),Le.init(e,t)});_R=$("ZodIBAN",(e,t)=>{Ly.init(e,t),Le.init(e,t)});Lp=$("ZodJWT",(e,t)=>{My.init(e,t),Le.init(e,t)});Vs=$("ZodCustomStringFormat",(e,t)=>{Fy.init(e,t),Le.init(e,t)});Oi=$("ZodNumber",(e,t)=>{wd.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>vw(e,r,n,s),e.isFinite=!0},V.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=lt(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=lt(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=lt(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>lt(e).format??null},{gt(e,t){return this.check(jr(e,t))},gte(e,t){return this.check(ir(e,t))},min(e,t){return this.check(ir(e,t))},lt(e,t){return this.check(Ur(e,t))},lte(e,t){return this.check(or(e,t))},max(e,t){return this.check(or(e,t))},int(e){return this.check(hp(e))},safe(e){return this.check(hp(e))},positive(e){return this.check(jr(0,e))},nonnegative(e){return this.check(ir(0,e))},negative(e){return this.check(Ur(0,e))},nonpositive(e){return this.check(or(0,e))},multipleOf(e,t){return this.check(Hn(e,t))},step(e,t){return this.check(Hn(e,t))},finite(){return this}}));qs=$("ZodNumberFormat",(e,t)=>{Ny.init(e,t),Oi.init(e,t)});Ii=$("ZodBoolean",(e,t)=>{Ec.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>kw(e,r,n,s)});xi=$("ZodBigInt",(e,t)=>{Rd.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Cw(e,r,n,s)},V.derived({minValue:e=>lt(e).minimum??null,maxValue:e=>lt(e).maximum??null,format:e=>lt(e).format??null},{gte(e,t){return this.check(ir(e,t))},min(e,t){return this.check(ir(e,t))},gt(e,t){return this.check(jr(e,t))},lt(e,t){return this.check(Ur(e,t))},lte(e,t){return this.check(or(e,t))},max(e,t){return this.check(or(e,t))},positive(e){return this.check(jr(BigInt(0),e))},negative(e){return this.check(Ur(BigInt(0),e))},nonpositive(e){return this.check(or(BigInt(0),e))},nonnegative(e){return this.check(ir(BigInt(0),e))},multipleOf(e,t){return this.check(Hn(e,t))}}));Mp=$("ZodBigIntFormat",(e,t)=>{Gy.init(e,t),xi.init(e,t)});CR=$("ZodSymbol",(e,t)=>{Uy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Pw(e,r,n,s)});PR=$("ZodUndefined",(e,t)=>{jy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Aw(e,r,n,s)});ER=$("ZodNull",(e,t)=>{zy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Ew(e,r,n,s)});TR=$("ZodAny",(e,t)=>{By.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Ow(e,r,n,s)});$R=$("ZodUnknown",(e,t)=>{Hy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Iw(e,r,n,s)});OR=$("ZodNever",(e,t)=>{Wy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>$w(e,r,n,s)});IR=$("ZodVoid",(e,t)=>{Vy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Tw(e,r,n,s)});Zc=$("ZodDate",(e,t)=>{qy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>xw(e,r,n,s),e.min=(r,n)=>e.check(ir(r,n)),e.max=(r,n)=>e.check(or(r,n))},V.derived({minDate:e=>{let{minimum:t}=lt(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=lt(e);return t?new Date(t):null}},{}));xR=$("ZodArray",(e,t)=>{Ws(),Ky.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Ww(e,r,n,s),e.element=t.element},{min(e,t){return this.check(mn(e,t))},nonempty(e){return this.check(mn(1,e))},max(e,t){return this.check(Us(e,t))},length(e,t){return this.check(js(e,t))},unwrap(){return this.element}});Jc=$("ZodObject",(e,t)=>{Ws(),Jy.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Vw(e,r,n,s),V.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Np(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(V.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Bs()}))},loose(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Bs()}))},strict(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Fp()}))},strip(){return this.clone(V.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return V.extend(this,e)},safeExtend(e){return V.safeExtend(this,e)},merge(e){return V.merge(this,e)},pick(e){return V.pick(this,e)},omit(e){return V.omit(this,e)},partial(...e){return V.partial(Qc,this,e[0])},exactPartial(...e){return V.partial(Up,this,e[0],"exactPartial")},required(...e){return V.required(jp,this,e[0])}});Yc=$("ZodUnion",(e,t)=>{Ac.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>up(e,r,n,s),e.options=t.options});DR=$("ZodXor",(e,t)=>{Yc.init(e,t),Yy.init(e,t),e._zod.processJSONSchema=(r,n,s)=>up(e,r,n,s),e.options=t.options});LR=$("ZodDiscriminatedUnion",(e,t)=>{Yc.init(e,t),Xy.init(e,t)});MR=$("ZodIntersection",(e,t)=>{eb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>qw(e,r,n,s)});NR=$("ZodTuple",(e,t)=>{Ws(),Sd.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Zw(e,r,n,s)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Qc({type:"optional",innerType:t}))})}});Ai=$("ZodRecord",(e,t)=>{Ws(),tb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Kw(e,r,n,s),e.keyType=t.keyType,e.valueType=t.valueType});jR=$("ZodMap",(e,t)=>{Ws(),rb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Bw(e,r,n,s),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(zr(...r)),e.nonempty=r=>e.check(zr(1,r)),e.max=(...r)=>e.check(Wn(...r)),e.size=(...r)=>e.check(Gs(...r))});zR=$("ZodSet",(e,t)=>{Ws(),nb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Hw(e,r,n,s),e.min=(...r)=>e.check(zr(...r)),e.nonempty=r=>e.check(zr(1,r)),e.max=(...r)=>e.check(Wn(...r)),e.size=(...r)=>e.check(Gs(...r))});Ti=$("ZodEnum",(e,t)=>{sb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(n,s,o)=>Dw(e,n,s,o),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ti({...t,checks:[],...V.normalizeParams(s),entries:o})},e.exclude=(n,s)=>{let o={...t.entries};for(let i of n)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Ti({...t,checks:[],...V.normalizeParams(s),entries:o})}});BR=$("ZodLiteral",(e,t)=>{ob.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Lw(e,r,n,s),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});HR=$("ZodFile",(e,t)=>{ib.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Nw(e,r,n,s),e.min=(r,n)=>e.check(zr(r,n)),e.max=(r,n)=>e.check(Wn(r,n)),e.mime=(r,n)=>e.check(wi(Array.isArray(r)?r:[r],n))});WR=$("ZodTransform",(e,t)=>{Ws(),ab.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>zw(e,r,n,s),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new zn(e.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(V.issue(o,r.value,t));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=r.value),i.inst??(i.inst=e),r.issues.push(V.issue(i))}};let s=t.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});Qc=$("ZodOptional",(e,t)=>{_d.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>lp(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});Up=$("ZodExactOptional",(e,t)=>{cb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>lp(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});qR=$("ZodNullable",(e,t)=>{ub.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Jw(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});ZR=$("ZodDefault",(e,t)=>{lb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Xw(e,r,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});JR=$("ZodPrefault",(e,t)=>{db.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>eR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});jp=$("ZodNonOptional",(e,t)=>{pb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Yw(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});XR=$("ZodSuccess",(e,t)=>{mb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Gw(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});eS=$("ZodCatch",(e,t)=>{fb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>tR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});rS=$("ZodNaN",(e,t)=>{gb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Mw(e,r,n,s)});Xc=$("ZodPipe",(e,t)=>{vd.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>rR(e,r,n,s),e.in=t.in,e.out=t.out});eu=$("ZodCodec",(e,t)=>{Xc.init(e,t),Tc.init(e,t)});nS=$("ZodPreprocess",(e,t)=>{Xc.init(e,t),hb.init(e,t)}),sS=$("ZodReadonly",(e,t)=>{yb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>nR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});iS=$("ZodTemplateLiteral",(e,t)=>{bb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Fw(e,r,n,s)});aS=$("ZodLazy",(e,t)=>{$c.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>oR(e,r,n,s),e.unwrap=()=>e._zod.def.getter()});uS=$("ZodPromise",(e,t)=>{Rb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>sR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});lS=$("ZodFunction",(e,t)=>{wb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>jw(e,r,n,s)});tu=$("ZodCustom",(e,t)=>{Sb.init(e,t),ge.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Uw(e,r,n,s)});tA=gw,rA=hw,mS=$("ZodInstanceOf",(e,t)=>{tu.init(e,t)},{properties(e,t){return this.check(bi(e,t))}});sA=(...e)=>yw({Codec:eu,Boolean:Ii,String:$i},...e)});function ej(e){Ye({customError:e})}function tj(){return Ye().customError}var XU,fS,aA=A(()=>{ar();XU={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};fS||(fS={})});var ru={};re(ru,{ZodISODate:()=>Jn,ZodISODateTime:()=>Kn,ZodISODuration:()=>Qn,ZodISOTime:()=>Yn,date:()=>nj,datetime:()=>rj,duration:()=>oj,time:()=>sj});function rj(e){return Fc(Kn,e)}function nj(e){return Nc(Jn,e)}function sj(e){return Gc(Yn,e)}function oj(e){return Uc(Qn,e)}var zp=A(()=>{ar();Xn();Xn()});function aj(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function cA(e,t){return e.map((r,n)=>n<t?r:r.optional())}function cj(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function uj(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let n=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===n){let s=r[1]===void 0?void 0:cj(r[1]);if(!s||!t.defs[s])throw new Error(`Reference not found: ${e}`);return t.defs[s]}throw new Error(`Reference not found: ${e}`)}function lj(e,t){return W.transform(n=>n).check(n=>{let s=n.value;if(typeof s!="object"||s===null||Array.isArray(s))return;let o=Object.getOwnPropertyNames(s);if(t.minProperties!==void 0&&o.length<t.minProperties&&n.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:s,inst:e,continue:!0}),t.maxProperties!==void 0&&o.length>t.maxProperties&&n.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:s,inst:e,continue:!0}),t.keySchema)for(let i of o){let a=t.keySchema.safeParse(i);a.success||n.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:i,path:[i],continue:!0})}}).pipe(e)}function gS(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let n=String(e);return`${r[0]}${n.length}:${n}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let o=[];for(let i of e){let a=gS(i,t);if(a===null)return null;o.push(a)}return`a${o.length}:[${o.join(",")}]`}let n=Object.keys(e).sort(),s=[];for(let o of n){let i=gS(e[o],t);if(i===null)return null;s.push(`${o.length}:${o}=${i}`)}return`o${s.length}:{${s.join(",")}}`}finally{t.delete(e)}}function nu(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(nu):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>dj.has(t)?nu(r):!pj.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(nu))}function uA(e){return e===1?"element":"elements"}function mj(e,t){return W.transform(n=>n).check(n=>{let s=n.value;if(Array.isArray(s)){if(t.uniqueItems===!0){let o=new Map;for(let i=0;i<s.length;i++){let a=gS(s[i],new Set);if(a===null)continue;let c=o.get(a);if(c===void 0){o.set(a,i);continue}n.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${c}`,input:s,path:[i],continue:!0})}}if(t.containsSchema){let o=t.minContains??1,i=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of s)if(t.containsSchema.safeParse(c).success&&++a>=i)break;a<o&&n.issues.push({code:"custom",message:`Array must contain at least ${o} matching ${uA(o)}; found ${a}`,input:s,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&n.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${uA(t.maxContains)}`,input:s,continue:!0})}}}).pipe(e)}function lA(e,t){if(e!==!1)return e===void 0||e===!0?W.any():Nt(e,t)}function dA(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return W.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let s=e.$ref;if(t.refs.has(s))return t.refs.get(s);if(t.processing.has(s))return W.lazy(()=>{if(!t.refs.has(s))throw new Error(`Circular reference not resolved: ${s}`);return t.refs.get(s)});t.processing.add(s);let o=uj(s,t),i=Nt(o,t);return t.refs.set(s,i),t.processing.delete(s),i}if(e.enum!==void 0){let s=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&s.length===1&&s[0]===null)return W.null();if(s.length===0)return W.never();if(s.length===1)return W.literal(s[0]);if(s.every(i=>typeof i=="string"))return W.enum(s);let o=s.map(i=>W.literal(i));return o.length<2?o[0]:W.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return W.literal(e.const);let r=e.type;if(Array.isArray(r)){let s=r.map(o=>{let i={...e,type:o};return dA(i,t)});return s.length===0?W.never():s.length===1?s[0]:W.union(s)}if(!r)return W.any();let n;switch(r){case"string":{let s=W.string();if(e.format){let o=e.format;o==="email"?s=s.check(W.email()):o==="uri"||o==="uri-reference"?s=s.check(W.url()):o==="uuid"||o==="guid"?s=s.check(W.uuid()):o==="date-time"?s=s.check(W.iso.datetime({offset:!0})):o==="date"?s=s.check(W.iso.date()):o==="time"?s=s.check(W.regex(fj)):o==="duration"?s=s.check(W.iso.duration()):o==="hostname"?s=s.check(W.hostname()):o==="ipv4"?s=s.check(W.ipv4()):o==="ipv6"?s=s.check(W.ipv6()):o==="mac"?s=s.check(W.mac()):o==="cidr"?s=s.check(W.cidrv4()):o==="cidr-v6"?s=s.check(W.cidrv6()):o==="base64"?s=s.check(W.base64()):o==="base64url"?s=s.check(W.base64url()):o==="e164"?s=s.check(W.e164()):o==="credit_card"?s=s.check(W.creditCard()):o==="iban"?s=s.check(W.iban()):o==="jwt"?s=s.check(W.jwt()):o==="emoji"?s=s.check(W.emoji()):o==="nanoid"?s=s.check(W.nanoid()):o==="cuid"?s=s.check(W.cuid()):o==="cuid2"?s=s.check(W.cuid2()):o==="ulid"?s=s.check(W.ulid()):o==="xid"?s=s.check(W.xid()):o==="ksuid"&&(s=s.check(W.ksuid()))}typeof e.minLength=="number"&&(s=s.min(e.minLength)),typeof e.maxLength=="number"&&(s=s.max(e.maxLength)),e.pattern&&(s=s.regex(new RegExp(e.pattern))),n=s;break}case"number":case"integer":{let s=r==="integer"?W.number().int():W.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(s=s.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(s=s.max(e.maximum)),typeof e.exclusiveMinimum=="number"?s=s.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(s=s.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?s=s.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(s=s.lt(e.maximum)),typeof e.multipleOf=="number"&&(s=s.multipleOf(e.multipleOf)),n=s;break}case"boolean":{n=W.boolean();break}case"null":{n=W.null();break}case"object":{let s={},o=e.properties||{},i=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?Nt(e.additionalProperties,t):void 0;for(let[p,m]of Object.entries(o)){let f=Nt(m,t);St(s,p,i.has(p)?f:f.optional())}if(e.patternProperties){let p=e.patternProperties,m=Object.keys(p),f=[];for(let h of m){let b=Nt(p[h],t),w=W.string().regex(new RegExp(h));f.push(W.looseRecord(w,b))}let g=[];if(Object.keys(s).length>0&&g.push(W.object(s).passthrough()),g.push(...f),g.length===0)n=W.object({}).passthrough();else if(g.length===1)n=g[0];else{let h=W.intersection(g[0],g[1]);for(let b=2;b<g.length;b++)h=W.intersection(h,g[b]);n=h}if(e.additionalProperties===!1){let h=Object.keys(s),b=m.map(y=>new RegExp(y)),w=n;n=n.check(y=>{if(!br(y.value))return;let S=[];for(let k of Object.keys(y.value))h.includes(k)||b.some(R=>R.test(k))||S.push(k);S.length&&y.issues.push({code:"unrecognized_keys",keys:S,input:y.value,inst:w})})}}else{let p=W.object(s);e.additionalProperties===!1?n=p.strict():a?n=p.catchall(a):n=p.passthrough()}let c=e.propertyNames!==void 0&&e.propertyNames!==!0,u=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(c||u!==void 0||d!==void 0){let p;if(c){let m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=Nt(m,t)}n=lj(n,{keySchema:p,minProperties:u,maxProperties:d})}break}case"array":{let s=e.prefixItems,o=e.items;if(s&&Array.isArray(s)){let i=typeof e.minItems=="number"?e.minItems:0,a=s.map(p=>Nt(p,t)),c=cA(a,i),u=Array.isArray(o)?void 0:lA(o,t),d=W.tuple(c);n=u?d.rest(u):d,typeof e.minItems=="number"&&(n=n.check(W.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(W.maxLength(e.maxItems)))}else if(Array.isArray(o)){let i=typeof e.minItems=="number"?e.minItems:0,a=o.map(p=>Nt(p,t)),c=cA(a,i),u=lA(e.additionalItems,t),d=W.tuple(c);n=u?d.rest(u):d,typeof e.minItems=="number"&&(n=n.check(W.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(W.maxLength(e.maxItems)))}else if(o!==void 0){let i=Nt(o,t),a=W.array(i);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),n=a}else n=W.array(W.any());(e.uniqueItems===!0||e.contains!==void 0)&&(n=mj(n,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?Nt(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return n}function Nt(e,t){if(typeof e=="boolean")return e?W.any():W.never();let r=dA(e,t),n=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(u=>Nt(u,t)),c=W.union(a);r=n?W.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(u=>Nt(u,t)),c=W.xor(a);r=n?W.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=n?r:W.any();else{let a=n?r:Nt(e.allOf[0],t),c=n?0:1;for(let u=c;u<e.allOf.length;u++)a=W.intersection(a,Nt(e.allOf[u],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=W.nullable(r)),e.readOnly===!0&&(r=W.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let s={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of o)a in e&&(s[a]=e[a]);let i=["contentEncoding","contentMediaType","contentSchema"];for(let a of i)a in e&&(s[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!nu(e.propertyNames)&&(s.propertyNames=e.propertyNames);for(let a of["minProperties","maxProperties"])e[a]!==void 0&&(s[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!nu(e.contains)&&(s.contains=e.contains);for(let a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(s[a]=e[a])}for(let a of Object.keys(e))ij.has(a)||St(s,a,e[a]);return Object.keys(s).length>0&&t.registry.add(r,s),e.description&&(r=r.describe(e.description)),r}function pA(e,t){if(typeof e=="boolean")return e?W.any():W.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let n=aj(r,t?.defaultTarget),s=r.$defs||r.definitions||{},o={version:n,defs:s,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??_t};return Nt(r,o)}var W,ij,dj,pj,fj,mA=A(()=>{Lc();rt();fp();zp();Xn();W={...Li,...mp,iso:ru},ij=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);dj=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),pj=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);fj=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/});function su(e,t){let r=typeof t=="function"?t:(i,a)=>{let c=t[i._zod.def.type];return c?c(i,a):i},n=new Map;function s(i){let a=n.get(i);if(a===fA)return new $c({type:"lazy",getter:()=>n.get(i)});if(a!==void 0)return a;n.set(i,fA);let c=o(i),u=r(c,c!==i);return n.set(i,u),u}function o(i){let a=i._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,d=Object.keys(u),p=!1,m={};for(let g of d){let h=s(u[g]);h!==u[g]&&(p=!0),m[g]=h}let f=a.catchall;return a.catchall&&(f=s(a.catchall),f!==a.catchall&&(p=!0)),p?Oe(i,{...a,shape:m,catchall:f}):i}case"array":{let u=s(a.element);return u===a.element?i:Oe(i,{...a,element:u})}case"tuple":{let u=a.items,d=!1,p=[];for(let f of u){let g=s(f);g!==f&&(d=!0),p.push(g)}let m=a.rest;return a.rest&&(m=s(a.rest),m!==a.rest&&(d=!0)),d?Oe(i,{...a,items:p,rest:m}):i}case"record":case"map":{let u=s(a.keyType),d=s(a.valueType);return u===a.keyType&&d===a.valueType?i:Oe(i,{...a,keyType:u,valueType:d})}case"set":{let u=s(a.valueType);return u===a.valueType?i:Oe(i,{...a,valueType:u})}case"union":{let u=a.options,d=!1,p=[];for(let m of u){let f=s(m);f!==m&&(d=!0),p.push(f)}return d?Oe(i,{...a,options:p}):i}case"intersection":{let u=s(a.left),d=s(a.right);return u===a.left&&d===a.right?i:Oe(i,{...a,left:u,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=s(a.innerType);return u===a.innerType?i:Oe(i,{...a,innerType:u})}case"pipe":{let u=s(a.in),d=s(a.out);return u===a.in&&d===a.out?i:Oe(i,{...a,in:u,out:d})}case"function":{let u=s(a.input),d=s(a.output);return u===a.input&&d===a.output?i:Oe(i,{...a,input:u,output:d})}case"lazy":{let u=a.getter,{_cachedInner:d,...p}=a;return Oe(i,{...p,getter:()=>s(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return i;default:return i}}return s(e)}var fA,hS=A(()=>{ui();rt();fA=Symbol("z.visit/resolving")});function gA(e){return su(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:Di(r.options)}})}var hA=A(()=>{hS();Xn()});function gj(e,t){if(!t?.length)return e;let r=e._zod.def;return Oe(e,Cr(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function yA(e){return gj(e.out,e.checks)}function hj(e){return e.in._zod.traits.has("$ZodTransform")?yA(e):e.in}function bA(e){return su(e,{pipe:t=>hj(t._zod.def),default:(t,r)=>r?Hs(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function wA(e){return su(e,{pipe:t=>yA(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var RA=A(()=>{rt();hS();Xn()});var yS={};re(yS,{bigint:()=>Rj,boolean:()=>wj,date:()=>Sj,number:()=>bj,string:()=>yj});function yj(e){return Mb($i,e)}function bj(e){return zb(Oi,e)}function wj(e){return Kb(Ii,e)}function Rj(e){return Yb(xi,e)}function Sj(e){return cw(Zc,e)}var SA=A(()=>{ar();Xn()});var l={};re(l,{$brand:()=>Jg,$input:()=>Ab,$output:()=>Eb,INVALID:()=>Mt,NEVER:()=>Kg,TimePrecision:()=>Ub,ZodAny:()=>TR,ZodArray:()=>xR,ZodBase64:()=>Ip,ZodBase64URL:()=>xp,ZodBigInt:()=>xi,ZodBigIntFormat:()=>Mp,ZodBoolean:()=>Ii,ZodCIDRv4:()=>$p,ZodCIDRv6:()=>Op,ZodCUID:()=>vp,ZodCUID2:()=>kp,ZodCatch:()=>eS,ZodCodec:()=>eu,ZodCompileAsyncError:()=>Pr,ZodCompileUnsupportedError:()=>Se,ZodCreditCard:()=>SR,ZodCustom:()=>tu,ZodCustomStringFormat:()=>Vs,ZodDate:()=>Zc,ZodDefault:()=>ZR,ZodDiscriminatedUnion:()=>LR,ZodE164:()=>Dp,ZodEmail:()=>wp,ZodEmoji:()=>Sp,ZodEnum:()=>Ti,ZodError:()=>JU,ZodExactOptional:()=>Up,ZodFile:()=>HR,ZodFirstPartyTypeKind:()=>fS,ZodFunction:()=>lS,ZodGUID:()=>Rp,ZodIBAN:()=>_R,ZodIPv4:()=>Ap,ZodIPv6:()=>Tp,ZodISODate:()=>Jn,ZodISODateTime:()=>Kn,ZodISODuration:()=>Qn,ZodISOTime:()=>Yn,ZodInstanceOf:()=>mS,ZodIntersection:()=>MR,ZodIssueCode:()=>XU,ZodJWT:()=>Lp,ZodKSUID:()=>Ep,ZodLazy:()=>aS,ZodLiteral:()=>BR,ZodMAC:()=>RR,ZodMap:()=>jR,ZodNaN:()=>rS,ZodNanoID:()=>_p,ZodNever:()=>OR,ZodNonOptional:()=>jp,ZodNull:()=>ER,ZodNullable:()=>qR,ZodNumber:()=>Oi,ZodNumberFormat:()=>qs,ZodObject:()=>Jc,ZodOptional:()=>Qc,ZodPipe:()=>Xc,ZodPrefault:()=>JR,ZodPreprocess:()=>nS,ZodPromise:()=>uS,ZodReadonly:()=>sS,ZodRealError:()=>Jt,ZodRecord:()=>Ai,ZodSet:()=>zR,ZodString:()=>$i,ZodStringFormat:()=>Le,ZodSuccess:()=>XR,ZodSymbol:()=>CR,ZodTemplateLiteral:()=>iS,ZodTransform:()=>WR,ZodTuple:()=>NR,ZodType:()=>ge,ZodULID:()=>Cp,ZodURL:()=>qc,ZodUUID:()=>Br,ZodUndefined:()=>PR,ZodUnion:()=>Yc,ZodUnknown:()=>$R,ZodVoid:()=>IR,ZodXID:()=>Pp,ZodXor:()=>DR,_ZodString:()=>bp,_default:()=>KR,_function:()=>QE,any:()=>TE,array:()=>Kc,base64:()=>uE,base64url:()=>lE,bigint:()=>kE,boolean:()=>kR,catch:()=>tS,check:()=>XE,cidrv4:()=>aE,cidrv6:()=>cE,clone:()=>Oe,codec:()=>ZE,coerce:()=>yS,compile:()=>Ib,config:()=>Ye,core:()=>fn,creditCard:()=>pE,cuid:()=>XP,cuid2:()=>eE,currencyCode:()=>bE,custom:()=>eA,date:()=>OE,decode:()=>pR,decodeAsync:()=>fR,deepPartial:()=>gA,describe:()=>tA,discriminatedUnion:()=>FE,e164:()=>dE,email:()=>BP,emoji:()=>YP,encode:()=>dR,encodeAsync:()=>mR,endsWith:()=>yi,enum:()=>Np,exactOptional:()=>VR,file:()=>HE,flattenError:()=>fc,float32:()=>RE,float64:()=>SE,formatError:()=>gc,fromJSONSchema:()=>pA,function:()=>QE,getDiscriminatedOption:()=>Qy,getErrorMap:()=>tj,globalRegistry:()=>_t,gt:()=>jr,gte:()=>ir,guid:()=>HP,hash:()=>wE,hex:()=>yE,hostname:()=>hE,httpUrl:()=>JP,iban:()=>mE,includes:()=>gi,input:()=>bA,instanceof:()=>nA,int:()=>hp,int32:()=>_E,int64:()=>CE,intersection:()=>FR,invertCodec:()=>KE,ipv4:()=>sE,ipv6:()=>iE,iso:()=>ru,json:()=>oA,jwt:()=>fE,keyof:()=>IE,ksuid:()=>nE,lazy:()=>cS,length:()=>js,literal:()=>BE,locales:()=>Dc,looseObject:()=>LE,looseRecord:()=>GE,lowercase:()=>mi,lt:()=>Ur,lte:()=>or,mac:()=>oE,map:()=>UE,maxLength:()=>Us,maxSize:()=>Wn,memoizer:()=>xc,meta:()=>rA,mime:()=>wi,minLength:()=>mn,minSize:()=>zr,multipleOf:()=>Hn,nan:()=>qE,nanoid:()=>QP,nativeEnum:()=>zE,negative:()=>sp,never:()=>Fp,nonnegative:()=>ip,nonoptional:()=>QR,nonpositive:()=>op,normalize:()=>Ri,null:()=>AR,nullable:()=>Vc,nullish:()=>WE,number:()=>vR,object:()=>xE,optional:()=>Hs,output:()=>wA,overwrite:()=>Er,parse:()=>aR,parseAsync:()=>cR,partialRecord:()=>NE,pipe:()=>yp,positive:()=>np,prefault:()=>YR,preprocess:()=>iA,prettifyError:()=>th,promise:()=>YE,properties:()=>bi,property:()=>ap,readonly:()=>oS,record:()=>UR,refine:()=>dS,regex:()=>pi,regexes:()=>Rr,registry:()=>Id,safeDecode:()=>hR,safeDecodeAsync:()=>bR,safeEncode:()=>gR,safeEncodeAsync:()=>yR,safeParse:()=>uR,safeParseAsync:()=>lR,set:()=>jE,setErrorMap:()=>ej,size:()=>Gs,slugify:()=>ki,startsWith:()=>hi,strictObject:()=>DE,string:()=>Wc,stringFormat:()=>gE,stringbool:()=>sA,success:()=>VE,superRefine:()=>pS,symbol:()=>EE,templateLiteral:()=>JE,toJSONSchema:()=>dp,toLowerCase:()=>_i,toUpperCase:()=>vi,toZod:()=>sc,transform:()=>Gp,treeifyError:()=>eh,trim:()=>Si,tuple:()=>GR,uint32:()=>vE,uint64:()=>PE,ulid:()=>tE,undefined:()=>AE,union:()=>Di,unknown:()=>Bs,uppercase:()=>fi,url:()=>KP,util:()=>V,uuid:()=>WP,uuidv4:()=>VP,uuidv6:()=>qP,uuidv7:()=>ZP,validate:()=>hc,validateAsync:()=>yc,void:()=>$E,withParser:()=>xd,xid:()=>rE,xor:()=>ME});var bS=A(()=>{ar();Xn();fp();iR();wR();aA();ar();Hc();mA();hA();RA();Pb();zp();zp();SA()});var ou=A(()=>{bS();bS()});function kA({author:e,comments:t}){let r=t.filter(n=>!n.isBot&&n.author===e).map(n=>n.body);return r.some(n=>Cj.some(s=>s.test(n)))?"superseded":r.some(n=>Pj.test(n))?"no-traction":t.some(n=>!n.isBot&&n.author!==e)?"after-feedback":"no-response"}function CA({author:e,closer:t,closerIsBot:r,comments:n}){let s=n.filter(o=>!o.isBot&&o.author!==e).map(o=>o.body);return s.some(o=>_j.test(o))?"ai-policy":s.some(o=>vj.test(o))?"superseded":r||s.some(o=>kj.test(o))?"stale":t?t===e?"self-closed":"rejected":"unknown"}var _A,vA,_j,vj,kj,Cj,Pj,wS=A(()=>{"use strict";_A=["ai-policy","superseded","stale","self-closed","rejected","unknown"],vA=["superseded","no-traction","after-feedback","no-response"],_j=/\b(?:AI|LLM)[- ](?:generated|written|authored|slop|polic(?:y|ies))|(?:generated|written) (?:by|with) (?:an? )?(?:AI|LLM|ChatGPT|Copilot)\b|vibe[- ]?cod|machine[- ]generated/i,vj=/clos(?:e|ing) (?:this )?as (?:a )?duplicate|duplicate of #\d+|superseded by|already (?:been )?(?:fixed|merged|addressed|resolved|implemented)|fixed (?:in|by|via) #\d+|in favou?r of #\d+/i,kj=/marked as stale|clos(?:e|ing) (?:this )?(?:as|due to) (?:stale|inactiv)|no activity (?:for|in)/i,Cj=[/already (?:been )?(?:fixed|merged|addressed|resolved|implemented|landed|applied|several)/i,/cover(?:s|ed) (?:this|everything|the same)|same (?:one-line )?fix|(?:landed|fixed|ships?) the same/i,/has (?:landed|shipped)|is in and|(?:fixed|addressed|resolved|landed|applied) (?:upstream|elsewhere)/i,/upstream (?:upgrade|commit|fix)|supersed|in favou?r of|replaced by|duplicate/i,/no longer (?:needed|relevant|reproduc|applies)/i],Pj=/traction|(?:been )?quiet|unmaintained|actively (?:reviewing|maintained)|not maintained|no (?:response|activity)|keep the queue tidy|sitting in (?:your|the) queue|stale/i});function Mi(e){return l.custom(t=>typeof t=="string")}function Hj(e){let t=e?.openPRs;return!Array.isArray(t)||t.length===0?e:{...e,needsAddressingPRs:t.filter(r=>r?.status==="needs_addressing"),waitingOnMaintainerPRs:t.filter(r=>r?.status==="waiting_on_maintainer")}}function TA(e,t){let r=e!==null&&typeof e=="object"?e.workClaims:void 0;return Array.isArray(r)?Math.max(0,r.length-t.workClaims.length):0}function Hp(e){if(!e||typeof e!="object")return[];let t=new Set(Object.keys(Gt.shape));return Object.keys(e).filter(r=>!t.has(r))}var Ej,SS,_S,vS,kS,Aj,Tj,EA,AA,$j,Oj,Ij,xj,Dj,Lj,Mj,Fj,PA,Nj,Bp,Gj,Uj,jj,zj,Bj,RS,Wj,Vj,qj,Zj,Kj,CS,PS,Zs,Jj,Gt,Wp,gn=A(()=>{"use strict";ou();wS();Ej=l.enum(["candidate","claimed","in_progress","pr_submitted"]),SS=l.enum(["needs_addressing","waiting_on_maintainer"]),_S=l.enum(["nonprofit","devtools","infrastructure","web-frameworks","data-ml","education"]),vS=l.enum(["beginner","intermediate","advanced"]),kS=l.enum(["inline","sourcetree","vscode","custom"]),Aj=l.object({hasActiveMaintainers:l.boolean(),isResponsive:l.boolean(),hasHostileComments:l.boolean()}),Tj=l.object({repo:l.string(),score:l.number(),mergedPRCount:l.number(),closedWithoutMergeCount:l.number(),avgResponseDays:l.number().nullable(),lastMergedAt:l.string().optional(),lastEvaluatedAt:l.string(),signals:Aj,stargazersCount:l.number().optional(),language:l.string().nullable().optional()}).passthrough(),EA=l.object({issueUrl:l.string(),grade:l.number(),recommendation:l.string(),stargazersCount:l.number().optional(),source:Mi(["vet","vet-list","list"]),capturedAt:l.string().optional(),labels:l.array(l.string()).optional(),issueAuthorAssociation:Mi(["OWNER","MEMBER","COLLABORATOR","CONTRIBUTOR","FIRST_TIMER","FIRST_TIME_CONTRIBUTOR","MANNEQUIN","NONE"]).optional(),issueAuthorIsBot:l.boolean().optional(),competingPRs:l.number().optional(),mentioningPRs:l.number().optional(),firstInRepo:l.boolean().optional(),commentCount:l.number().optional()}).passthrough(),AA={issueUrl:l.string().optional(),pick:EA.optional(),lastReviewDecision:l.string().optional(),lastCiStatus:l.string().optional(),backfilledAt:l.string().optional(),responseRule:l.number().int().optional()},$j=l.object({url:l.string(),title:l.string(),mergedAt:l.string(),openedAt:l.string().optional(),firstMaintainerResponseAt:l.string().optional(),commentsFetchedAt:l.string().datetime().optional(),learningsExtractedAt:l.string().datetime().optional(),...AA}).passthrough(),Oj=l.object({url:l.string(),title:l.string(),closedAt:l.string(),openedAt:l.string().optional(),firstMaintainerResponseAt:l.string().optional(),commentsFetchedAt:l.string().datetime().optional(),learningsExtractedAt:l.string().datetime().optional(),...AA,closeReason:Mi(_A).optional(),selfCloseReason:Mi(vA).optional()}).passthrough(),Ij=l.object({url:l.string(),repo:l.string(),analyzedAt:l.string()}),xj=l.object({tier:l.enum(["light_check_in","direct_check_in","final_check_in"]),timestamp:l.string().datetime(),draftPath:l.string().optional()}),Dj=l.object({workflowName:l.enum(["draft-first","work-through-issues","pre-commit-review"]),currentStep:l.string(),branchName:l.string().optional(),issueContext:l.object({title:l.string(),url:l.string()}).optional(),completedSteps:l.array(l.string()).default([]),stepData:l.record(l.string(),l.unknown()).default({}),lastUpdatedAt:l.string().datetime()}),Lj=l.object({branchNamingConvention:l.string().optional(),commitMessageFormat:l.string().optional(),prTitleFormat:l.string().optional(),requiredChecks:l.array(l.string()).optional(),testFramework:l.string().optional(),testCoverageRequired:l.boolean().optional(),testFileNaming:l.string().optional(),linter:l.string().optional(),formatter:l.string().optional(),styleGuideUrl:l.string().optional(),issueClaimProcess:l.string().optional(),reviewProcess:l.string().optional(),claRequired:l.boolean().optional(),rawContent:l.string().optional()}),Mj=l.object({passedAllChecks:l.boolean(),checks:l.object({noExistingPR:l.boolean(),notClaimed:l.boolean(),projectActive:l.boolean(),clearRequirements:l.boolean(),contributionGuidelinesFound:l.boolean()}),contributionGuidelines:Lj.optional(),notes:l.array(l.string())}),Fj=l.object({id:l.number(),url:l.string(),repo:l.string(),number:l.number(),title:l.string(),status:Ej,labels:l.array(l.string()),createdAt:l.string(),updatedAt:l.string(),vetted:l.boolean(),vettingResult:Mj.optional()}),PA=l.object({number:l.number(),url:l.string(),title:l.string(),repo:l.string(),daysSinceActivity:l.number(),status:SS}),Nj=l.object({status:SS,setAt:l.string(),lastActivityAt:l.string()}),Bp=l.object({setupComplete:l.boolean().default(!1),setupCompletedAt:l.string().optional(),persistence:l.enum(["local","gist"]).default("local"),maxActivePRs:l.number().default(10),maxOpenPRsPerRepo:l.number().int().min(0).default(0),maxOpenPRsColdRepo:l.number().int().min(0).default(1),maxConcurrentImplementations:l.number().int().min(0).default(2),dormantThresholdDays:l.number().default(30),approachingDormantDays:l.number().default(25),maxIssueAgeDays:l.number().default(90),skipBroadWhenSufficientResults:l.number().min(0).default(8),languages:l.array(l.string()).default(["typescript","javascript"]),labels:l.array(l.string()).default(["good first issue","help wanted"]),scope:l.array(vS).optional(),excludeRepos:l.array(l.string()).default([]),excludeOrgs:l.array(l.string()).optional(),untrackedOrgs:l.array(l.string()).default([]),avoidRepos:l.array(l.string()).default([]),boostIssueTypes:l.array(l.string()).default([]),trustedProjects:l.array(l.string()).default([]),githubUsername:l.string().default(""),minRepoScoreThreshold:l.number().default(4),starredRepos:l.array(l.string()).default([]),starredReposLastFetched:l.string().optional(),squashByDefault:l.union([l.boolean(),l.literal("ask")]).default(!0),localRepoScanPaths:l.array(l.string()).optional(),minStars:l.number().default(50),includeDocIssues:l.boolean().default(!0),aiPolicyBlocklist:l.array(l.string()).default(["matplotlib/matplotlib"]),shelvedPRUrls:l.array(l.string()).default([]),dismissedIssues:l.record(l.string(),l.string()).default({}),dismissedPRHeads:l.record(l.string(),l.string()).default({}),statusOverrides:l.record(l.string(),Nj).optional(),issueListPath:l.string().optional(),skippedIssuesPath:l.string().optional(),projectCategories:l.array(_S).default([]),preferredOrgs:l.array(l.string()).default([]),diffTool:kS.default("inline"),diffToolCustomCommand:l.string().optional(),autoExtractLearnings:l.boolean().default(!0),autoFormatBeforePush:l.boolean().default(!1),trustOwnRepoWrites:l.boolean().default(!1),healthCheckFreshnessMinutes:l.number().int().positive().default(30),reviewMaxPasses:l.number().int().positive().optional(),slmTriageModel:l.string().default(""),slmTriageHost:l.string().default("")}).passthrough().transform(({snoozedPRs:e,...t})=>t),Gj=l.object({repos:l.record(l.string(),l.object({path:l.string(),exists:l.boolean(),currentBranch:l.string().nullable()})),scanPaths:l.array(l.string()),cachedAt:l.string()}),Uj=l.object({url:l.string(),repo:l.string(),number:l.number(),title:l.string(),closedAt:l.string(),closedBy:l.string().optional(),openedAt:l.string().optional(),issueUrl:l.string().optional()}),jj=l.object({url:l.string(),repo:l.string(),number:l.number(),title:l.string(),mergedAt:l.string(),openedAt:l.string().optional(),issueUrl:l.string().optional()}),zj=l.object({totalActivePRs:l.number(),totalNeedingAttention:l.number(),totalMergedAllTime:l.number(),mergeRate:l.number()}),Bj=l.object({url:l.string(),repo:l.string(),number:l.number(),status:SS}).passthrough(),RS=l.array(Bj);Wj=l.object({generatedAt:l.string(),openPRs:RS,needsAddressingPRs:RS,waitingOnMaintainerPRs:RS,recentlyClosedPRs:l.array(Uj),recentlyMergedPRs:l.array(jj),shelvedPRs:l.array(PA),autoUnshelvedPRs:l.array(PA),summary:zj}),Vj=l.preprocess(Hj,Wj),qj=l.object({url:l.string(),lastSeenAt:l.string()}),Zj=l.object({url:l.string(),branch:l.string(),worktree:l.string().optional(),note:l.string().optional(),recordedAt:l.string(),pushedRef:l.string().optional(),pushedAt:l.string().optional(),compareUrl:l.string().optional(),pushProblem:l.string().optional()}).passthrough(),Kj=l.object({url:l.string(),attemptedAt:l.string(),outcome:l.enum(["prepared","blocked"]),note:l.string().optional()}).passthrough(),CS=l.object({runAt:l.string(),reportPath:l.string(),prepareCount:l.number().int().nonnegative(),judgmentCount:l.number().int().nonnegative(),prepared:l.array(Zj).default([]),implementUrl:l.string().optional(),implementAttempts:l.array(Kj).optional()}).passthrough(),PS=l.object({languageOffset:l.number().int().nonnegative().default(0),phase0Offset:l.number().int().nonnegative().default(0),starredOffset:l.number().int().nonnegative().default(0),maintainedOffset:l.number().int().nonnegative().default(0),strategyOffset:l.number().int().nonnegative().default(0),lastRotatedAt:l.string().optional()}).passthrough(),Zs=l.object({kind:Mi(["implementation","pr"]),url:l.string(),session:l.string(),startedAt:l.string(),expiresAt:l.string(),status:Mi(["running","finished"]),branch:l.string().optional(),worktree:l.string().optional(),host:l.string().optional(),machineId:l.string().optional(),runId:l.string().optional(),finishedAt:l.string().optional()}).loose(),Jj=l.array(l.unknown()).default([]).transform(e=>e.flatMap(t=>{let r=Zs.safeParse(t);return r.success?[r.data]:[]}));Gt=l.object({version:l.literal(4),gistId:l.string().optional(),repoScores:l.record(l.string(),Tj).default({}),config:Bp.default(()=>Bp.parse({})),lastRunAt:l.string().default(()=>new Date().toISOString()),lastDigestAt:l.string().optional(),lastStrategyAt:l.string().optional(),lastDigest:Vj.optional(),monthlyMergedCounts:l.record(l.string(),l.number()).optional(),monthlyClosedCounts:l.record(l.string(),l.number()).optional(),monthlyOpenedCounts:l.record(l.string(),l.number()).optional(),localRepoCache:Gj.optional(),mergedPRs:l.array($j).optional(),closedPRs:l.array(Oj).optional(),analyzedIssueConversations:l.array(Ij).optional(),activeIssues:l.array(Fj).default([]),prFollowUpHistory:l.record(l.string(),l.array(xj)).optional(),workflowState:Dj.optional(),searchSeen:l.array(qj).default([]),pickSnapshots:l.array(EA).default([]),lastOvernight:CS.optional(),searchRotation:PS.optional(),workClaims:Jj}).passthrough();Wp="was written by a different oss-autopilot release (usually a newer one); this version keeps those fields but cannot use them. If you are not on the latest release, update with `claude plugin update oss-autopilot@oss-autopilot` and restart Claude Code."});function ES(e,t){return Yj.test(e)&&Qj.test(t)}function q(e){if(!e.startsWith("https://github.com/"))return null;let t=e.match(/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/);if(t){let n=t[1],s=t[2];return ES(n,s)?{owner:n,repo:s,number:parseInt(t[3],10),type:"pull"}:null}let r=e.match(/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+)/);if(r){let n=r[1],s=r[2];return ES(n,s)?{owner:n,repo:s,number:parseInt(r[3],10),type:"issues"}:null}return null}function We(e){let t=q(e);return t?`${t.owner.toLowerCase()}/${t.repo.toLowerCase()}#${t.number}`:null}function Hr(e){if(!e.startsWith("https://github.com/"))return null;let t=e.match(/github\.com\/([^/]+)\/([^/]+)/);if(!t)return null;let r=t[1],n=t[2];return ES(r,n)?{owner:r,repo:n}:null}function Ks(e){let[t,r]=e.split("/",2);if(!t||!r)throw new Error(`Invalid repo format: expected "owner/repo", got "${e}"`);return{owner:t,repo:r}}function Sr(e,t){return e.toLowerCase()===t.toLowerCase()}function Fi(e,t=[]){let r=e.toLowerCase();return t.some(n=>n.toLowerCase()===r)}var Yj,Qj,nt=A(()=>{"use strict";Yj=/^[\w-]+$/,Qj=/^[\w.-]+$/});function Yt(e){return We(e)??e.trim().toLowerCase()}function AS(e,t=Date.now()){let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&r>t}function cr(e,t=Date.now()){return e.filter(r=>AS(r,t))}function Js(e,t,r=Date.now()){let n=Yt(t);return cr(e,r).find(s=>Yt(s.url)===n)}function qp(e,t,r,n=Date.now()){let s=Js(e,t,n);if(!(s===void 0||s.session===r))return s}function Zp(e,t){let r=new Date(Date.parse(t)+au*36e5),n=Date.parse(e.expiresAt),s=Number.isFinite(n)&&n>r.getTime()?e.expiresAt:r.toISOString();return{...e,status:"finished",finishedAt:t,expiresAt:s}}function Kp(e,t=Date.now()){return cr(e,t).filter(r=>r.kind==="implementation"&&r.status==="finished")}function xA(e,t=Date.now()){return cr(e,t).filter(r=>r.kind==="implementation"&&r.status==="running")}function Ni(e){return IA.default.resolve(e.trim())}function Xj(e,t){return e===void 0||t===void 0||e===t}function $A(e){try{return OA.realpathSync(e)}catch{return e}}function ez(e,t,r){if(!e.worktree)return!1;let n=Ni(e.worktree);return e.machineId!==void 0&&r.machineId!==void 0?e.machineId!==r.machineId?!1:$A(n)===$A(t):Xj(e.host,r.host)&&n===t}function Jp(e,t,r,n=Date.now()){let s=Yt(t.url),o=cr(e,n).filter(a=>a.kind==="implementation"&&Yt(a.url)!==s);if(t.worktree!==void 0){let a=Ni(t.worktree),c=o.filter(u=>ez(u,a,t));if(c.length>0){let u=c[0];return{reason:"worktree",blocking:c,message:`Checkout ${a} already hosts an implementation of ${u.url} (session ${u.session}, ${u.status}). Use a separate worktree, or finish or release that claim first.`}}}let i=o.filter(a=>a.status==="running");if(r>0&&i.length>=r){let a=i.map(c=>`${c.url} (session ${c.session})`).join(", ");return{reason:"cap",blocking:i,message:`Implementation cap reached: ${i.length} of ${r} running (${a}). Collect or release one, or raise it with \`setup --set maxConcurrentImplementations=N\`.`}}return null}function TS(e,t=Date.now()){let r=Date.parse(e.startedAt),n=Number.isFinite(r)?Math.max(0,Math.floor((t-r)/6e4)):0;return n<60?`${n} min`:n<1440?`${Math.floor(n/60)} h`:`${Math.floor(n/1440)} d`}function cu(e,t=Date.now()){return`${e.kind} claimed in session ${e.session} (${TS(e,t)}, ${e.status})`}function Gi(e,t,r=Date.now()){let n=Js(e,t,r);return!n||n.kind!=="implementation"?null:{recommendation:"skip",reasonsToSkip:[`Already being implemented: ${cu(n,r)}`],workClaim:n}}var OA,IA,Vp,iu,au,$S=A(()=>{"use strict";OA=B(require("node:fs"),1),IA=B(require("node:path"),1);nt();Vp={implementation:24,pr:12},iu=168,au=168});function rz(e){let t=e.lastDigest,r=[...t?.openPRs??[],...t?.shelvedPRs??[],...e.activeIssues].map(i=>i.repo),s=[...(e.mergedPRs??[]).map(i=>i.url),...(e.closedPRs??[]).map(i=>i.url),...e.config.shelvedPRUrls??[]].flatMap(i=>{let a=q(i);return a?[`${a.owner}/${a.repo}`]:[]}),o=new Set(r);for(let i of s)o.add(i);return o}function nz(e,t=Date.now()){let r=t-uu*DA,n=e.searchSeen.filter(c=>Date.parse(c.lastSeenAt)>=r),s=t-tz*DA,o=rz(e),i=Object.fromEntries(Object.entries(e.repoScores).filter(([c,u])=>{let d=u.mergedPRCount>0||u.closedWithoutMergeCount>0,p=Date.parse(u.lastEvaluatedAt),m=Number.isNaN(p)||p>=s;return d||o.has(c)||m})),a=e.lastDigest&&{...e.lastDigest,needsAddressingPRs:[],waitingOnMaintainerPRs:[]};return{...e,searchSeen:n,repoScores:i,lastDigest:a}}function Ar(e){return JSON.stringify(nz(e))}var DA,OS,uu,tz,Ui=A(()=>{"use strict";nt();DA=1440*60*1e3,OS=7,uu=OS+1,tz=14});function sz(){try{return Yp.userInfo().homedir}catch{return null}}function Qp(){let e=Yp.homedir(),t=process.env.VITEST?sz():null;if(t!==null&&yt.resolve(e)===yt.resolve(t))throw new Error(`Refusing to use the real home directory (${e}) under vitest`);return yt.join(e,".oss-autopilot")}function ur(){let e=Qp();return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function jt(){return yt.join(ur(),"state.json")}function LA(){return yt.join(process.cwd(),"data","state.json")}function MA(){return yt.join(process.cwd(),"data","backups")}function Ys(){let e=yt.join(ur(),"backups");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function Xp(){let e=yt.join(ur(),"cache");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function ji(){let e=yt.join(ur(),"reports");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function Qs(){return yt.join(ur(),"gist-id")}function FA(){return yt.join(ur(),"machine-id")}function es(){return yt.join(ur(),"state-cache.json")}function em(){return Ut.existsSync(yt.join(Qp(),"state.json"))}function Wr(){return"3.40.2"}var Ut,yt,Yp,Vr=A(()=>{"use strict";Ut=B(require("node:fs"),1),yt=B(require("node:path"),1),Yp=B(require("node:os"),1)});function rm(){tm=!0}function NA(){return tm}function O(e,t,...r){if(!tm)return;let n=new Date().toISOString();console.error(`[${n}] [DEBUG] [${e}] ${t}`,...r)}function GA(e,t,...r){let n=new Date().toISOString();console.error(`[${n}] [INFO] [${e}] ${t}`,...r)}function v(e,t,...r){let n=new Date().toISOString();console.error(`[${n}] [WARN] [${e}] ${t}`,...r)}async function nm(e,t,r){if(!tm)return r();let n=performance.now();try{let s=await r(),o=(performance.now()-n).toFixed(0);return O(e,`${t} completed in ${o}ms`),s}catch(s){let o=(performance.now()-n).toFixed(0);throw O(e,`${t} failed after ${o}ms`),s}}var tm,ce=A(()=>{"use strict";tm=!1});function du(e){if(process.env[sm]!==void 0)throw new Te(`Refusing to ${e} during an unattended run (${sm} is set). Run it yourself in an interactive session.`)}function I(e){return e instanceof Error?e.message:String(e)}function Ue(e){if(e&&typeof e=="object"&&"status"in e){let t=e.status;return typeof t=="number"&&Number.isFinite(t)?t:void 0}}function hn(e){let t=Ue(e);return t===void 0?void 0:`HTTP ${t}`}function Xt(e){let t=hn(e);return t?`${t}: ${I(e)}`:I(e)}function zt(e){let t=Ue(e);return t===429?!0:t===403?I(e).toLowerCase().includes("rate limit"):!1}function UA(e){if(Ue(e)!==422)return!1;let t=e?.response?.data,r=t&&typeof t=="object"?t.errors:void 0;return Array.isArray(r)?r.some(n=>{if(!n||typeof n!="object")return!1;let s=n;return s.resource!=="Search"||s.code!=="invalid"?!1:typeof s.message=="string"?IS.test(s.message):IS.test(I(e))}):IS.test(I(e))}function de(e){let t=Ue(e);if(t===401||t===429)return!0;if(t===403){let r=I(e).toLowerCase();return r.includes("rate limit")||r.includes("abuse detection")}return!1}function im(e){if(!e||typeof e!="object")return!1;let t=Ue(e);if(typeof t=="number"&&t>=500&&t<600)return!0;let r=e.code;if(typeof r=="string"&&(r==="ECONNRESET"||r==="ETIMEDOUT"||r==="ENETUNREACH"||r==="ENOTFOUND"||r==="ECONNREFUSED"||r==="EAI_AGAIN"))return!0;let n=e.name;return typeof n=="string"&&(n==="AbortError"||n==="TimeoutError")}function jA(e){return t=>{if(de(t))throw t;return v(e.module,`Failed to ${e.label}: ${I(t)}`),e.fallback}}function am(e){if(e instanceof Te)return"CONFIGURATION";if(e instanceof j)return"VALIDATION";if(e instanceof Tr||e instanceof Qt)return"CONCURRENCY";let t=Ue(e);if(t===401)return"AUTH_REQUIRED";if(t===403){let n=I(e).toLowerCase();return n.includes("rate limit")||n.includes("abuse detection")?"RATE_LIMITED":"AUTH_REQUIRED"}if(t===404)return"NOT_FOUND";if(t===429)return"RATE_LIMITED";let r=I(e).toLowerCase();return r.includes("enotfound")||r.includes("econnrefused")||r.includes("econnreset")||r.includes("etimedout")||r.includes("fetch failed")?"NETWORK":r.includes("state")&&(r.includes("corrupt")||r.includes("invalid"))?"STATE_CORRUPTED":"UNKNOWN"}var _r,Te,sm,j,zi,lu,Tr,Qt,om,$r,IS,ee=A(()=>{"use strict";ce();_r=class extends Error{constructor(r,n){super(r);this.code=n;this.name="OssAutopilotError"}code},Te=class extends _r{constructor(t){super(t,"CONFIGURATION_ERROR"),this.name="ConfigurationError"}},sm="OSS_AUTOPILOT_UNATTENDED";j=class extends _r{constructor(t){super(t,"VALIDATION_ERROR"),this.name="ValidationError"}},zi=class extends Te{constructor(t){super(t??'Your GitHub token does not have Gist permissions. Run `gh auth refresh -s gist` to add the required scope, or create a token with the "gist" scope.'),this.name="GistPermissionError"}},lu=class extends Te{constructor(r,n,s){let o=s instanceof Error?s.message:String(s),i=n?`
64
64
  Corrupt content preserved at: ${n}
65
65
  Inspect or restore manually, then re-run. Falling back to a fresh state would overwrite your Gist.`:`
66
- Could not preserve the rejected content; do not push without inspecting the Gist manually.`;super(`Gist ${r} state.json is corrupt or fails schema validation: ${o}${i}`);this.gistId=r;this.rejectedPath=n;this.cause=s;this.name="GistCorruptError"}gistId;rejectedPath;cause},Tr=class extends _r{constructor(r,n){super("Another oss-autopilot process wrote state.json concurrently. Re-run the command to retry \u2014 the last write wins and no data was lost from the other process.","CONCURRENCY_ERROR");this.expectedMtimeMs=r;this.actualMtimeMs=n;this.name="ConcurrencyError"}expectedMtimeMs;actualMtimeMs},Qt=class extends _r{constructor(r,n){super("Another machine pushed to the state Gist while this push was in flight, and the merge attempt also collided. Your local mutations are still in memory, but `state --sync` cannot merge them: re-run the command that made the change.","CONCURRENCY_ERROR");this.expectedEtag=r;this.remoteEtag=n;this.name="GistConcurrencyError"}expectedEtag;remoteEtag},om="trim the large state fields in the Gist (repoScores and searchSeen are usually the biggest), or run state-unlink to fall back to local state",$r=class extends Te{constructor(t){super(t),this.name="GistFileSizeError"}};IS=/users.*do not exist|cannot be searched/i});function iz(e){try{let t=JSON.parse(ie.readFileSync(e,"utf8"));return Date.now()-t.timestamp>oz}catch(t){return O(ne,"Lock file unreadable or invalid JSON, treating as stale",t),!0}}function HA(e){let t=JSON.stringify({pid:process.pid,timestamp:Date.now()});try{ie.writeFileSync(e,t,{flag:"wx"});return}catch(r){O(ne,"Lock file already exists, checking staleness",r)}if(!iz(e))throw new Error("State file is locked by another process");try{ie.unlinkSync(e)}catch(r){O(ne,"Stale lock already removed by another process",r)}try{ie.writeFileSync(e,t,{flag:"wx"})}catch(r){throw O(ne,"Lock re-acquire failed (race condition)",r),new Error("State file is locked by another process",{cause:r})}}function WA(e){try{JSON.parse(ie.readFileSync(e,"utf8")).pid===process.pid&&ie.unlinkSync(e)}catch(t){O(ne,"Lock file already removed or unreadable during release",t)}}function Or(e,t,r){let n=`${e}.${process.pid}.tmp`;ie.writeFileSync(n,t,{mode:r??384}),ie.renameSync(n,e),r!==void 0&&ie.chmodSync(e,r)}function Hi(e){O(ne,"Migrating state from v1 to v2 (fresh GitHub fetching)...");let t=e.mergedPRs||[],r=e.closedPRs||[],n={...e.repoScores||{}};for(let o of[...t,...r])n[o.repo]||(n[o.repo]={repo:o.repo,score:5,mergedPRCount:0,closedWithoutMergeCount:0,avgResponseDays:null,lastEvaluatedAt:new Date().toISOString(),signals:{hasActiveMaintainers:!0,isResponsive:!1,hasHostileComments:!1}});let s={version:2,activeIssues:e.activeIssues||[],repoScores:n,config:e.config,lastRunAt:new Date().toISOString()};return O(ne,`Migration complete. Preserved ${Object.keys(n).length} repo scores.`),s}function Wi(e){O(ne,"Migrating state from v2 to v3 (drop dead fields, add learnings tracking)..."),delete e.events,delete e.dailyActivityCounts;let t=e.config;return t&&(delete t.showHealthCheck,delete t.scoreThreshold),e.version=3,O(ne,"v2 to v3 migration complete."),e}function Vi(e){return O(ne,"Migrating state from v3 to v4 (add commentsFetchedAt to stored PR records)..."),e.version=4,O(ne,"v3 to v4 migration complete (no data transformation required)."),e}function bn(){return Gt.parse({version:4})}function az(){let e=jt(),t=LA(),r=MA();if(ie.existsSync(e)||!ie.existsSync(t))return!1;O(ne,"Migrating state from ./data/ to ~/.oss-autopilot/...");try{if(ur(),ie.copyFileSync(t,e),O(ne,`Migrated state file to ${e}`),ie.existsSync(r)){let s=Ys(),o=ie.readdirSync(r).filter(i=>i.startsWith("state-")&&i.endsWith(".json"));for(let i of o){let a=yn.join(r,i),c=yn.join(s,i);ie.copyFileSync(a,c)}O(ne,`Migrated ${o.length} backup files`)}if(ie.unlinkSync(t),O(ne,"Removed legacy state file"),ie.existsSync(r)){let s=ie.readdirSync(r);for(let o of s)ie.unlinkSync(yn.join(r,o));ie.rmdirSync(r)}let n=yn.dirname(t);return ie.existsSync(n)&&ie.readdirSync(n).length===0&&(ie.rmdirSync(n),O(ne,"Removed empty legacy data directory")),O(ne,"Migration complete!"),!0}catch(n){if(v(ne,`Failed to migrate state: ${I(n)}`),ie.existsSync(e)&&ie.existsSync(t))try{ie.unlinkSync(e),O(ne,"Cleaned up partial migration - removed incomplete new state file")}catch(s){v(ne,"Could not clean up partial migration file"),O(ne,"Partial migration cleanup failed",s)}return v(ne,"To resolve this issue:"),v(ne," 1. Ensure you have write permissions to ~/.oss-autopilot/"),v(ne," 2. Check available disk space"),v(ne," 3. Manually copy ./data/state.json to ~/.oss-autopilot/state.json"),v(ne," 4. Or delete ./data/state.json to start fresh"),!1}}function zA(){let e=Ys();if(!ie.existsSync(e))return null;let t=ie.readdirSync(e).filter(r=>r.startsWith("state-")&&r.endsWith(".json")).sort().reverse();for(let r of t){let n=yn.join(e,r);try{let s=ie.readFileSync(n,"utf8"),o=JSON.parse(s);if(typeof o=="object"&&o!==null){let c=o;c.version===1&&(o=Hi(c)),o.version===2&&(o=Wi(o)),o.version===3&&(o=Vi(o))}let i=Gt.safeParse(o);if(i.success){let c=i.data;O(ne,`Successfully restored state from backup: ${r}`);let u=Object.keys(c.repoScores).length;O(ne,`Restored state v${c.version}: ${u} repo scores`);let d=jt();return Or(d,Ar(c),384),O(ne,"Restored backup written to main state file"),c}let a=i.error.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join("; ");v(ne,`Backup ${r} failed schema validation: ${a}`),O(ne,`Backup ${r} full validation errors:`,i.error.issues)}catch(s){let o=s instanceof Error?s.message:String(s);v(ne,`Backup ${r} is corrupted (${o}), trying next...`),O(ne,`Backup ${r} parse failed`,s)}}return null}function BA(e){try{let t=e+".rejected-"+Date.now();return ie.copyFileSync(e,t),v(ne,`Previous state preserved at: ${t}`),t}catch(t){return v(ne,`Could not preserve rejected state file: ${I(t)}`),null}}function Xs(e,t,r){let n=TA(e,t);n>0&&v(ne,`${r} has ${n} unreadable work claim(s); they were dropped`)}function cm(){az();let e=jt();try{if(ie.existsSync(e)){let t=Bi(e),r=ie.readFileSync(e,"utf8"),n=JSON.parse(r),s=!1;if(typeof n=="object"&&n!==null){let u=n;u.version===1&&(n=Hi(u),s=!0),n.version===2&&(n=Wi(n),s=!0),n.version===3&&(n=Vi(n),s=!0)}let o=Hp(n);o.length>0&&v(ne,`State file (fields: ${o.join(", ")}) ${Wp}`);let i=Gt.safeParse(n);if(!i.success){let u=i.error.issues.map(f=>`${f.path.join(".")}: ${f.message}`).join("; ");v(ne,`Invalid state file structure: ${u}`),v(ne,"Attempting to restore from backup..."),O(ne,"Full validation errors:",i.error.issues);let d=BA(e),p=`Invalid state file structure: ${u}`,m=zA();if(m){let f=Bi(e);return{state:m,mtimeMs:f,recovery:{source:"backup",rejectedPath:d,reason:p}}}return v(ne,"No valid backup found, starting fresh"),{state:bn(),mtimeMs:0,recovery:{source:"fresh",rejectedPath:d,reason:p}}}s&&(Or(e,Ar(i.data),384),t=Bi(e),O(ne,"Migrated and validated state saved"));let a=i.data;Xs(n,a,"State file");let c=Object.keys(a.repoScores).length;return O(ne,`Loaded state v${a.version}: ${c} repo scores tracked`),{state:a,mtimeMs:t}}}catch(t){let r=t?.code;if(r==="EACCES"||r==="EPERM")throw new Error(`Permission denied reading state file (${r}): ${I(t)}. This is an environment problem, not state corruption. Check the ownership and permissions of ~/.oss-autopilot/state.json (e.g. run \`ls -l ~/.oss-autopilot/state.json\` and fix with chown/chmod), then retry.`,{cause:t});v(ne,"Error loading state:",t),v(ne,"Attempting to restore from backup...");let n=ie.existsSync(e)?BA(e):null,s=`Error loading state: ${I(t)}`,o=zA();if(o){let i=Bi(e);return{state:o,mtimeMs:i,recovery:{source:"backup",rejectedPath:n,reason:s}}}return v(ne,"No valid backup found, starting fresh"),{state:bn(),mtimeMs:0,recovery:{source:"fresh",rejectedPath:n,reason:s}}}return O(ne,"No existing state found, initializing..."),{state:bn(),mtimeMs:0}}function Bi(e){try{return ie.statSync(e).mtimeMs}catch(t){return O(ne,`Could not read state file mtime (reload detection will always trigger): ${I(t)}`),0}}function cz(){let e=Ys();try{let t=ie.readdirSync(e).filter(r=>r.startsWith("state-")).sort().reverse();for(let r of t.slice(10))try{ie.unlinkSync(yn.join(e,r))}catch(n){v(ne,`Could not delete old backup ${r}:`,I(n))}}catch(t){v(ne,"Could not clean up backups:",I(t))}}function VA(e,t=null){let r=jt(),n=r+".lock",s=Ys();HA(n);try{if(t!==null&&t>0&&ie.existsSync(r)){let i=Bi(r);if(i!==t)throw new Tr(t,i)}try{if(ie.existsSync(r)){let i=new Date().toISOString().replaceAll(/[.:]/g,"-"),a=Math.random().toString(36).slice(2,8).padEnd(6,"0"),c=yn.join(s,`state-${i}-${a}.json`);ie.copyFileSync(r,c),ie.chmodSync(c,384),cz()}}catch(i){v(ne,`Could not create backup before save: ${I(i)}`)}Or(r,Ar(e),384);let o=Bi(r);return O(ne,"State saved successfully"),o}finally{WA(n)}}function qA(e){try{let t=jt();if(ie.statSync(t).mtimeMs===e)return null;let n=cm();if(n.recovery)try{n.mtimeMs=ie.statSync(t).mtimeMs}catch(s){O(ne,"Could not re-read mtime after reload (will retry next cycle)",s)}return n}catch(t){return v(ne,`Failed to reload state from disk: ${I(t)}`),null}}var ie,yn,ne,oz,pu=A(()=>{"use strict";ie=B(require("node:fs"),1),yn=B(require("node:path"),1);gn();Ui();Vr();ee();ce();ne="state",oz=3e4});function qr(e,t){return e===void 0||e<t}var xS,uz,um,eo,to,lz,ts=A(()=>{"use strict";gn();xS=Bp.parse({}),uz=Gt.parse({version:4}),um=_S.options,eo=vS.options,to=kS.options,lz={beginner:["good first issue","help wanted","easy","up-for-grabs","first-timers-only","beginner"],intermediate:["enhancement","feature","feature-request","contributions welcome"],advanced:["proposal","RFC","accepted","design"]}});function Sz(e){return{repo:e,score:YA,mergedPRCount:0,closedWithoutMergeCount:0,avgResponseDays:null,lastEvaluatedAt:new Date().toISOString(),signals:{hasActiveMaintainers:!0,isResponsive:!1,hasHostileComments:!1}}}function _z(e){let t=YA;if(e.mergedPRCount>0){let r=Math.min(Math.round(Math.log2(e.mergedPRCount+1)*dz),pz);t+=r}if(t-=Math.min(e.closedWithoutMergeCount,mz),e.lastMergedAt){let r=new Date(e.lastMergedAt);isNaN(r.getTime())?v(qi,`Invalid lastMergedAt date for ${e.repo}: "${e.lastMergedAt}". Skipping recency bonus.`):Math.floor((Date.now()-r.getTime())/864e5)<=fz&&(t+=gz)}return e.signals.isResponsive&&(t+=hz),e.signals.hasHostileComments&&(t-=yz),Math.max(bz,Math.min(wz,t))}function QA(e,t){return e.repoScores[t]}function ZA(e){return JSON.stringify([e.mergedPRCount,e.closedWithoutMergeCount,e.avgResponseDays??null,e.lastMergedAt??null,e.signals.hasActiveMaintainers,e.signals.isResponsive,e.signals.hasHostileComments])}function DS(e,t,r){let n=!e.repoScores[t];n&&(e.repoScores[t]=Sz(t));let s=e.repoScores[t],o=ZA(s);r.mergedPRCount!==void 0&&(s.mergedPRCount=r.mergedPRCount),r.closedWithoutMergeCount!==void 0&&(s.closedWithoutMergeCount=r.closedWithoutMergeCount),r.avgResponseDays!==void 0&&(s.avgResponseDays=r.avgResponseDays),r.lastMergedAt!==void 0&&(s.lastMergedAt=r.lastMergedAt),r.stargazersCount!==void 0&&(s.stargazersCount=r.stargazersCount),r.language!==void 0&&(s.language=r.language),r.signals&&(s.signals={...s.signals,...r.signals}),s.score=_z(s),(n||ZA(s)!==o)&&(s.lastEvaluatedAt=new Date().toISOString()),O(qi,`Updated repo score for ${t}: ${s.score}/10`)}function XA(e){return Object.values(e.repoScores).filter(t=>t.mergedPRCount>0).sort((t,r)=>r.mergedPRCount-t.mergedPRCount).map(t=>t.repo)}function eT(e){return Object.values(e.repoScores).filter(t=>t.mergedPRCount===0&&t.closedWithoutMergeCount===0).sort((t,r)=>r.score-t.score).map(t=>t.repo)}function tT(e,t){let r=t??e.config.minRepoScoreThreshold;return Object.values(e.repoScores).filter(n=>n.score>=r).sort((n,s)=>s.score-n.score).map(n=>n.repo)}function rT(e,t){let r=t??e.config.minRepoScoreThreshold,n=Date.now();return Object.values(e.repoScores).filter(s=>{if(s.score>r)return!1;let o=n-new Date(s.lastEvaluatedAt).getTime();return Number.isFinite(o)?o<=Rz:(v(qi,`Invalid lastEvaluatedAt for repo ${s.repo}: "${s.lastEvaluatedAt}", treating as stale`),!1)}).sort((s,o)=>s.score-o.score).map(s=>s.repo)}function KA(e){let t=new Map;for(let r of e){let n=q(r.url);if(!n){v(qi,`Skipping PR with unparseable URL during reconciliation: "${r.url}"`);continue}let s=`${n.owner}/${n.repo}`;t.set(s,(t.get(s)??0)+1)}return t}function nT(e,t,r){let n=JA(e,KA(t),"mergedPRCount"),s=JA(e,KA(r),"closedWithoutMergeCount");return n||s}function JA(e,t,r){let n=!1;for(let[s,o]of t){let i=e.repoScores[s]?.[r]??0;o>i&&(O(qi,`Reconciling ${s} ${r}: ${i} \u2192 ${o}`),DS(e,s,{[r]:o}),n=!0)}return n}function sT(e,t){let r=new Set(t.map(o=>o.url)),n=new Map;for(let o of t){let i=q(o.url);!i||!o.title||n.set(`${i.number}\0${o.title}`,`${i.owner}/${i.repo}`)}let s=new Map;for(let o of e){let i=r.has(o.url)||!o.title?null:q(o.url);if(!i)continue;let a=`${i.owner}/${i.repo}`,c=n.get(`${i.number}\0${o.title}`);c&&c!==a&&s.set(a,c)}return s}function oT(e,t,r){let n=`https://github.com/${t}/`,s=`https://github.com/${r}/`,o=a=>{if(!a?.some(d=>d.url.startsWith(n)))return a;let c=new Set;return a.map(d=>{if(!d.url.startsWith(n))return d;let p=s+d.url.slice(n.length);return c.add(p),{...d,url:p}}).filter((d,p)=>!c.has(d.url)||a[p].url.startsWith(n))};e.mergedPRs=o(e.mergedPRs),e.closedPRs=o(e.closedPRs);let i=e.repoScores[t];i&&(Object.hasOwn(e.repoScores,r)||(e.repoScores[r]={...i,repo:r}),delete e.repoScores[t]),O(qi,`Renamed transferred repo ${t} \u2192 ${r}`)}function iT(e){let t=0,r=0,n=0;for(let i of Object.values(e.repoScores))qr(i.stargazersCount,e.config.minStars??50)||(n++,t+=i.mergedPRCount,r+=i.closedWithoutMergeCount);let s=t+r,o=s>0?t/s*100:0;return{mergedPRs:t,closedPRs:r,activeIssues:0,trustedProjects:e.config.trustedProjects.length,mergeRate:o.toFixed(1)+"%",totalTracked:n,needsResponse:0}}var qi,YA,dz,pz,mz,fz,gz,hz,yz,bz,wz,Rz,LS=A(()=>{"use strict";ts();ce();nt();qi="scoring",YA=5,dz=2,pz=5,mz=3,fz=90,gz=1,hz=1,yz=2,bz=1,wz=10,Rz=720*60*60*1e3});function aT(e){return e?e.etag??e.ETag??null:null}function MS(e,t){try{let r=`${es()}.rejected-${Date.now()}`;return Zr.writeFileSync(r,e,{encoding:"utf8",mode:384}),r}catch(r){return v(Pe,`Could not preserve rejected Gist content for ${t}: ${r instanceof Error?r.message:String(r)}`),null}}var Zr,Pe,FS,wn,kz,cT,Cz,Pz,uT,Zi,NS=A(()=>{"use strict";Zr=B(require("node:fs"),1);gn();Ui();pu();Vr();ce();ee();Pe="gist-store";FS="oss-autopilot-state",wn="state.json",kz=900*1024,cT=10*1024*1024,Cz="gist.githubusercontent.com",Pz=100*1024,uT=new Map,Zi=class e{gistId=null;cachedFiles=new Map;dirtyFiles=new Set;baselineFiles=new Map;lastFetchedEtag=null;octokit;lastRefreshAt=0;static REFRESH_THROTTLE_MS=3e4;lastRefreshError=null;constructor(t){this.octokit=t}async bootstrap(){try{await this.checkGistScope();let t=this.readLocalGistId();if(t){O(Pe,`Found local Gist ID: ${t}`);try{this.gistId=t;let o=await this.fetchAndCache(t);return{gistId:t,state:o,created:!1}}catch(o){if(o instanceof Te||zt(o))throw o;v(Pe,`Failed to fetch Gist ${t}, will search/create`,o)}}let r=await this.searchForGist();if(r){O(Pe,`Found Gist via search: ${r}`),this.gistId=r,this.writeLocalGistId(r);let o=await this.fetchAndCache(r);return{gistId:r,state:o,created:!1}}O(Pe,"No existing Gist found, creating new one");let{id:n,state:s}=await this.createGist();return this.writeLocalGistId(n),{gistId:n,state:s,created:!0}}catch(t){if(t instanceof Te||zt(t))throw t;this.gistId=null,this.lastFetchedEtag=null,v(Pe,"All Gist API paths failed, entering degraded mode",t);let r=es(),n=null;try{if(Zr.existsSync(r)){n=Zr.readFileSync(r,"utf8");let s=JSON.parse(n);if(typeof s=="object"&&s!==null){let i=s;i.version===1&&(s=Hi(i)),s.version===2&&(s=Wi(s)),s.version===3&&(s=Vi(s))}let o=Gt.parse(s);return Xs(s,o,"Local state cache"),O(Pe,"Loaded state from local cache in degraded mode"),{gistId:"",state:o,created:!1,degraded:!0}}}catch(s){if(n){let o=MS(n,"local-cache");v(Pe,`Local state cache failed to parse in degraded mode: ${s instanceof Error?s.message:String(s)}. Corrupt cache preserved at: ${o??"(could not preserve)"}`)}else v(Pe,`Failed to read local cache in degraded mode: ${s instanceof Error?s.message:String(s)}`)}return O(Pe,"No local cache found, returning fresh state in degraded mode"),{gistId:"",state:bn(),created:!1,degraded:!0}}}async bootstrapWithMigration(t){try{await this.checkGistScope();let r=this.readLocalGistId();if(r){O(Pe,`bootstrapWithMigration: found local Gist ID: ${r}`);try{this.gistId=r;let i=await this.fetchAndCache(r);return{gistId:r,state:i,created:!1,migrated:!1}}catch(i){if(i instanceof Te||zt(i))throw i;v(Pe,`bootstrapWithMigration: failed to fetch Gist ${r}, will search/create`,i)}}let n=await this.searchForGist();if(n){O(Pe,`bootstrapWithMigration: found Gist via search: ${n}`),this.gistId=n,this.writeLocalGistId(n);let i=await this.fetchAndCache(n);return{gistId:n,state:i,created:!1,migrated:!1}}O(Pe,"bootstrapWithMigration: no existing Gist found, creating one seeded with local state");let{id:s,state:o}=await this.createGistFromState(t);return this.writeLocalGistId(s),{gistId:s,state:o,created:!0,migrated:!0}}catch(r){if(r instanceof Te||zt(r))throw r;this.gistId=null,this.lastFetchedEtag=null,v(Pe,"bootstrapWithMigration: all Gist API paths failed, entering degraded mode",r);let n=es(),s=null;try{if(Zr.existsSync(n)){s=Zr.readFileSync(n,"utf8");let o=JSON.parse(s);if(typeof o=="object"&&o!==null){let a=o;a.version===1&&(o=Hi(a)),o.version===2&&(o=Wi(o)),o.version===3&&(o=Vi(o))}let i=Gt.parse(o);return Xs(o,i,"Local state cache"),O(Pe,"bootstrapWithMigration: loaded state from local cache in degraded mode"),{gistId:"",state:i,created:!1,degraded:!0,migrated:!1}}}catch(o){if(s){let i=MS(s,"local-cache");v(Pe,`bootstrapWithMigration: local cache failed to parse: ${o instanceof Error?o.message:String(o)}. Corrupt cache preserved at: ${i??"(could not preserve)"}`)}else v(Pe,`bootstrapWithMigration: failed to read local cache: ${o instanceof Error?o.message:String(o)}`)}return O(Pe,"bootstrapWithMigration: no local cache found, returning existing state in degraded mode"),{gistId:"",state:t,created:!1,degraded:!0,migrated:!1}}}getGistId(){return this.gistId}markDirty(t){this.dirtyFiles.add(t)}getDocument(t){return this.cachedFiles.get(t)??null}setDocument(t,r){this.cachedFiles.set(t,r),this.markDirty(t)}listDocuments(t){let r=[];for(let n of this.cachedFiles.keys())n.startsWith(t)&&r.push(n);return r}setState(t){this.cachedFiles.set(wn,t),this.markDirty(wn)}async push(){if(this.dirtyFiles.size===0)return!0;if(this.gistId===null)throw new Error("GistStateStore: cannot push before bootstrap \u2014 gistId is null");this.checkPushSize();let t=()=>{let o={};for(let i of this.dirtyFiles){let a=this.cachedFiles.get(i);a!==void 0&&(o[i]={content:a})}return o},r=async()=>{try{let o={gist_id:this.gistId,files:t()},i=await this.octokit.gists.update(o),a=aT(i.headers);return a&&(this.lastFetchedEtag=a),{ok:!0}}catch(o){return{ok:!1,status:o.status,err:o}}};if(this.dirtyFiles.has(wn)){let o={};for(let f of this.dirtyFiles){let g=this.cachedFiles.get(f);g!==void 0&&(o[f]=g)}let i=new Map(this.cachedFiles),a=new Map(this.baselineFiles),c=this.lastFetchedEtag,u=a.get(wn),d=()=>{for(let[f,g]of Object.entries(o))this.cachedFiles.set(f,g)},p=()=>{this.cachedFiles.clear();for(let[f,g]of i)this.cachedFiles.set(f,g);this.baselineFiles=a,this.lastFetchedEtag=c,d()};try{await this.fetchAndCache(this.gistId)}catch(f){throw v(Pe,`Pre-write re-read failed: ${I(f)}`),p(),f instanceof lu||f instanceof $r||zt(f)?f:new Qt(c,null)}let m=this.cachedFiles.get(wn);if(u!==m){v(Pe,"state.json changed remotely since our last fetch; surfacing GistConcurrencyError instead of clobbering (#1235, #1510)");let f=this.lastFetchedEtag;throw p(),new Qt(c,f)}d()}let n=await r();if(!n.ok&&(O(Pe,`push failed on first attempt, retrying: ${n.err}`),n=await r(),!n.ok))return v(Pe,`push failed after retry, giving up: ${n.err}`),!1;if(this.dirtyFiles.clear(),this.baselineFiles=new Map(this.cachedFiles),this.cachedFiles.get(wn))try{let o=this.parseStateFromCache();this.writeLocalStateCache(o)}catch(o){O(Pe,`push succeeded but local cache write failed: ${o}`)}return!0}async refreshFromGist(t={}){if(!this.gistId)return{status:"no-gist"};let r=Date.now(),n=r-this.lastRefreshAt;if(n<e.REFRESH_THROTTLE_MS&&!t.force)return{status:"throttled",sinceLastMs:n};this.lastRefreshAt=r;try{return await this.fetchAndCache(this.gistId),this.lastRefreshError=null,{status:"refreshed"}}catch(s){let o=s instanceof Error?s:new Error(String(s));return v(Pe,`refreshFromGist failed: ${o.message}`),this.lastRefreshError=o,{status:"error",error:o}}}checkPushSize(){for(let t of this.dirtyFiles){let r=this.cachedFiles.get(t);if(r===void 0)continue;let n=Buffer.byteLength(r,"utf8");if(n>cT)throw new $r(`Refusing to push Gist file ${t}: ${n} bytes exceeds the ${cT}-byte limit the Gist API can serve back. The local change is kept in memory but was not synced.`);if(n>kz){let s=Math.floor(n/Pz);(uT.get(t)??-1)<s&&(uT.set(t,s),v(Pe,`Gist file ${t} is ${n} bytes, near or past the 1 MB the Gist API returns inline. Reads fall back to raw_url, which works up to 10 MB; to stay well under that, trim large state fields (repoScores and searchSeen are usually the biggest).`))}}}async checkGistScope(){try{await this.octokit.gists.list({per_page:1,page:1})}catch(t){if(zt(t))throw t;let r=t.status;throw r===401||r===403?new zi:t}}async fetchAndCache(t){let r=await this.octokit.gists.get({gist_id:t});this.gistId=t;let n=new Map;for(let[o,i]of Object.entries(r.data.files)){if(!i)continue;let a=i.truncated?await this.fetchRawContent(o,i.raw_url):i.content;a!=null&&n.set(o,a)}this.lastFetchedEtag=aT(r.headers),this.cachedFiles.clear();for(let[o,i]of n)this.cachedFiles.set(o,i);this.baselineFiles=new Map(this.cachedFiles);let s=this.parseStateFromCache();return this.writeLocalStateCache(s),s}async fetchRawContent(t,r){let n=a=>new $r(`Gist file ${t} is larger than the 1 MB the Gist API returns inline and its full content could not be read from raw_url (${a}). Local state was left unchanged.`);if(!this.octokit.request)throw n("no HTTP client available");if(!r)throw n("the API returned no raw_url");let s=URL.canParse(r)?new URL(r):void 0;if((s?.protocol==="https:"?s.hostname:"")!==Cz)throw n("unexpected raw_url host");let i;try{({data:i}=await this.octokit.request({method:"GET",url:r}))}catch(a){throw zt(a)||im(a)?a:n(I(a))}if(typeof i!="string")throw n("response body was not text");return i}parseStateFromCache(){let t=this.cachedFiles.get(wn);if(!t)return O(Pe,"No state.json found in Gist, using fresh state"),bn();try{let r=JSON.parse(t);if(typeof r=="object"&&r!==null){let o=r;o.version===1&&(r=Hi(o)),r.version===2&&(r=Wi(r)),r.version===3&&(r=Vi(r))}let n=Hp(r);n.length>0&&v(Pe,`Gist state (fields: ${n.join(", ")}) ${Wp}`);let s=Gt.parse(r);return Xs(r,s,"Gist state"),s}catch(r){let n=MS(t,this.gistId??"unknown");throw v(Pe,`Gist state.json failed to parse \u2014 refusing to overwrite with fresh state. Corrupt content preserved at: ${n??"(could not preserve)"}`),new lu(this.gistId??"unknown",n,r)}}async searchForGist(){try{for(let r=1;r<=10;r++){let{data:n}=await this.octokit.gists.list({per_page:100,page:r});if(n.length===0)break;let s=n.find(o=>o.description===FS);if(s)return s.id}}catch(t){if(zt(t))throw t;v(Pe,"Failed to search Gists by description",t)}return null}async createGist(){let t=bn(),r=Ar(t),{data:n}=await this.octokit.gists.create({description:FS,public:!1,files:{[wn]:{content:r}}});this.gistId=n.id,this.cachedFiles.clear();for(let[s,o]of Object.entries(n.files))o&&o.content!=null&&this.cachedFiles.set(s,o.content);return this.baselineFiles=new Map(this.cachedFiles),this.writeLocalStateCache(t),{id:n.id,state:t}}async createGistFromState(t){let r=Ar(t),{data:n}=await this.octokit.gists.create({description:FS,public:!1,files:{[wn]:{content:r}}});this.gistId=n.id,this.cachedFiles.clear();for(let[s,o]of Object.entries(n.files))o&&o.content!=null&&this.cachedFiles.set(s,o.content);return this.baselineFiles=new Map(this.cachedFiles),this.writeLocalStateCache(t),{id:n.id,state:t}}readLocalGistId(){try{let t=Qs();if(Zr.existsSync(t))return Zr.readFileSync(t,"utf8").trim()||null}catch(t){O(Pe,"Could not read local Gist ID file",t)}return null}writeLocalGistId(t){try{let r=Qs();Or(r,t,384),O(Pe,`Wrote Gist ID to ${r}`)}catch(r){v(Pe,`Failed to write local Gist ID file: ${r}`)}}writeLocalStateCache(t){try{let r=es();Or(r,Ar(t),384),O(Pe,`Wrote state cache to ${r}`)}catch(r){v(Pe,`Failed to write local state cache: ${r}`)}}}});function fu(e){if(!e.includes("/"))throw new _r(`Invalid repo identifier "${e}". Expected "owner/repo" format.`,"INVALID_REPO_ID");let[t,r]=e.split("/",2);return`${Ki}${t}--${r}${GS}`}function US(e){if(!e.startsWith(Ki)||!e.endsWith(GS))return null;let t=e.slice(Ki.length,e.length-GS.length),r=t.indexOf("--");if(r===-1)return null;let n=t.slice(0,r),s=t.slice(r+2);return!n||!s?null:`${n}/${s}`}function lT(e,t){if(!e)return null;let r=e.getDocument(fu(t));return r===null||r===""?null:r}function dT(e,t,r){if(!e)throw new rs;let n=Buffer.byteLength(r,"utf8");if(n>lm)throw new mu(n);e.setDocument(fu(t),r)}function pT(e,t){if(!e)throw new rs;e.setDocument(fu(t),"")}function mT(e){if(!e)return[];let t=e.listDocuments(Ki),r=[];for(let n of t){let s=US(n);if(!s)continue;let o=e.getDocument(n);o===null||o===""||r.push(s)}return r.sort()}var Ki,lm,GS,rs,mu,jS=A(()=>{"use strict";ee();Ki="guidelines--",lm=8192,GS=".md";rs=class extends _r{constructor(t){super(t??"Per-repo guidelines require Gist persistence. Run `oss-autopilot setup` to enable Gist sync, then retry.","GUIDELINES_NOT_AVAILABLE"),this.name="GuidelinesNotAvailableError"}},mu=class extends _r{constructor(t,r=lm){super(`Guidelines content is ${t} bytes, exceeding the ${r}-byte cap. Trim or split across categories.`,"GUIDELINES_TOO_LARGE"),this.name="GuidelinesTooLargeError"}}});function Ji(e,t={}){return`Gist persistence is configured but ${typeof e=="string"?Az[e]:e.reason}; writes are LOCAL-ONLY and may be overwritten by the next successful Gist sync.${t.retryHint?` ${t.retryHint}`:""}`}var Az,zS=A(()=>{"use strict";Az={"no-token":"no GitHub token was available","state-unreadable":"the state file could not be read","init-fallback":"initialization hit a transient network failure","configured-but-local":"this process is running local-only (Gist init has not succeeded)","bootstrap-degraded":"the Gist bootstrap fell back to the local cache (reads may be stale and pushes are failing)"}});function ns(){return typeof navigator=="object"&&"userAgent"in navigator?navigator.userAgent:typeof process=="object"&&process.version!==void 0?`Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`:"<environment undetectable>"}var gu=A(()=>{});function dm(e,t,r,n){if(typeof r!="function")throw new Error("method for before hook must be a function");return n||(n={}),Array.isArray(t)?t.reverse().reduce((s,o)=>dm.bind(null,e,o,s,n),r)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((s,o)=>o.hook.bind(null,s,n),r)():r(n))}var fT=A(()=>{});function gT(e,t,r,n){let s=n;e.registry[r]||(e.registry[r]=[]),t==="before"&&(n=(o,i)=>Promise.resolve().then(s.bind(null,i)).then(o.bind(null,i))),t==="after"&&(n=(o,i)=>{let a;return Promise.resolve().then(o.bind(null,i)).then(c=>(a=c,s(a,i))).then(()=>a)}),t==="error"&&(n=(o,i)=>Promise.resolve().then(o.bind(null,i)).catch(a=>s(a,i))),e.registry[r].push({hook:n,orig:s})}var hT=A(()=>{});function yT(e,t,r){if(!e.registry[t])return;let n=e.registry[t].map(s=>s.orig).indexOf(r);n!==-1&&e.registry[t].splice(n,1)}var bT=A(()=>{});function ST(e,t,r){let n=RT(yT,null).apply(null,r?[t,r]:[t]);e.api={remove:n},e.remove=n,["before","error","after","wrap"].forEach(s=>{let o=r?[t,s,r]:[t,s];e[s]=e.api[s]=RT(gT,null).apply(null,o)})}function Tz(){let e=Symbol("Singular"),t={registry:{}},r=dm.bind(null,t,e);return ST(r,t,e),r}function $z(){let e={registry:{}},t=dm.bind(null,e);return ST(t,e),t}var wT,RT,_T,vT=A(()=>{fT();hT();bT();wT=Function.bind,RT=wT.bind(wT);_T={Singular:Tz,Collection:$z}});function Dz(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function Lz(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}function PT(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(n=>{Lz(t[n])?n in e?r[n]=PT(e[n],t[n]):Object.assign(r,{[n]:t[n]}):Object.assign(r,{[n]:t[n]})}),r}function kT(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function HS(e,t,r){if(typeof t=="string"){let[s,o]=t.split(" ");r=Object.assign(o?{method:s,url:o}:{url:s},r)}else r=Object.assign({},t);r.headers=Dz(r.headers),kT(r),kT(r.headers);let n=PT(e||{},r);return r.url==="/graphql"&&(e&&e.mediaType.previews?.length&&(n.mediaType.previews=e.mediaType.previews.filter(s=>!n.mediaType.previews.includes(s)).concat(n.mediaType.previews)),n.mediaType.previews=(n.mediaType.previews||[]).map(s=>s.replace(/-preview/,""))),n}function Mz(e,t){let r=/\?/.test(e)?"&":"?",n=Object.keys(t);return n.length===0?e:e+r+n.map(s=>s==="q"?"q="+t.q.split("+").map(encodeURIComponent).join("+"):`${s}=${encodeURIComponent(t[s])}`).join("&")}function Nz(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function Gz(e){let t=e.match(Fz);return t?t.map(Nz).reduce((r,n)=>r.concat(n),[]):[]}function CT(e,t){let r={__proto__:null};for(let n of Object.keys(e))t.indexOf(n)===-1&&(r[n]=e[n]);return r}function ET(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(t){return/%[0-9A-Fa-f]/.test(t)||(t=encodeURI(t).replace(/%5B/g,"[").replace(/%5D/g,"]")),t}).join("")}function Qi(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function hu(e,t,r){return t=e==="+"||e==="#"?ET(t):Qi(t),r?Qi(r)+"="+t:t}function Yi(e){return e!=null}function BS(e){return e===";"||e==="&"||e==="?"}function Uz(e,t,r,n){var s=e[r],o=[];if(Yi(s)&&s!=="")if(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")s=s.toString(),n&&n!=="*"&&(s=s.substring(0,parseInt(n,10))),o.push(hu(t,s,BS(t)?r:""));else if(n==="*")Array.isArray(s)?s.filter(Yi).forEach(function(i){o.push(hu(t,i,BS(t)?r:""))}):Object.keys(s).forEach(function(i){Yi(s[i])&&o.push(hu(t,s[i],i))});else{let i=[];Array.isArray(s)?s.filter(Yi).forEach(function(a){i.push(hu(t,a))}):Object.keys(s).forEach(function(a){Yi(s[a])&&(i.push(Qi(a)),i.push(hu(t,s[a].toString())))}),BS(t)?o.push(Qi(r)+"="+i.join(",")):i.length!==0&&o.push(i.join(","))}else t===";"?Yi(s)&&o.push(Qi(r)):s===""&&(t==="&"||t==="?")?o.push(Qi(r)+"="):s===""&&o.push("");return o}function jz(e){return{expand:zz.bind(null,e)}}function zz(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(n,s,o){if(s){let a="",c=[];if(r.indexOf(s.charAt(0))!==-1&&(a=s.charAt(0),s=s.substr(1)),s.split(/,/g).forEach(function(u){var d=/([^:\*]*)(?::(\d+)|(\*))?/.exec(u);c.push(Uz(t,a,d[1],d[2]||d[3]))}),a&&a!=="+"){var i=",";return a==="?"?i="&":a!=="#"&&(i=a),(c.length!==0?a:"")+c.join(i)}else return c.join(",")}else return ET(o)}),e==="/"?e:e.replace(/\/$/,"")}function AT(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),n=Object.assign({},e.headers),s,o=CT(e,["method","baseUrl","url","headers","request","mediaType"]),i=Gz(r);r=jz(r).expand(o),/^http/.test(r)||(r=e.baseUrl+r);let a=Object.keys(e).filter(d=>i.includes(d)).concat("baseUrl"),c=CT(o,a);if(!/application\/octet-stream/i.test(n.accept)&&(e.mediaType.format&&(n.accept=n.accept.split(/,/).map(d=>d.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(",")),r.endsWith("/graphql")&&e.mediaType.previews?.length)){let d=n.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[];n.accept=d.concat(e.mediaType.previews).map(p=>{let m=e.mediaType.format?`.${e.mediaType.format}`:"+json";return`application/vnd.github.${p}-preview${m}`}).join(",")}return["GET","HEAD"].includes(t)?r=Mz(r,c):"data"in c?s=c.data:Object.keys(c).length&&(s=c),!n["content-type"]&&typeof s<"u"&&(n["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(t)&&typeof s>"u"&&(s=""),Object.assign({method:t,url:r,headers:n},typeof s<"u"?{body:s}:null,e.request?{request:e.request}:null)}function Bz(e,t,r){return AT(HS(e,t,r))}function TT(e,t){let r=HS(e,t),n=Bz.bind(null,r);return Object.assign(n,{DEFAULTS:r,defaults:TT.bind(null,r),merge:HS.bind(null,r),parse:AT})}var Oz,Iz,xz,Fz,$T,OT=A(()=>{gu();Oz="0.0.0-development",Iz=`octokit-endpoint.js/${Oz} ${ns()}`,xz={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":Iz},mediaType:{format:""}};Fz=/\{[^{}}]+\}/g;$T=TT(null,xz)});var LT=bC((U5,yu)=>{"use strict";var fm=function(){};fm.prototype=Object.create(null);var pm=/; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu,mm=/\\([\v\u0020-\u00ff])/gu,IT=/^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u,ro={type:"",parameters:new fm};Object.freeze(ro.parameters);Object.freeze(ro);function xT(e){if(typeof e!="string")throw new TypeError("argument header is required and must be a string");let t=e.indexOf(";"),r=t!==-1?e.slice(0,t).trim():e.trim();if(IT.test(r)===!1)throw new TypeError("invalid media type");let n={type:r.toLowerCase(),parameters:new fm};if(t===-1)return n;let s,o,i;for(pm.lastIndex=t;o=pm.exec(e);){if(o.index!==t)throw new TypeError("invalid parameter format");t+=o[0].length,s=o[1].toLowerCase(),i=o[2],i[0]==='"'&&(i=i.slice(1,i.length-1),mm.test(i)&&(i=i.replace(mm,"$1"))),n.parameters[s]=i}if(t!==e.length)throw new TypeError("invalid parameter format");return n}function DT(e){if(typeof e!="string")return ro;let t=e.indexOf(";"),r=t!==-1?e.slice(0,t).trim():e.trim();if(IT.test(r)===!1)return ro;let n={type:r.toLowerCase(),parameters:new fm};if(t===-1)return n;let s,o,i;for(pm.lastIndex=t;o=pm.exec(e);){if(o.index!==t)return ro;t+=o[0].length,s=o[1].toLowerCase(),i=o[2],i[0]==='"'&&(i=i.slice(1,i.length-1),mm.test(i)&&(i=i.replace(mm,"$1"))),n.parameters[s]=i}return t!==e.length?ro:n}yu.exports.default={parse:xT,safeParse:DT};yu.exports.parse=xT;yu.exports.safeParse=DT;yu.exports.defaultContentType=ro});var Hz,NT,WS,MT,Wz,Vz,qz,GT,Zz,Kz,Jz,UT,FT,Yz,Qz,jT,zT=A(()=>{Hz=/^-?\d+$/,NT=/^-?\d+n+$/,WS=JSON.stringify,MT=JSON.parse,Wz=/^-?\d+n$/,Vz=/([\[:])?"(-?\d+)n"($|([\\n]|\s)*(\s|[\\n])*[,\}\]])/g,qz=/([\[:])?("-?\d+n+)n("$|"([\\n]|\s)*(\s|[\\n])*[,\}\]])/g,GT=(e,t,r)=>"rawJSON"in JSON?WS(e,(i,a)=>typeof a=="bigint"?JSON.rawJSON(a.toString()):typeof t=="function"?t(i,a):(Array.isArray(t)&&t.includes(i),a),r):e?WS(e,(i,a)=>typeof a=="string"&&!!a.match(NT)||typeof a=="bigint"?a.toString()+"n":typeof t=="function"?t(i,a):(Array.isArray(t)&&t.includes(i),a),r).replace(Vz,"$1$2$3").replace(qz,"$1$2$3"):WS(e,t,r),Zz=()=>JSON.parse("1",(e,t,r)=>!!r&&r.source==="1"),Kz=(e,t,r,n)=>typeof t=="string"&&t.match(Wz)?BigInt(t.slice(0,-1)):typeof t=="string"&&t.match(NT)?t.slice(0,-1):typeof n!="function"?t:n(e,t,r),Jz=(e,t)=>JSON.parse(e,(r,n,s)=>{let o=typeof n=="number"&&(n>Number.MAX_SAFE_INTEGER||n<Number.MIN_SAFE_INTEGER),i=s&&Hz.test(s.source);return o&&i?BigInt(s.source):typeof t!="function"?n:t(r,n,s)}),UT=Number.MAX_SAFE_INTEGER.toString(),FT=UT.length,Yz=/"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g,Qz=/^"-?\d+n+"$/,jT=(e,t)=>{if(!e)return MT(e,t);if(Zz())return Jz(e,t);let r=e.replace(Yz,(n,s,o,i)=>{let a=n[0]==='"';if(a&&!!n.match(Qz))return n.substring(0,n.length-1)+'n"';let u=o||i,d=s&&(s.length<FT||s.length===FT&&s<=UT);return a||u||d?n:'"'+n+'n"'});return MT(r,(n,s,o)=>Kz(n,s,o,t))}});var Rn,VS=A(()=>{Rn=class extends Error{name;status;request;response;constructor(t,r,n){super(t,{cause:n.cause}),this.name="HttpError",this.status=Number.parseInt(r),Number.isNaN(this.status)&&(this.status=0);"response"in n&&(this.response=n.response);let s=Object.assign({},n.request);n.request.headers.authorization&&(s.headers=Object.assign({},n.request.headers,{authorization:n.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),s.url=s.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=s}}});function t1(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}async function HT(e){let t=e.request?.fetch||globalThis.fetch;if(!t)throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");let r=e.request?.log||console,n=e.request?.parseSuccessResponseBody!==!1,s=t1(e.body)||Array.isArray(e.body)?GT(e.body):e.body,o=Object.fromEntries(Object.entries(e.headers).map(([p,m])=>[p,String(m)])),i;try{i=await t(e.url,{method:e.method,body:s,redirect:e.request?.redirect,headers:o,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(p){let m="Unknown Error";if(p instanceof Error){if(p.name==="AbortError")throw p.status=500,p;m=p.message,p.name==="TypeError"&&"cause"in p&&(p.cause instanceof Error?m=p.cause.message:typeof p.cause=="string"&&(m=p.cause))}let f=new Rn(m,500,{request:e});throw f.cause=p,f}let a=i.status,c=i.url,u={};for(let[p,m]of i.headers)u[p]=m;let d={url:c,status:a,headers:u,data:""};if("deprecation"in u){let p=u.link&&u.link.match(/<([^<>]+)>; rel="deprecation"/),m=p&&p.pop();r.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${u.sunset}${m?`. See ${m}`:""}`)}if(a===204||a===205)return d;if(e.method==="HEAD"){if(a<400)return d;throw new Rn(i.statusText,a,{response:d,request:e})}if(a===304)throw d.data=await qS(i),new Rn("Not modified",a,{response:d,request:e});if(a>=400)throw d.data=await qS(i),new Rn(n1(d.data),a,{response:d,request:e});return d.data=n?await qS(i):i.body,d}async function qS(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(BT);let r=(0,WT.safeParse)(t);if(r1(r)){let n="";try{return n=await e.text(),jT(n)}catch{return n}}else return r.type.startsWith("text/")||r.parameters.charset?.toLowerCase()==="utf-8"?e.text().catch(BT):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function r1(e){return e.type==="application/json"||e.type==="application/scim+json"}function n1(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return"Unknown error";if("message"in e){let t="documentation_url"in e?` - ${e.documentation_url}`:"";return Array.isArray(e.errors)?`${e.message}: ${e.errors.map(r=>JSON.stringify(r)).join(", ")}${t}`:`${e.message}${t}`}return`Unknown error: ${JSON.stringify(e)}`}function ZS(e,t){let r=e.defaults(t);return Object.assign(function(s,o){let i=r.merge(s,o);if(!i.request||!i.request.hook)return HT(r.parse(i));let a=(c,u)=>HT(r.parse(r.merge(c,u)));return Object.assign(a,{endpoint:r,defaults:ZS.bind(null,r)}),i.request.hook(a,i)},{endpoint:r,defaults:ZS.bind(null,r)})}var WT,Xz,e1,BT,bu,KS=A(()=>{OT();gu();WT=B(LT(),1);zT();VS();Xz="10.0.8",e1={headers:{"user-agent":`octokit-request.js/${Xz} ${ns()}`}};BT=()=>"";bu=ZS($T,e1);});function o1(e){return`Request failed due to following response errors:
66
+ Could not preserve the rejected content; do not push without inspecting the Gist manually.`;super(`Gist ${r} state.json is corrupt or fails schema validation: ${o}${i}`);this.gistId=r;this.rejectedPath=n;this.cause=s;this.name="GistCorruptError"}gistId;rejectedPath;cause},Tr=class extends _r{constructor(r,n){super("Another oss-autopilot process wrote state.json concurrently. Re-run the command to retry \u2014 the last write wins and no data was lost from the other process.","CONCURRENCY_ERROR");this.expectedMtimeMs=r;this.actualMtimeMs=n;this.name="ConcurrencyError"}expectedMtimeMs;actualMtimeMs},Qt=class extends _r{constructor(r,n){super("Another machine pushed to the state Gist while this push was in flight, and the merge attempt also collided. Your local mutations are still in memory, but `state --sync` cannot merge them: re-run the command that made the change.","CONCURRENCY_ERROR");this.expectedEtag=r;this.remoteEtag=n;this.name="GistConcurrencyError"}expectedEtag;remoteEtag},om="trim the large state fields in the Gist (repoScores and searchSeen are usually the biggest), or run state-unlink to fall back to local state",$r=class extends Te{constructor(t){super(t),this.name="GistFileSizeError"}};IS=/users.*do not exist|cannot be searched/i});function iz(e){try{let t=JSON.parse(ie.readFileSync(e,"utf8"));return Date.now()-t.timestamp>oz}catch(t){return O(ne,"Lock file unreadable or invalid JSON, treating as stale",t),!0}}function HA(e){let t=JSON.stringify({pid:process.pid,timestamp:Date.now()});try{ie.writeFileSync(e,t,{flag:"wx"});return}catch(r){O(ne,"Lock file already exists, checking staleness",r)}if(!iz(e))throw new Error("State file is locked by another process");try{ie.unlinkSync(e)}catch(r){O(ne,"Stale lock already removed by another process",r)}try{ie.writeFileSync(e,t,{flag:"wx"})}catch(r){throw O(ne,"Lock re-acquire failed (race condition)",r),new Error("State file is locked by another process",{cause:r})}}function WA(e){try{JSON.parse(ie.readFileSync(e,"utf8")).pid===process.pid&&ie.unlinkSync(e)}catch(t){O(ne,"Lock file already removed or unreadable during release",t)}}function Or(e,t,r){let n=`${e}.${process.pid}.tmp`;ie.writeFileSync(n,t,{mode:r??384}),ie.renameSync(n,e),r!==void 0&&ie.chmodSync(e,r)}function Hi(e){O(ne,"Migrating state from v1 to v2 (fresh GitHub fetching)...");let t=e.mergedPRs||[],r=e.closedPRs||[],n={...e.repoScores||{}};for(let o of[...t,...r])n[o.repo]||(n[o.repo]={repo:o.repo,score:5,mergedPRCount:0,closedWithoutMergeCount:0,avgResponseDays:null,lastEvaluatedAt:new Date().toISOString(),signals:{hasActiveMaintainers:!0,isResponsive:!1,hasHostileComments:!1}});let s={version:2,activeIssues:e.activeIssues||[],repoScores:n,config:e.config,lastRunAt:new Date().toISOString()};return O(ne,`Migration complete. Preserved ${Object.keys(n).length} repo scores.`),s}function Wi(e){O(ne,"Migrating state from v2 to v3 (drop dead fields, add learnings tracking)..."),delete e.events,delete e.dailyActivityCounts;let t=e.config;return t&&(delete t.showHealthCheck,delete t.scoreThreshold),e.version=3,O(ne,"v2 to v3 migration complete."),e}function Vi(e){return O(ne,"Migrating state from v3 to v4 (add commentsFetchedAt to stored PR records)..."),e.version=4,O(ne,"v3 to v4 migration complete (no data transformation required)."),e}function bn(){return Gt.parse({version:4})}function az(){let e=jt(),t=LA(),r=MA();if(ie.existsSync(e)||!ie.existsSync(t))return!1;O(ne,"Migrating state from ./data/ to ~/.oss-autopilot/...");try{if(ur(),ie.copyFileSync(t,e),O(ne,`Migrated state file to ${e}`),ie.existsSync(r)){let s=Ys(),o=ie.readdirSync(r).filter(i=>i.startsWith("state-")&&i.endsWith(".json"));for(let i of o){let a=yn.join(r,i),c=yn.join(s,i);ie.copyFileSync(a,c)}O(ne,`Migrated ${o.length} backup files`)}if(ie.unlinkSync(t),O(ne,"Removed legacy state file"),ie.existsSync(r)){let s=ie.readdirSync(r);for(let o of s)ie.unlinkSync(yn.join(r,o));ie.rmdirSync(r)}let n=yn.dirname(t);return ie.existsSync(n)&&ie.readdirSync(n).length===0&&(ie.rmdirSync(n),O(ne,"Removed empty legacy data directory")),O(ne,"Migration complete!"),!0}catch(n){if(v(ne,`Failed to migrate state: ${I(n)}`),ie.existsSync(e)&&ie.existsSync(t))try{ie.unlinkSync(e),O(ne,"Cleaned up partial migration - removed incomplete new state file")}catch(s){v(ne,"Could not clean up partial migration file"),O(ne,"Partial migration cleanup failed",s)}return v(ne,"To resolve this issue:"),v(ne," 1. Ensure you have write permissions to ~/.oss-autopilot/"),v(ne," 2. Check available disk space"),v(ne," 3. Manually copy ./data/state.json to ~/.oss-autopilot/state.json"),v(ne," 4. Or delete ./data/state.json to start fresh"),!1}}function zA(){let e=Ys();if(!ie.existsSync(e))return null;let t=ie.readdirSync(e).filter(r=>r.startsWith("state-")&&r.endsWith(".json")).sort().reverse();for(let r of t){let n=yn.join(e,r);try{let s=ie.readFileSync(n,"utf8"),o=JSON.parse(s);if(typeof o=="object"&&o!==null){let c=o;c.version===1&&(o=Hi(c)),o.version===2&&(o=Wi(o)),o.version===3&&(o=Vi(o))}let i=Gt.safeParse(o);if(i.success){let c=i.data;O(ne,`Successfully restored state from backup: ${r}`);let u=Object.keys(c.repoScores).length;O(ne,`Restored state v${c.version}: ${u} repo scores`);let d=jt();return Or(d,Ar(c),384),O(ne,"Restored backup written to main state file"),c}let a=i.error.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join("; ");v(ne,`Backup ${r} failed schema validation: ${a}`),O(ne,`Backup ${r} full validation errors:`,i.error.issues)}catch(s){let o=s instanceof Error?s.message:String(s);v(ne,`Backup ${r} is corrupted (${o}), trying next...`),O(ne,`Backup ${r} parse failed`,s)}}return null}function BA(e){try{let t=e+".rejected-"+Date.now();return ie.copyFileSync(e,t),v(ne,`Previous state preserved at: ${t}`),t}catch(t){return v(ne,`Could not preserve rejected state file: ${I(t)}`),null}}function Xs(e,t,r){let n=TA(e,t);n>0&&v(ne,`${r} has ${n} unreadable work claim(s); they were dropped`)}function cm(){az();let e=jt();try{if(ie.existsSync(e)){let t=Bi(e),r=ie.readFileSync(e,"utf8"),n=JSON.parse(r),s=!1;if(typeof n=="object"&&n!==null){let u=n;u.version===1&&(n=Hi(u),s=!0),n.version===2&&(n=Wi(n),s=!0),n.version===3&&(n=Vi(n),s=!0)}let o=Hp(n);o.length>0&&v(ne,`State file (fields: ${o.join(", ")}) ${Wp}`);let i=Gt.safeParse(n);if(!i.success){let u=i.error.issues.map(f=>`${f.path.join(".")}: ${f.message}`).join("; ");v(ne,`Invalid state file structure: ${u}`),v(ne,"Attempting to restore from backup..."),O(ne,"Full validation errors:",i.error.issues);let d=BA(e),p=`Invalid state file structure: ${u}`,m=zA();if(m){let f=Bi(e);return{state:m,mtimeMs:f,recovery:{source:"backup",rejectedPath:d,reason:p}}}return v(ne,"No valid backup found, starting fresh"),{state:bn(),mtimeMs:0,recovery:{source:"fresh",rejectedPath:d,reason:p}}}s&&(Or(e,Ar(i.data),384),t=Bi(e),O(ne,"Migrated and validated state saved"));let a=i.data;Xs(n,a,"State file");let c=Object.keys(a.repoScores).length;return O(ne,`Loaded state v${a.version}: ${c} repo scores tracked`),{state:a,mtimeMs:t}}}catch(t){let r=t?.code;if(r==="EACCES"||r==="EPERM")throw new Error(`Permission denied reading state file (${r}): ${I(t)}. This is an environment problem, not state corruption. Check the ownership and permissions of ~/.oss-autopilot/state.json (e.g. run \`ls -l ~/.oss-autopilot/state.json\` and fix with chown/chmod), then retry.`,{cause:t});v(ne,"Error loading state:",t),v(ne,"Attempting to restore from backup...");let n=ie.existsSync(e)?BA(e):null,s=`Error loading state: ${I(t)}`,o=zA();if(o){let i=Bi(e);return{state:o,mtimeMs:i,recovery:{source:"backup",rejectedPath:n,reason:s}}}return v(ne,"No valid backup found, starting fresh"),{state:bn(),mtimeMs:0,recovery:{source:"fresh",rejectedPath:n,reason:s}}}return O(ne,"No existing state found, initializing..."),{state:bn(),mtimeMs:0}}function Bi(e){try{return ie.statSync(e).mtimeMs}catch(t){return O(ne,`Could not read state file mtime (reload detection will always trigger): ${I(t)}`),0}}function cz(){let e=Ys();try{let t=ie.readdirSync(e).filter(r=>r.startsWith("state-")).sort().reverse();for(let r of t.slice(10))try{ie.unlinkSync(yn.join(e,r))}catch(n){v(ne,`Could not delete old backup ${r}:`,I(n))}}catch(t){v(ne,"Could not clean up backups:",I(t))}}function VA(e,t=null){let r=jt(),n=r+".lock",s=Ys();HA(n);try{if(t!==null&&t>0&&ie.existsSync(r)){let i=Bi(r);if(i!==t)throw new Tr(t,i)}try{if(ie.existsSync(r)){let i=new Date().toISOString().replaceAll(/[.:]/g,"-"),a=Math.random().toString(36).slice(2,8).padEnd(6,"0"),c=yn.join(s,`state-${i}-${a}.json`);ie.copyFileSync(r,c),ie.chmodSync(c,384),cz()}}catch(i){v(ne,`Could not create backup before save: ${I(i)}`)}Or(r,Ar(e),384);let o=Bi(r);return O(ne,"State saved successfully"),o}finally{WA(n)}}function qA(e){try{let t=jt();if(ie.statSync(t).mtimeMs===e)return null;let n=cm();if(n.recovery)try{n.mtimeMs=ie.statSync(t).mtimeMs}catch(s){O(ne,"Could not re-read mtime after reload (will retry next cycle)",s)}return n}catch(t){return v(ne,`Failed to reload state from disk: ${I(t)}`),null}}var ie,yn,ne,oz,pu=A(()=>{"use strict";ie=B(require("node:fs"),1),yn=B(require("node:path"),1);gn();Ui();Vr();ee();ce();ne="state",oz=3e4});function qr(e,t){return e===void 0||e<t}var xS,uz,um,eo,to,lz,ts=A(()=>{"use strict";gn();xS=Bp.parse({}),uz=Gt.parse({version:4}),um=_S.options,eo=vS.options,to=kS.options,lz={beginner:["good first issue","help wanted","easy","up-for-grabs","first-timers-only","beginner"],intermediate:["enhancement","feature","feature-request","contributions welcome"],advanced:["proposal","RFC","accepted","design"]}});function Sz(e){return{repo:e,score:YA,mergedPRCount:0,closedWithoutMergeCount:0,avgResponseDays:null,lastEvaluatedAt:new Date().toISOString(),signals:{hasActiveMaintainers:!0,isResponsive:!1,hasHostileComments:!1}}}function _z(e){let t=YA;if(e.mergedPRCount>0){let r=Math.min(Math.round(Math.log2(e.mergedPRCount+1)*dz),pz);t+=r}if(t-=Math.min(e.closedWithoutMergeCount,mz),e.lastMergedAt){let r=new Date(e.lastMergedAt);isNaN(r.getTime())?v(qi,`Invalid lastMergedAt date for ${e.repo}: "${e.lastMergedAt}". Skipping recency bonus.`):Math.floor((Date.now()-r.getTime())/864e5)<=fz&&(t+=gz)}return e.signals.isResponsive&&(t+=hz),e.signals.hasHostileComments&&(t-=yz),Math.max(bz,Math.min(wz,t))}function QA(e,t){return e.repoScores[t]}function ZA(e){return JSON.stringify([e.mergedPRCount,e.closedWithoutMergeCount,e.avgResponseDays??null,e.lastMergedAt??null,e.signals.hasActiveMaintainers,e.signals.isResponsive,e.signals.hasHostileComments])}function DS(e,t,r){let n=!e.repoScores[t];n&&(e.repoScores[t]=Sz(t));let s=e.repoScores[t],o=ZA(s);r.mergedPRCount!==void 0&&(s.mergedPRCount=r.mergedPRCount),r.closedWithoutMergeCount!==void 0&&(s.closedWithoutMergeCount=r.closedWithoutMergeCount),r.avgResponseDays!==void 0&&(s.avgResponseDays=r.avgResponseDays),r.lastMergedAt!==void 0&&(s.lastMergedAt=r.lastMergedAt),r.stargazersCount!==void 0&&(s.stargazersCount=r.stargazersCount),r.language!==void 0&&(s.language=r.language),r.signals&&(s.signals={...s.signals,...r.signals}),s.score=_z(s),(n||ZA(s)!==o)&&(s.lastEvaluatedAt=new Date().toISOString()),O(qi,`Updated repo score for ${t}: ${s.score}/10`)}function XA(e){return Object.values(e.repoScores).filter(t=>t.mergedPRCount>0).sort((t,r)=>r.mergedPRCount-t.mergedPRCount).map(t=>t.repo)}function eT(e){return Object.values(e.repoScores).filter(t=>t.mergedPRCount===0&&t.closedWithoutMergeCount===0).sort((t,r)=>r.score-t.score).map(t=>t.repo)}function tT(e,t){let r=t??e.config.minRepoScoreThreshold;return Object.values(e.repoScores).filter(n=>n.score>=r).sort((n,s)=>s.score-n.score).map(n=>n.repo)}function rT(e,t){let r=t??e.config.minRepoScoreThreshold,n=Date.now();return Object.values(e.repoScores).filter(s=>{if(s.score>r)return!1;let o=n-new Date(s.lastEvaluatedAt).getTime();return Number.isFinite(o)?o<=Rz:(v(qi,`Invalid lastEvaluatedAt for repo ${s.repo}: "${s.lastEvaluatedAt}", treating as stale`),!1)}).sort((s,o)=>s.score-o.score).map(s=>s.repo)}function KA(e){let t=new Map;for(let r of e){let n=q(r.url);if(!n){v(qi,`Skipping PR with unparseable URL during reconciliation: "${r.url}"`);continue}let s=`${n.owner}/${n.repo}`;t.set(s,(t.get(s)??0)+1)}return t}function nT(e,t,r){let n=JA(e,KA(t),"mergedPRCount"),s=JA(e,KA(r),"closedWithoutMergeCount");return n||s}function JA(e,t,r){let n=!1;for(let[s,o]of t){let i=e.repoScores[s]?.[r]??0;o>i&&(O(qi,`Reconciling ${s} ${r}: ${i} \u2192 ${o}`),DS(e,s,{[r]:o}),n=!0)}return n}function sT(e,t){let r=new Set(t.map(o=>o.url)),n=new Map;for(let o of t){let i=q(o.url);!i||!o.title||n.set(`${i.number}\0${o.title}`,`${i.owner}/${i.repo}`)}let s=new Map;for(let o of e){let i=r.has(o.url)||!o.title?null:q(o.url);if(!i)continue;let a=`${i.owner}/${i.repo}`,c=n.get(`${i.number}\0${o.title}`);c&&c!==a&&s.set(a,c)}return s}function oT(e,t,r){let n=`https://github.com/${t}/`,s=`https://github.com/${r}/`,o=a=>{if(!a?.some(d=>d.url.startsWith(n)))return a;let c=new Set;return a.map(d=>{if(!d.url.startsWith(n))return d;let p=s+d.url.slice(n.length);return c.add(p),{...d,url:p}}).filter((d,p)=>!c.has(d.url)||a[p].url.startsWith(n))};e.mergedPRs=o(e.mergedPRs),e.closedPRs=o(e.closedPRs);let i=e.repoScores[t];i&&(Object.hasOwn(e.repoScores,r)||(e.repoScores[r]={...i,repo:r}),delete e.repoScores[t]),O(qi,`Renamed transferred repo ${t} \u2192 ${r}`)}function iT(e){let t=0,r=0,n=0;for(let i of Object.values(e.repoScores))qr(i.stargazersCount,e.config.minStars??50)||(n++,t+=i.mergedPRCount,r+=i.closedWithoutMergeCount);let s=t+r,o=s>0?t/s*100:0;return{mergedPRs:t,closedPRs:r,activeIssues:0,trustedProjects:e.config.trustedProjects.length,mergeRate:o.toFixed(1)+"%",totalTracked:n,needsResponse:0}}var qi,YA,dz,pz,mz,fz,gz,hz,yz,bz,wz,Rz,LS=A(()=>{"use strict";ts();ce();nt();qi="scoring",YA=5,dz=2,pz=5,mz=3,fz=90,gz=1,hz=1,yz=2,bz=1,wz=10,Rz=720*60*60*1e3});function aT(e){return e?e.etag??e.ETag??null:null}function MS(e,t){try{let r=`${es()}.rejected-${Date.now()}`;return Zr.writeFileSync(r,e,{encoding:"utf8",mode:384}),r}catch(r){return v(Pe,`Could not preserve rejected Gist content for ${t}: ${r instanceof Error?r.message:String(r)}`),null}}var Zr,Pe,FS,wn,kz,cT,Cz,Pz,uT,Zi,NS=A(()=>{"use strict";Zr=B(require("node:fs"),1);gn();Ui();pu();Vr();ce();ee();Pe="gist-store";FS="oss-autopilot-state",wn="state.json",kz=900*1024,cT=10*1024*1024,Cz="gist.githubusercontent.com",Pz=100*1024,uT=new Map,Zi=class e{gistId=null;cachedFiles=new Map;dirtyFiles=new Set;baselineFiles=new Map;lastFetchedEtag=null;octokit;lastRefreshAt=0;static REFRESH_THROTTLE_MS=3e4;lastRefreshError=null;constructor(t){this.octokit=t}async bootstrap(){try{await this.checkGistScope();let t=this.readLocalGistId();if(t){O(Pe,`Found local Gist ID: ${t}`);try{this.gistId=t;let o=await this.fetchAndCache(t);return{gistId:t,state:o,created:!1}}catch(o){if(o instanceof Te||zt(o))throw o;v(Pe,`Failed to fetch Gist ${t}, will search/create`,o)}}let r=await this.searchForGist();if(r){O(Pe,`Found Gist via search: ${r}`),this.gistId=r,this.writeLocalGistId(r);let o=await this.fetchAndCache(r);return{gistId:r,state:o,created:!1}}O(Pe,"No existing Gist found, creating new one");let{id:n,state:s}=await this.createGist();return this.writeLocalGistId(n),{gistId:n,state:s,created:!0}}catch(t){if(t instanceof Te||zt(t))throw t;this.gistId=null,this.lastFetchedEtag=null,v(Pe,"All Gist API paths failed, entering degraded mode",t);let r=es(),n=null;try{if(Zr.existsSync(r)){n=Zr.readFileSync(r,"utf8");let s=JSON.parse(n);if(typeof s=="object"&&s!==null){let i=s;i.version===1&&(s=Hi(i)),s.version===2&&(s=Wi(s)),s.version===3&&(s=Vi(s))}let o=Gt.parse(s);return Xs(s,o,"Local state cache"),O(Pe,"Loaded state from local cache in degraded mode"),{gistId:"",state:o,created:!1,degraded:!0}}}catch(s){if(n){let o=MS(n,"local-cache");v(Pe,`Local state cache failed to parse in degraded mode: ${s instanceof Error?s.message:String(s)}. Corrupt cache preserved at: ${o??"(could not preserve)"}`)}else v(Pe,`Failed to read local cache in degraded mode: ${s instanceof Error?s.message:String(s)}`)}return O(Pe,"No local cache found, returning fresh state in degraded mode"),{gistId:"",state:bn(),created:!1,degraded:!0}}}async bootstrapWithMigration(t){try{await this.checkGistScope();let r=this.readLocalGistId();if(r){O(Pe,`bootstrapWithMigration: found local Gist ID: ${r}`);try{this.gistId=r;let i=await this.fetchAndCache(r);return{gistId:r,state:i,created:!1,migrated:!1}}catch(i){if(i instanceof Te||zt(i))throw i;v(Pe,`bootstrapWithMigration: failed to fetch Gist ${r}, will search/create`,i)}}let n=await this.searchForGist();if(n){O(Pe,`bootstrapWithMigration: found Gist via search: ${n}`),this.gistId=n,this.writeLocalGistId(n);let i=await this.fetchAndCache(n);return{gistId:n,state:i,created:!1,migrated:!1}}O(Pe,"bootstrapWithMigration: no existing Gist found, creating one seeded with local state");let{id:s,state:o}=await this.createGistFromState(t);return this.writeLocalGistId(s),{gistId:s,state:o,created:!0,migrated:!0}}catch(r){if(r instanceof Te||zt(r))throw r;this.gistId=null,this.lastFetchedEtag=null,v(Pe,"bootstrapWithMigration: all Gist API paths failed, entering degraded mode",r);let n=es(),s=null;try{if(Zr.existsSync(n)){s=Zr.readFileSync(n,"utf8");let o=JSON.parse(s);if(typeof o=="object"&&o!==null){let a=o;a.version===1&&(o=Hi(a)),o.version===2&&(o=Wi(o)),o.version===3&&(o=Vi(o))}let i=Gt.parse(o);return Xs(o,i,"Local state cache"),O(Pe,"bootstrapWithMigration: loaded state from local cache in degraded mode"),{gistId:"",state:i,created:!1,degraded:!0,migrated:!1}}}catch(o){if(s){let i=MS(s,"local-cache");v(Pe,`bootstrapWithMigration: local cache failed to parse: ${o instanceof Error?o.message:String(o)}. Corrupt cache preserved at: ${i??"(could not preserve)"}`)}else v(Pe,`bootstrapWithMigration: failed to read local cache: ${o instanceof Error?o.message:String(o)}`)}return O(Pe,"bootstrapWithMigration: no local cache found, returning existing state in degraded mode"),{gistId:"",state:t,created:!1,degraded:!0,migrated:!1}}}getGistId(){return this.gistId}markDirty(t){this.dirtyFiles.add(t)}getDocument(t){return this.cachedFiles.get(t)??null}setDocument(t,r){this.cachedFiles.set(t,r),this.markDirty(t)}listDocuments(t){let r=[];for(let n of this.cachedFiles.keys())n.startsWith(t)&&r.push(n);return r}setState(t){this.cachedFiles.set(wn,t),this.markDirty(wn)}async push(){if(this.dirtyFiles.size===0)return!0;if(this.gistId===null)throw new Error("GistStateStore: cannot push before bootstrap \u2014 gistId is null");this.checkPushSize();let t=()=>{let o={};for(let i of this.dirtyFiles){let a=this.cachedFiles.get(i);a!==void 0&&(o[i]={content:a})}return o},r=async()=>{try{let o={gist_id:this.gistId,files:t()},i=await this.octokit.gists.update(o),a=aT(i.headers);return a&&(this.lastFetchedEtag=a),{ok:!0}}catch(o){return{ok:!1,status:o.status,err:o}}};if(this.dirtyFiles.has(wn)){let o={};for(let f of this.dirtyFiles){let g=this.cachedFiles.get(f);g!==void 0&&(o[f]=g)}let i=new Map(this.cachedFiles),a=new Map(this.baselineFiles),c=this.lastFetchedEtag,u=a.get(wn),d=()=>{for(let[f,g]of Object.entries(o))this.cachedFiles.set(f,g)},p=()=>{this.cachedFiles.clear();for(let[f,g]of i)this.cachedFiles.set(f,g);this.baselineFiles=a,this.lastFetchedEtag=c,d()};try{await this.fetchAndCache(this.gistId)}catch(f){throw v(Pe,`Pre-write re-read failed: ${I(f)}`),p(),f instanceof lu||f instanceof $r||zt(f)?f:new Qt(c,null)}let m=this.cachedFiles.get(wn);if(u!==m){v(Pe,"state.json changed remotely since our last fetch; surfacing GistConcurrencyError instead of clobbering (#1235, #1510)");let f=this.lastFetchedEtag;throw p(),new Qt(c,f)}d()}let n=await r();if(!n.ok&&(O(Pe,`push failed on first attempt, retrying: ${n.err}`),n=await r(),!n.ok))return v(Pe,`push failed after retry, giving up: ${n.err}`),!1;if(this.dirtyFiles.clear(),this.baselineFiles=new Map(this.cachedFiles),this.cachedFiles.get(wn))try{let o=this.parseStateFromCache();this.writeLocalStateCache(o)}catch(o){O(Pe,`push succeeded but local cache write failed: ${o}`)}return!0}async refreshFromGist(t={}){if(!this.gistId)return{status:"no-gist"};let r=Date.now(),n=r-this.lastRefreshAt;if(n<e.REFRESH_THROTTLE_MS&&!t.force)return{status:"throttled",sinceLastMs:n};this.lastRefreshAt=r;try{return await this.fetchAndCache(this.gistId),this.lastRefreshError=null,{status:"refreshed"}}catch(s){let o=s instanceof Error?s:new Error(String(s));return v(Pe,`refreshFromGist failed: ${o.message}`),this.lastRefreshError=o,{status:"error",error:o}}}checkPushSize(){for(let t of this.dirtyFiles){let r=this.cachedFiles.get(t);if(r===void 0)continue;let n=Buffer.byteLength(r,"utf8");if(n>cT)throw new $r(`Refusing to push Gist file ${t}: ${n} bytes exceeds the ${cT}-byte limit the Gist API can serve back. The local change is kept in memory but was not synced.`);if(n>kz){let s=Math.floor(n/Pz);(uT.get(t)??-1)<s&&(uT.set(t,s),v(Pe,`Gist file ${t} is ${n} bytes, near or past the 1 MB the Gist API returns inline. Reads fall back to raw_url, which works up to 10 MB; to stay well under that, trim large state fields (repoScores and searchSeen are usually the biggest).`))}}}async checkGistScope(){try{await this.octokit.gists.list({per_page:1,page:1})}catch(t){if(zt(t))throw t;let r=t.status;throw r===401||r===403?new zi:t}}async fetchAndCache(t){let r=await this.octokit.gists.get({gist_id:t});this.gistId=t;let n=new Map;for(let[o,i]of Object.entries(r.data.files)){if(!i)continue;let a=i.truncated?await this.fetchRawContent(o,i.raw_url):i.content;a!=null&&n.set(o,a)}this.lastFetchedEtag=aT(r.headers),this.cachedFiles.clear();for(let[o,i]of n)this.cachedFiles.set(o,i);this.baselineFiles=new Map(this.cachedFiles);let s=this.parseStateFromCache();return this.writeLocalStateCache(s),s}async fetchRawContent(t,r){let n=a=>new $r(`Gist file ${t} is larger than the 1 MB the Gist API returns inline and its full content could not be read from raw_url (${a}). Local state was left unchanged.`);if(!this.octokit.request)throw n("no HTTP client available");if(!r)throw n("the API returned no raw_url");let s=URL.canParse(r)?new URL(r):void 0;if((s?.protocol==="https:"?s.hostname:"")!==Cz)throw n("unexpected raw_url host");let i;try{({data:i}=await this.octokit.request({method:"GET",url:r}))}catch(a){throw zt(a)||im(a)?a:n(I(a))}if(typeof i!="string")throw n("response body was not text");return i}parseStateFromCache(){let t=this.cachedFiles.get(wn);if(!t)return O(Pe,"No state.json found in Gist, using fresh state"),bn();try{let r=JSON.parse(t);if(typeof r=="object"&&r!==null){let o=r;o.version===1&&(r=Hi(o)),r.version===2&&(r=Wi(r)),r.version===3&&(r=Vi(r))}let n=Hp(r);n.length>0&&v(Pe,`Gist state (fields: ${n.join(", ")}) ${Wp}`);let s=Gt.parse(r);return Xs(r,s,"Gist state"),s}catch(r){let n=MS(t,this.gistId??"unknown");throw v(Pe,`Gist state.json failed to parse \u2014 refusing to overwrite with fresh state. Corrupt content preserved at: ${n??"(could not preserve)"}`),new lu(this.gistId??"unknown",n,r)}}async searchForGist(){try{for(let r=1;r<=10;r++){let{data:n}=await this.octokit.gists.list({per_page:100,page:r});if(n.length===0)break;let s=n.find(o=>o.description===FS);if(s)return s.id}}catch(t){if(zt(t))throw t;v(Pe,"Failed to search Gists by description",t)}return null}async createGist(){let t=bn(),r=Ar(t),{data:n}=await this.octokit.gists.create({description:FS,public:!1,files:{[wn]:{content:r}}});this.gistId=n.id,this.cachedFiles.clear();for(let[s,o]of Object.entries(n.files))o&&o.content!=null&&this.cachedFiles.set(s,o.content);return this.baselineFiles=new Map(this.cachedFiles),this.writeLocalStateCache(t),{id:n.id,state:t}}async createGistFromState(t){let r=Ar(t),{data:n}=await this.octokit.gists.create({description:FS,public:!1,files:{[wn]:{content:r}}});this.gistId=n.id,this.cachedFiles.clear();for(let[s,o]of Object.entries(n.files))o&&o.content!=null&&this.cachedFiles.set(s,o.content);return this.baselineFiles=new Map(this.cachedFiles),this.writeLocalStateCache(t),{id:n.id,state:t}}readLocalGistId(){try{let t=Qs();if(Zr.existsSync(t))return Zr.readFileSync(t,"utf8").trim()||null}catch(t){O(Pe,"Could not read local Gist ID file",t)}return null}writeLocalGistId(t){try{let r=Qs();Or(r,t,384),O(Pe,`Wrote Gist ID to ${r}`)}catch(r){v(Pe,`Failed to write local Gist ID file: ${r}`)}}writeLocalStateCache(t){try{let r=es();Or(r,Ar(t),384),O(Pe,`Wrote state cache to ${r}`)}catch(r){v(Pe,`Failed to write local state cache: ${r}`)}}}});function fu(e){if(!e.includes("/"))throw new _r(`Invalid repo identifier "${e}". Expected "owner/repo" format.`,"INVALID_REPO_ID");let[t,r]=e.split("/",2);return`${Ki}${t}--${r}${GS}`}function US(e){if(!e.startsWith(Ki)||!e.endsWith(GS))return null;let t=e.slice(Ki.length,e.length-GS.length),r=t.indexOf("--");if(r===-1)return null;let n=t.slice(0,r),s=t.slice(r+2);return!n||!s?null:`${n}/${s}`}function lT(e,t){if(!e)return null;let r=e.getDocument(fu(t));return r===null||r===""?null:r}function dT(e,t,r){if(!e)throw new rs;let n=Buffer.byteLength(r,"utf8");if(n>lm)throw new mu(n);e.setDocument(fu(t),r)}function pT(e,t){if(!e)throw new rs;e.setDocument(fu(t),"")}function mT(e){if(!e)return[];let t=e.listDocuments(Ki),r=[];for(let n of t){let s=US(n);if(!s)continue;let o=e.getDocument(n);o===null||o===""||r.push(s)}return r.sort()}var Ki,lm,GS,rs,mu,jS=A(()=>{"use strict";ee();Ki="guidelines--",lm=8192,GS=".md";rs=class extends _r{constructor(t){super(t??"Per-repo guidelines require Gist persistence. Run `oss-autopilot setup` to enable Gist sync, then retry.","GUIDELINES_NOT_AVAILABLE"),this.name="GuidelinesNotAvailableError"}},mu=class extends _r{constructor(t,r=lm){super(`Guidelines content is ${t} bytes, exceeding the ${r}-byte cap. Trim or split across categories.`,"GUIDELINES_TOO_LARGE"),this.name="GuidelinesTooLargeError"}}});function Ji(e,t={}){return`Gist persistence is configured but ${typeof e=="string"?Az[e]:e.reason}; writes are LOCAL-ONLY and may be overwritten by the next successful Gist sync.${t.retryHint?` ${t.retryHint}`:""}`}var Az,zS=A(()=>{"use strict";Az={"no-token":"no GitHub token was available","state-unreadable":"the state file could not be read","init-fallback":"initialization hit a transient network failure","configured-but-local":"this process is running local-only (Gist init has not succeeded)","bootstrap-degraded":"the Gist bootstrap fell back to the local cache (reads may be stale and pushes are failing)"}});function ns(){return typeof navigator=="object"&&"userAgent"in navigator?navigator.userAgent:typeof process=="object"&&process.version!==void 0?`Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`:"<environment undetectable>"}var gu=A(()=>{});function dm(e,t,r,n){if(typeof r!="function")throw new Error("method for before hook must be a function");return n||(n={}),Array.isArray(t)?t.reverse().reduce((s,o)=>dm.bind(null,e,o,s,n),r)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((s,o)=>o.hook.bind(null,s,n),r)():r(n))}var fT=A(()=>{});function gT(e,t,r,n){let s=n;e.registry[r]||(e.registry[r]=[]),t==="before"&&(n=(o,i)=>Promise.resolve().then(s.bind(null,i)).then(o.bind(null,i))),t==="after"&&(n=(o,i)=>{let a;return Promise.resolve().then(o.bind(null,i)).then(c=>(a=c,s(a,i))).then(()=>a)}),t==="error"&&(n=(o,i)=>Promise.resolve().then(o.bind(null,i)).catch(a=>s(a,i))),e.registry[r].push({hook:n,orig:s})}var hT=A(()=>{});function yT(e,t,r){if(!e.registry[t])return;let n=e.registry[t].map(s=>s.orig).indexOf(r);n!==-1&&e.registry[t].splice(n,1)}var bT=A(()=>{});function ST(e,t,r){let n=RT(yT,null).apply(null,r?[t,r]:[t]);e.api={remove:n},e.remove=n,["before","error","after","wrap"].forEach(s=>{let o=r?[t,s,r]:[t,s];e[s]=e.api[s]=RT(gT,null).apply(null,o)})}function Tz(){let e=Symbol("Singular"),t={registry:{}},r=dm.bind(null,t,e);return ST(r,t,e),r}function $z(){let e={registry:{}},t=dm.bind(null,e);return ST(t,e),t}var wT,RT,_T,vT=A(()=>{fT();hT();bT();wT=Function.bind,RT=wT.bind(wT);_T={Singular:Tz,Collection:$z}});function Dz(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function Lz(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}function PT(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(n=>{Lz(t[n])?n in e?r[n]=PT(e[n],t[n]):Object.assign(r,{[n]:t[n]}):Object.assign(r,{[n]:t[n]})}),r}function kT(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function HS(e,t,r){if(typeof t=="string"){let[s,o]=t.split(" ");r=Object.assign(o?{method:s,url:o}:{url:s},r)}else r=Object.assign({},t);r.headers=Dz(r.headers),kT(r),kT(r.headers);let n=PT(e||{},r);return r.url==="/graphql"&&(e&&e.mediaType.previews?.length&&(n.mediaType.previews=e.mediaType.previews.filter(s=>!n.mediaType.previews.includes(s)).concat(n.mediaType.previews)),n.mediaType.previews=(n.mediaType.previews||[]).map(s=>s.replace(/-preview/,""))),n}function Mz(e,t){let r=/\?/.test(e)?"&":"?",n=Object.keys(t);return n.length===0?e:e+r+n.map(s=>s==="q"?"q="+t.q.split("+").map(encodeURIComponent).join("+"):`${s}=${encodeURIComponent(t[s])}`).join("&")}function Nz(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function Gz(e){let t=e.match(Fz);return t?t.map(Nz).reduce((r,n)=>r.concat(n),[]):[]}function CT(e,t){let r={__proto__:null};for(let n of Object.keys(e))t.indexOf(n)===-1&&(r[n]=e[n]);return r}function ET(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(t){return/%[0-9A-Fa-f]/.test(t)||(t=encodeURI(t).replace(/%5B/g,"[").replace(/%5D/g,"]")),t}).join("")}function Qi(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function hu(e,t,r){return t=e==="+"||e==="#"?ET(t):Qi(t),r?Qi(r)+"="+t:t}function Yi(e){return e!=null}function BS(e){return e===";"||e==="&"||e==="?"}function Uz(e,t,r,n){var s=e[r],o=[];if(Yi(s)&&s!=="")if(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")s=s.toString(),n&&n!=="*"&&(s=s.substring(0,parseInt(n,10))),o.push(hu(t,s,BS(t)?r:""));else if(n==="*")Array.isArray(s)?s.filter(Yi).forEach(function(i){o.push(hu(t,i,BS(t)?r:""))}):Object.keys(s).forEach(function(i){Yi(s[i])&&o.push(hu(t,s[i],i))});else{let i=[];Array.isArray(s)?s.filter(Yi).forEach(function(a){i.push(hu(t,a))}):Object.keys(s).forEach(function(a){Yi(s[a])&&(i.push(Qi(a)),i.push(hu(t,s[a].toString())))}),BS(t)?o.push(Qi(r)+"="+i.join(",")):i.length!==0&&o.push(i.join(","))}else t===";"?Yi(s)&&o.push(Qi(r)):s===""&&(t==="&"||t==="?")?o.push(Qi(r)+"="):s===""&&o.push("");return o}function jz(e){return{expand:zz.bind(null,e)}}function zz(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(n,s,o){if(s){let a="",c=[];if(r.indexOf(s.charAt(0))!==-1&&(a=s.charAt(0),s=s.substr(1)),s.split(/,/g).forEach(function(u){var d=/([^:\*]*)(?::(\d+)|(\*))?/.exec(u);c.push(Uz(t,a,d[1],d[2]||d[3]))}),a&&a!=="+"){var i=",";return a==="?"?i="&":a!=="#"&&(i=a),(c.length!==0?a:"")+c.join(i)}else return c.join(",")}else return ET(o)}),e==="/"?e:e.replace(/\/$/,"")}function AT(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),n=Object.assign({},e.headers),s,o=CT(e,["method","baseUrl","url","headers","request","mediaType"]),i=Gz(r);r=jz(r).expand(o),/^http/.test(r)||(r=e.baseUrl+r);let a=Object.keys(e).filter(d=>i.includes(d)).concat("baseUrl"),c=CT(o,a);if(!/application\/octet-stream/i.test(n.accept)&&(e.mediaType.format&&(n.accept=n.accept.split(/,/).map(d=>d.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(",")),r.endsWith("/graphql")&&e.mediaType.previews?.length)){let d=n.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[];n.accept=d.concat(e.mediaType.previews).map(p=>{let m=e.mediaType.format?`.${e.mediaType.format}`:"+json";return`application/vnd.github.${p}-preview${m}`}).join(",")}return["GET","HEAD"].includes(t)?r=Mz(r,c):"data"in c?s=c.data:Object.keys(c).length&&(s=c),!n["content-type"]&&typeof s<"u"&&(n["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(t)&&typeof s>"u"&&(s=""),Object.assign({method:t,url:r,headers:n},typeof s<"u"?{body:s}:null,e.request?{request:e.request}:null)}function Bz(e,t,r){return AT(HS(e,t,r))}function TT(e,t){let r=HS(e,t),n=Bz.bind(null,r);return Object.assign(n,{DEFAULTS:r,defaults:TT.bind(null,r),merge:HS.bind(null,r),parse:AT})}var Oz,Iz,xz,Fz,$T,OT=A(()=>{gu();Oz="0.0.0-development",Iz=`octokit-endpoint.js/${Oz} ${ns()}`,xz={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":Iz},mediaType:{format:""}};Fz=/\{[^{}}]+\}/g;$T=TT(null,xz)});var LT=bC((j5,yu)=>{"use strict";var fm=function(){};fm.prototype=Object.create(null);var pm=/; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu,mm=/\\([\v\u0020-\u00ff])/gu,IT=/^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u,ro={type:"",parameters:new fm};Object.freeze(ro.parameters);Object.freeze(ro);function xT(e){if(typeof e!="string")throw new TypeError("argument header is required and must be a string");let t=e.indexOf(";"),r=t!==-1?e.slice(0,t).trim():e.trim();if(IT.test(r)===!1)throw new TypeError("invalid media type");let n={type:r.toLowerCase(),parameters:new fm};if(t===-1)return n;let s,o,i;for(pm.lastIndex=t;o=pm.exec(e);){if(o.index!==t)throw new TypeError("invalid parameter format");t+=o[0].length,s=o[1].toLowerCase(),i=o[2],i[0]==='"'&&(i=i.slice(1,i.length-1),mm.test(i)&&(i=i.replace(mm,"$1"))),n.parameters[s]=i}if(t!==e.length)throw new TypeError("invalid parameter format");return n}function DT(e){if(typeof e!="string")return ro;let t=e.indexOf(";"),r=t!==-1?e.slice(0,t).trim():e.trim();if(IT.test(r)===!1)return ro;let n={type:r.toLowerCase(),parameters:new fm};if(t===-1)return n;let s,o,i;for(pm.lastIndex=t;o=pm.exec(e);){if(o.index!==t)return ro;t+=o[0].length,s=o[1].toLowerCase(),i=o[2],i[0]==='"'&&(i=i.slice(1,i.length-1),mm.test(i)&&(i=i.replace(mm,"$1"))),n.parameters[s]=i}return t!==e.length?ro:n}yu.exports.default={parse:xT,safeParse:DT};yu.exports.parse=xT;yu.exports.safeParse=DT;yu.exports.defaultContentType=ro});var Hz,NT,WS,MT,Wz,Vz,qz,GT,Zz,Kz,Jz,UT,FT,Yz,Qz,jT,zT=A(()=>{Hz=/^-?\d+$/,NT=/^-?\d+n+$/,WS=JSON.stringify,MT=JSON.parse,Wz=/^-?\d+n$/,Vz=/([\[:])?"(-?\d+)n"($|([\\n]|\s)*(\s|[\\n])*[,\}\]])/g,qz=/([\[:])?("-?\d+n+)n("$|"([\\n]|\s)*(\s|[\\n])*[,\}\]])/g,GT=(e,t,r)=>"rawJSON"in JSON?WS(e,(i,a)=>typeof a=="bigint"?JSON.rawJSON(a.toString()):typeof t=="function"?t(i,a):(Array.isArray(t)&&t.includes(i),a),r):e?WS(e,(i,a)=>typeof a=="string"&&!!a.match(NT)||typeof a=="bigint"?a.toString()+"n":typeof t=="function"?t(i,a):(Array.isArray(t)&&t.includes(i),a),r).replace(Vz,"$1$2$3").replace(qz,"$1$2$3"):WS(e,t,r),Zz=()=>JSON.parse("1",(e,t,r)=>!!r&&r.source==="1"),Kz=(e,t,r,n)=>typeof t=="string"&&t.match(Wz)?BigInt(t.slice(0,-1)):typeof t=="string"&&t.match(NT)?t.slice(0,-1):typeof n!="function"?t:n(e,t,r),Jz=(e,t)=>JSON.parse(e,(r,n,s)=>{let o=typeof n=="number"&&(n>Number.MAX_SAFE_INTEGER||n<Number.MIN_SAFE_INTEGER),i=s&&Hz.test(s.source);return o&&i?BigInt(s.source):typeof t!="function"?n:t(r,n,s)}),UT=Number.MAX_SAFE_INTEGER.toString(),FT=UT.length,Yz=/"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g,Qz=/^"-?\d+n+"$/,jT=(e,t)=>{if(!e)return MT(e,t);if(Zz())return Jz(e,t);let r=e.replace(Yz,(n,s,o,i)=>{let a=n[0]==='"';if(a&&!!n.match(Qz))return n.substring(0,n.length-1)+'n"';let u=o||i,d=s&&(s.length<FT||s.length===FT&&s<=UT);return a||u||d?n:'"'+n+'n"'});return MT(r,(n,s,o)=>Kz(n,s,o,t))}});var Rn,VS=A(()=>{Rn=class extends Error{name;status;request;response;constructor(t,r,n){super(t,{cause:n.cause}),this.name="HttpError",this.status=Number.parseInt(r),Number.isNaN(this.status)&&(this.status=0);"response"in n&&(this.response=n.response);let s=Object.assign({},n.request);n.request.headers.authorization&&(s.headers=Object.assign({},n.request.headers,{authorization:n.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),s.url=s.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=s}}});function t1(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}async function HT(e){let t=e.request?.fetch||globalThis.fetch;if(!t)throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");let r=e.request?.log||console,n=e.request?.parseSuccessResponseBody!==!1,s=t1(e.body)||Array.isArray(e.body)?GT(e.body):e.body,o=Object.fromEntries(Object.entries(e.headers).map(([p,m])=>[p,String(m)])),i;try{i=await t(e.url,{method:e.method,body:s,redirect:e.request?.redirect,headers:o,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(p){let m="Unknown Error";if(p instanceof Error){if(p.name==="AbortError")throw p.status=500,p;m=p.message,p.name==="TypeError"&&"cause"in p&&(p.cause instanceof Error?m=p.cause.message:typeof p.cause=="string"&&(m=p.cause))}let f=new Rn(m,500,{request:e});throw f.cause=p,f}let a=i.status,c=i.url,u={};for(let[p,m]of i.headers)u[p]=m;let d={url:c,status:a,headers:u,data:""};if("deprecation"in u){let p=u.link&&u.link.match(/<([^<>]+)>; rel="deprecation"/),m=p&&p.pop();r.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${u.sunset}${m?`. See ${m}`:""}`)}if(a===204||a===205)return d;if(e.method==="HEAD"){if(a<400)return d;throw new Rn(i.statusText,a,{response:d,request:e})}if(a===304)throw d.data=await qS(i),new Rn("Not modified",a,{response:d,request:e});if(a>=400)throw d.data=await qS(i),new Rn(n1(d.data),a,{response:d,request:e});return d.data=n?await qS(i):i.body,d}async function qS(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(BT);let r=(0,WT.safeParse)(t);if(r1(r)){let n="";try{return n=await e.text(),jT(n)}catch{return n}}else return r.type.startsWith("text/")||r.parameters.charset?.toLowerCase()==="utf-8"?e.text().catch(BT):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function r1(e){return e.type==="application/json"||e.type==="application/scim+json"}function n1(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return"Unknown error";if("message"in e){let t="documentation_url"in e?` - ${e.documentation_url}`:"";return Array.isArray(e.errors)?`${e.message}: ${e.errors.map(r=>JSON.stringify(r)).join(", ")}${t}`:`${e.message}${t}`}return`Unknown error: ${JSON.stringify(e)}`}function ZS(e,t){let r=e.defaults(t);return Object.assign(function(s,o){let i=r.merge(s,o);if(!i.request||!i.request.hook)return HT(r.parse(i));let a=(c,u)=>HT(r.parse(r.merge(c,u)));return Object.assign(a,{endpoint:r,defaults:ZS.bind(null,r)}),i.request.hook(a,i)},{endpoint:r,defaults:ZS.bind(null,r)})}var WT,Xz,e1,BT,bu,KS=A(()=>{OT();gu();WT=B(LT(),1);zT();VS();Xz="10.0.8",e1={headers:{"user-agent":`octokit-request.js/${Xz} ${ns()}`}};BT=()=>"";bu=ZS($T,e1);});function o1(e){return`Request failed due to following response errors:
67
67
  `+e.errors.map(t=>` - ${t.message}`).join(`
68
- `)}function u1(e,t,r){if(r){if(typeof t=="string"&&"query"in r)return Promise.reject(new Error('[@octokit/graphql] "query" cannot be used as variable name'));for(let i in r)if(c1.includes(i))return Promise.reject(new Error(`[@octokit/graphql] "${i}" cannot be used as variable name`))}let n=typeof t=="string"?Object.assign({query:t},r):t,s=Object.keys(n).reduce((i,a)=>a1.includes(a)?(i[a]=n[a],i):(i.variables||(i.variables={}),i.variables[a]=n[a],i),{}),o=n.baseUrl||e.endpoint.DEFAULTS.baseUrl;return VT.test(o)&&(s.url=o.replace(VT,"/api/graphql")),e(s).then(i=>{if(i.data.errors){let a={};for(let c of Object.keys(i.headers))a[c]=i.headers[c];throw new i1(s,a,i.data)}return i.data.data})}function JS(e,t){let r=e.defaults(t);return Object.assign((s,o)=>u1(r,s,o),{defaults:JS.bind(null,r),endpoint:r.endpoint})}function qT(e){return JS(e,{method:"POST",url:"/graphql"})}var s1,i1,a1,c1,VT,J5,ZT=A(()=>{KS();gu();s1="0.0.0-development";i1=class extends Error{constructor(e,t,r){super(o1(r)),this.request=e,this.headers=t,this.response=r,this.errors=r.errors,this.data=r.data,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}name="GraphqlResponseError";errors;data},a1=["method","baseUrl","url","headers","request","query","mediaType","operationName"],c1=["query","method","url"],VT=/\/api\/v3\/?$/;J5=JS(bu,{headers:{"user-agent":`octokit-graphql.js/${s1} ${ns()}`},method:"POST",url:"/graphql"})});async function d1(e){let t=l1(e),r=e.startsWith("v1.")||e.startsWith("ghs_"),n=e.startsWith("ghu_");return{type:"token",token:e,tokenType:t?"app":r?"installation":n?"user-to-server":"oauth"}}function p1(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function m1(e,t,r,n){let s=t.endpoint.merge(r,n);return s.headers.authorization=p1(e),t(s)}var YS,KT,JT,l1,YT,QT=A(()=>{YS="(?:[a-zA-Z0-9_-]+)",KT="\\.",JT=new RegExp(`^${YS}${KT}${YS}${KT}${YS}$`),l1=JT.test.bind(JT);YT=function(t){if(!t)throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");if(typeof t!="string")throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");return t=t.replace(/^(token|bearer) +/i,""),Object.assign(d1.bind(null,t),{hook:m1.bind(null,t)})}});var QS,XT=A(()=>{QS="7.0.6"});function h1(e={}){return typeof e.debug!="function"&&(e.debug=e$),typeof e.info!="function"&&(e.info=e$),typeof e.warn!="function"&&(e.warn=f1),typeof e.error!="function"&&(e.error=g1),e}var e$,f1,g1,t$,gm,r$=A(()=>{gu();vT();KS();ZT();QT();XT();e$=()=>{},f1=console.warn.bind(console),g1=console.error.bind(console);t$=`octokit-core.js/${QS} ${ns()}`,gm=class{static VERSION=QS;static defaults(t){return class extends this{constructor(...n){let s=n[0]||{};if(typeof t=="function"){super(t(s));return}super(Object.assign({},t,s,s.userAgent&&t.userAgent?{userAgent:`${s.userAgent} ${t.userAgent}`}:null))}}}static plugins=[];static plugin(...t){let r=this.plugins;return class extends this{static plugins=r.concat(t.filter(s=>!r.includes(s)))}}constructor(t={}){let r=new _T.Collection,n={baseUrl:bu.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},t.request,{hook:r.bind(null,"request")}),mediaType:{previews:[],format:""}};if(n.headers["user-agent"]=t.userAgent?`${t.userAgent} ${t$}`:t$,t.baseUrl&&(n.baseUrl=t.baseUrl),t.previews&&(n.mediaType.previews=t.previews),t.timeZone&&(n.headers["time-zone"]=t.timeZone),this.request=bu.defaults(n),this.graphql=qT(this.request).defaults(n),this.log=h1(t.log),this.hook=r,t.authStrategy){let{authStrategy:o,...i}=t,a=o(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:i},t.auth));r.wrap("request",a.hook),this.auth=a}else if(!t.auth)this.auth=async()=>({type:"unauthenticated"});else{let o=YT(t.auth);r.wrap("request",o.hook),this.auth=o}let s=this.constructor;for(let o=0;o<s.plugins.length;++o)Object.assign(this,s.plugins[o](this,t))}request;graphql;log;hook;auth}});var n$,s$=A(()=>{n$="6.0.0"});function XS(e){e.hook.wrap("request",(t,r)=>{e.log.debug("request",r);let n=Date.now(),s=e.request.endpoint.parse(r),o=s.url.replace(r.baseUrl,"");return t(r).then(i=>{let a=i.headers["x-github-request-id"];return e.log.info(`${s.method} ${o} - ${i.status} with id ${a} in ${Date.now()-n}ms`),i}).catch(i=>{let a=i.response?.headers["x-github-request-id"]||"UNKNOWN";throw e.log.error(`${s.method} ${o} - ${i.status} with id ${a} in ${Date.now()-n}ms`),i})})}var o$=A(()=>{s$();XS.VERSION=n$});function b1(e){if(!e.data)return{...e,data:[]};if(!(("total_count"in e.data||"total_commits"in e.data)&&!("url"in e.data)))return e;let r=e.data.incomplete_results,n=e.data.repository_selection,s=e.data.total_count,o=e.data.total_commits;delete e.data.incomplete_results,delete e.data.repository_selection,delete e.data.total_count,delete e.data.total_commits;let i=Object.keys(e.data)[0],a=e.data[i];return e.data=a,typeof r<"u"&&(e.data.incomplete_results=r),typeof n<"u"&&(e.data.repository_selection=n),e.data.total_count=s,e.data.total_commits=o,e}function e_(e,t,r){let n=typeof t=="function"?t.endpoint(r):e.request.endpoint(t,r),s=typeof t=="function"?t:e.request,o=n.method,i=n.headers,a=n.url;return{[Symbol.asyncIterator]:()=>({async next(){if(!a)return{done:!0};try{let c=await s({method:o,url:a,headers:i}),u=b1(c);if(a=((u.headers.link||"").match(/<([^<>]+)>;\s*rel="next"/)||[])[1],!a&&"total_commits"in u.data){let d=new URL(u.url),p=d.searchParams,m=parseInt(p.get("page")||"1",10),f=parseInt(p.get("per_page")||"250",10);m*f<u.data.total_commits&&(p.set("page",String(m+1)),a=d.toString())}return{value:u}}catch(c){if(c.status!==409)throw c;return a="",{value:{status:200,headers:{},data:[]}}}}})}}function i$(e,t,r,n){return typeof r=="function"&&(n=r,r=void 0),a$(e,[],e_(e,t,r)[Symbol.asyncIterator](),n)}function a$(e,t,r,n){return r.next().then(s=>{if(s.done)return t;let o=!1;function i(){o=!0}return t=t.concat(n?n(s.value,i):s.value.data),o?t:a$(e,t,r,n)})}function t_(e){return{paginate:Object.assign(i$.bind(null,e),{iterator:e_.bind(null,e)})}}var y1,mY,c$=A(()=>{y1="0.0.0-development";mY=Object.assign(i$,{iterator:e_});t_.VERSION=y1});var r_,u$=A(()=>{r_="17.0.0"});var w1,l$,d$=A(()=>{w1={actions:{addCustomLabelsToSelfHostedRunnerForOrg:["POST /orgs/{org}/actions/runners/{runner_id}/labels"],addCustomLabelsToSelfHostedRunnerForRepo:["POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],addRepoAccessToSelfHostedRunnerGroupInOrg:["PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],approveWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"],cancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],createEnvironmentVariable:["POST /repos/{owner}/{repo}/environments/{environment_name}/variables"],createHostedRunnerForOrg:["POST /orgs/{org}/actions/hosted-runners"],createOrUpdateEnvironmentSecret:["PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],createOrgVariable:["POST /orgs/{org}/actions/variables"],createRegistrationTokenForOrg:["POST /orgs/{org}/actions/runners/registration-token"],createRegistrationTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/registration-token"],createRemoveTokenForOrg:["POST /orgs/{org}/actions/runners/remove-token"],createRemoveTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/remove-token"],createRepoVariable:["POST /repos/{owner}/{repo}/actions/variables"],createWorkflowDispatch:["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],deleteActionsCacheById:["DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}"],deleteActionsCacheByKey:["DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}"],deleteArtifact:["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],deleteCustomImageFromOrg:["DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}"],deleteCustomImageVersionFromOrg:["DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}"],deleteEnvironmentSecret:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],deleteEnvironmentVariable:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],deleteHostedRunnerForOrg:["DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],deleteOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}"],deleteOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],deleteRepoVariable:["DELETE /repos/{owner}/{repo}/actions/variables/{name}"],deleteSelfHostedRunnerFromOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}"],deleteSelfHostedRunnerFromRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"],deleteWorkflowRun:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],deleteWorkflowRunLogs:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],disableSelectedRepositoryGithubActionsOrganization:["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"],disableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"],downloadArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"],downloadJobLogsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"],downloadWorkflowRunAttemptLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"],downloadWorkflowRunLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],enableSelectedRepositoryGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"],enableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"],forceCancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel"],generateRunnerJitconfigForOrg:["POST /orgs/{org}/actions/runners/generate-jitconfig"],generateRunnerJitconfigForRepo:["POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig"],getActionsCacheList:["GET /repos/{owner}/{repo}/actions/caches"],getActionsCacheUsage:["GET /repos/{owner}/{repo}/actions/cache/usage"],getActionsCacheUsageByRepoForOrg:["GET /orgs/{org}/actions/cache/usage-by-repository"],getActionsCacheUsageForOrg:["GET /orgs/{org}/actions/cache/usage"],getAllowedActionsOrganization:["GET /orgs/{org}/actions/permissions/selected-actions"],getAllowedActionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"],getArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],getCustomImageForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}"],getCustomImageVersionForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}"],getCustomOidcSubClaimForRepo:["GET /repos/{owner}/{repo}/actions/oidc/customization/sub"],getEnvironmentPublicKey:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key"],getEnvironmentSecret:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],getEnvironmentVariable:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],getGithubActionsDefaultWorkflowPermissionsOrganization:["GET /orgs/{org}/actions/permissions/workflow"],getGithubActionsDefaultWorkflowPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/workflow"],getGithubActionsPermissionsOrganization:["GET /orgs/{org}/actions/permissions"],getGithubActionsPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions"],getHostedRunnerForOrg:["GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],getHostedRunnersGithubOwnedImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/github-owned"],getHostedRunnersLimitsForOrg:["GET /orgs/{org}/actions/hosted-runners/limits"],getHostedRunnersMachineSpecsForOrg:["GET /orgs/{org}/actions/hosted-runners/machine-sizes"],getHostedRunnersPartnerImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/partner"],getHostedRunnersPlatformsForOrg:["GET /orgs/{org}/actions/hosted-runners/platforms"],getJobForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],getOrgPublicKey:["GET /orgs/{org}/actions/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}"],getOrgVariable:["GET /orgs/{org}/actions/variables/{name}"],getPendingDeploymentsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],getRepoPermissions:["GET /repos/{owner}/{repo}/actions/permissions",{},{renamed:["actions","getGithubActionsPermissionsRepository"]}],getRepoPublicKey:["GET /repos/{owner}/{repo}/actions/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],getRepoVariable:["GET /repos/{owner}/{repo}/actions/variables/{name}"],getReviewsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"],getSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}"],getSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],getWorkflow:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],getWorkflowAccessToRepository:["GET /repos/{owner}/{repo}/actions/permissions/access"],getWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],getWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"],getWorkflowRunUsage:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],getWorkflowUsage:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],listArtifactsForRepo:["GET /repos/{owner}/{repo}/actions/artifacts"],listCustomImageVersionsForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions"],listCustomImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom"],listEnvironmentSecrets:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets"],listEnvironmentVariables:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables"],listGithubHostedRunnersInGroupForOrg:["GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners"],listHostedRunnersForOrg:["GET /orgs/{org}/actions/hosted-runners"],listJobsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],listJobsForWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"],listLabelsForSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}/labels"],listLabelsForSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],listOrgSecrets:["GET /orgs/{org}/actions/secrets"],listOrgVariables:["GET /orgs/{org}/actions/variables"],listRepoOrganizationSecrets:["GET /repos/{owner}/{repo}/actions/organization-secrets"],listRepoOrganizationVariables:["GET /repos/{owner}/{repo}/actions/organization-variables"],listRepoSecrets:["GET /repos/{owner}/{repo}/actions/secrets"],listRepoVariables:["GET /repos/{owner}/{repo}/actions/variables"],listRepoWorkflows:["GET /repos/{owner}/{repo}/actions/workflows"],listRunnerApplicationsForOrg:["GET /orgs/{org}/actions/runners/downloads"],listRunnerApplicationsForRepo:["GET /repos/{owner}/{repo}/actions/runners/downloads"],listSelectedReposForOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"],listSelectedReposForOrgVariable:["GET /orgs/{org}/actions/variables/{name}/repositories"],listSelectedRepositoriesEnabledGithubActionsOrganization:["GET /orgs/{org}/actions/permissions/repositories"],listSelfHostedRunnersForOrg:["GET /orgs/{org}/actions/runners"],listSelfHostedRunnersForRepo:["GET /repos/{owner}/{repo}/actions/runners"],listWorkflowRunArtifacts:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"],listWorkflowRuns:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"],listWorkflowRunsForRepo:["GET /repos/{owner}/{repo}/actions/runs"],reRunJobForWorkflowRun:["POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun"],reRunWorkflow:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],reRunWorkflowFailedJobs:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs"],removeAllCustomLabelsFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels"],removeAllCustomLabelsFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],removeCustomLabelFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}"],removeCustomLabelFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],reviewCustomGatesForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule"],reviewPendingDeploymentsForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],setAllowedActionsOrganization:["PUT /orgs/{org}/actions/permissions/selected-actions"],setAllowedActionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"],setCustomLabelsForSelfHostedRunnerForOrg:["PUT /orgs/{org}/actions/runners/{runner_id}/labels"],setCustomLabelsForSelfHostedRunnerForRepo:["PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],setCustomOidcSubClaimForRepo:["PUT /repos/{owner}/{repo}/actions/oidc/customization/sub"],setGithubActionsDefaultWorkflowPermissionsOrganization:["PUT /orgs/{org}/actions/permissions/workflow"],setGithubActionsDefaultWorkflowPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/workflow"],setGithubActionsPermissionsOrganization:["PUT /orgs/{org}/actions/permissions"],setGithubActionsPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"],setSelectedReposForOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories"],setSelectedRepositoriesEnabledGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories"],setWorkflowAccessToRepository:["PUT /repos/{owner}/{repo}/actions/permissions/access"],updateEnvironmentVariable:["PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],updateHostedRunnerForOrg:["PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],updateOrgVariable:["PATCH /orgs/{org}/actions/variables/{name}"],updateRepoVariable:["PATCH /repos/{owner}/{repo}/actions/variables/{name}"]},activity:{checkRepoIsStarredByAuthenticatedUser:["GET /user/starred/{owner}/{repo}"],deleteRepoSubscription:["DELETE /repos/{owner}/{repo}/subscription"],deleteThreadSubscription:["DELETE /notifications/threads/{thread_id}/subscription"],getFeeds:["GET /feeds"],getRepoSubscription:["GET /repos/{owner}/{repo}/subscription"],getThread:["GET /notifications/threads/{thread_id}"],getThreadSubscriptionForAuthenticatedUser:["GET /notifications/threads/{thread_id}/subscription"],listEventsForAuthenticatedUser:["GET /users/{username}/events"],listNotificationsForAuthenticatedUser:["GET /notifications"],listOrgEventsForAuthenticatedUser:["GET /users/{username}/events/orgs/{org}"],listPublicEvents:["GET /events"],listPublicEventsForRepoNetwork:["GET /networks/{owner}/{repo}/events"],listPublicEventsForUser:["GET /users/{username}/events/public"],listPublicOrgEvents:["GET /orgs/{org}/events"],listReceivedEventsForUser:["GET /users/{username}/received_events"],listReceivedPublicEventsForUser:["GET /users/{username}/received_events/public"],listRepoEvents:["GET /repos/{owner}/{repo}/events"],listRepoNotificationsForAuthenticatedUser:["GET /repos/{owner}/{repo}/notifications"],listReposStarredByAuthenticatedUser:["GET /user/starred"],listReposStarredByUser:["GET /users/{username}/starred"],listReposWatchedByUser:["GET /users/{username}/subscriptions"],listStargazersForRepo:["GET /repos/{owner}/{repo}/stargazers"],listWatchedReposForAuthenticatedUser:["GET /user/subscriptions"],listWatchersForRepo:["GET /repos/{owner}/{repo}/subscribers"],markNotificationsAsRead:["PUT /notifications"],markRepoNotificationsAsRead:["PUT /repos/{owner}/{repo}/notifications"],markThreadAsDone:["DELETE /notifications/threads/{thread_id}"],markThreadAsRead:["PATCH /notifications/threads/{thread_id}"],setRepoSubscription:["PUT /repos/{owner}/{repo}/subscription"],setThreadSubscription:["PUT /notifications/threads/{thread_id}/subscription"],starRepoForAuthenticatedUser:["PUT /user/starred/{owner}/{repo}"],unstarRepoForAuthenticatedUser:["DELETE /user/starred/{owner}/{repo}"]},apps:{addRepoToInstallation:["PUT /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","addRepoToInstallationForAuthenticatedUser"]}],addRepoToInstallationForAuthenticatedUser:["PUT /user/installations/{installation_id}/repositories/{repository_id}"],checkToken:["POST /applications/{client_id}/token"],createFromManifest:["POST /app-manifests/{code}/conversions"],createInstallationAccessToken:["POST /app/installations/{installation_id}/access_tokens"],deleteAuthorization:["DELETE /applications/{client_id}/grant"],deleteInstallation:["DELETE /app/installations/{installation_id}"],deleteToken:["DELETE /applications/{client_id}/token"],getAuthenticated:["GET /app"],getBySlug:["GET /apps/{app_slug}"],getInstallation:["GET /app/installations/{installation_id}"],getOrgInstallation:["GET /orgs/{org}/installation"],getRepoInstallation:["GET /repos/{owner}/{repo}/installation"],getSubscriptionPlanForAccount:["GET /marketplace_listing/accounts/{account_id}"],getSubscriptionPlanForAccountStubbed:["GET /marketplace_listing/stubbed/accounts/{account_id}"],getUserInstallation:["GET /users/{username}/installation"],getWebhookConfigForApp:["GET /app/hook/config"],getWebhookDelivery:["GET /app/hook/deliveries/{delivery_id}"],listAccountsForPlan:["GET /marketplace_listing/plans/{plan_id}/accounts"],listAccountsForPlanStubbed:["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"],listInstallationReposForAuthenticatedUser:["GET /user/installations/{installation_id}/repositories"],listInstallationRequestsForAuthenticatedApp:["GET /app/installation-requests"],listInstallations:["GET /app/installations"],listInstallationsForAuthenticatedUser:["GET /user/installations"],listPlans:["GET /marketplace_listing/plans"],listPlansStubbed:["GET /marketplace_listing/stubbed/plans"],listReposAccessibleToInstallation:["GET /installation/repositories"],listSubscriptionsForAuthenticatedUser:["GET /user/marketplace_purchases"],listSubscriptionsForAuthenticatedUserStubbed:["GET /user/marketplace_purchases/stubbed"],listWebhookDeliveries:["GET /app/hook/deliveries"],redeliverWebhookDelivery:["POST /app/hook/deliveries/{delivery_id}/attempts"],removeRepoFromInstallation:["DELETE /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","removeRepoFromInstallationForAuthenticatedUser"]}],removeRepoFromInstallationForAuthenticatedUser:["DELETE /user/installations/{installation_id}/repositories/{repository_id}"],resetToken:["PATCH /applications/{client_id}/token"],revokeInstallationAccessToken:["DELETE /installation/token"],scopeToken:["POST /applications/{client_id}/token/scoped"],suspendInstallation:["PUT /app/installations/{installation_id}/suspended"],unsuspendInstallation:["DELETE /app/installations/{installation_id}/suspended"],updateWebhookConfigForApp:["PATCH /app/hook/config"]},billing:{getGithubActionsBillingOrg:["GET /orgs/{org}/settings/billing/actions"],getGithubActionsBillingUser:["GET /users/{username}/settings/billing/actions"],getGithubBillingPremiumRequestUsageReportOrg:["GET /organizations/{org}/settings/billing/premium_request/usage"],getGithubBillingPremiumRequestUsageReportUser:["GET /users/{username}/settings/billing/premium_request/usage"],getGithubBillingUsageReportOrg:["GET /organizations/{org}/settings/billing/usage"],getGithubBillingUsageReportUser:["GET /users/{username}/settings/billing/usage"],getGithubPackagesBillingOrg:["GET /orgs/{org}/settings/billing/packages"],getGithubPackagesBillingUser:["GET /users/{username}/settings/billing/packages"],getSharedStorageBillingOrg:["GET /orgs/{org}/settings/billing/shared-storage"],getSharedStorageBillingUser:["GET /users/{username}/settings/billing/shared-storage"]},campaigns:{createCampaign:["POST /orgs/{org}/campaigns"],deleteCampaign:["DELETE /orgs/{org}/campaigns/{campaign_number}"],getCampaignSummary:["GET /orgs/{org}/campaigns/{campaign_number}"],listOrgCampaigns:["GET /orgs/{org}/campaigns"],updateCampaign:["PATCH /orgs/{org}/campaigns/{campaign_number}"]},checks:{create:["POST /repos/{owner}/{repo}/check-runs"],createSuite:["POST /repos/{owner}/{repo}/check-suites"],get:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],getSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],listAnnotations:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"],listForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],listForSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"],listSuitesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],rerequestRun:["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"],rerequestSuite:["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"],setSuitesPreferences:["PATCH /repos/{owner}/{repo}/check-suites/preferences"],update:["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]},codeScanning:{commitAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits"],createAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],createVariantAnalysis:["POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses"],deleteAnalysis:["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"],deleteCodeqlDatabase:["DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getAlert:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}",{},{renamedParameters:{alert_id:"alert_number"}}],getAnalysis:["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"],getAutofix:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],getCodeqlDatabase:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getDefaultSetup:["GET /repos/{owner}/{repo}/code-scanning/default-setup"],getSarif:["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],getVariantAnalysis:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}"],getVariantAnalysisRepoTask:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}"],listAlertInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"],listAlertsForOrg:["GET /orgs/{org}/code-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/code-scanning/alerts"],listAlertsInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",{},{renamed:["codeScanning","listAlertInstances"]}],listCodeqlDatabases:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases"],listRecentAnalyses:["GET /repos/{owner}/{repo}/code-scanning/analyses"],updateAlert:["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"],updateDefaultSetup:["PATCH /repos/{owner}/{repo}/code-scanning/default-setup"],uploadSarif:["POST /repos/{owner}/{repo}/code-scanning/sarifs"]},codeSecurity:{attachConfiguration:["POST /orgs/{org}/code-security/configurations/{configuration_id}/attach"],attachEnterpriseConfiguration:["POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach"],createConfiguration:["POST /orgs/{org}/code-security/configurations"],createConfigurationForEnterprise:["POST /enterprises/{enterprise}/code-security/configurations"],deleteConfiguration:["DELETE /orgs/{org}/code-security/configurations/{configuration_id}"],deleteConfigurationForEnterprise:["DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],detachConfiguration:["DELETE /orgs/{org}/code-security/configurations/detach"],getConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}"],getConfigurationForRepository:["GET /repos/{owner}/{repo}/code-security-configuration"],getConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations"],getConfigurationsForOrg:["GET /orgs/{org}/code-security/configurations"],getDefaultConfigurations:["GET /orgs/{org}/code-security/configurations/defaults"],getDefaultConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/defaults"],getRepositoriesForConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories"],getRepositoriesForEnterpriseConfiguration:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories"],getSingleConfigurationForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],setConfigurationAsDefault:["PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults"],setConfigurationAsDefaultForEnterprise:["PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults"],updateConfiguration:["PATCH /orgs/{org}/code-security/configurations/{configuration_id}"],updateEnterpriseConfiguration:["PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}"]},codesOfConduct:{getAllCodesOfConduct:["GET /codes_of_conduct"],getConductCode:["GET /codes_of_conduct/{key}"]},codespaces:{addRepositoryForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],checkPermissionsForDevcontainer:["GET /repos/{owner}/{repo}/codespaces/permissions_check"],codespaceMachinesForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/machines"],createForAuthenticatedUser:["POST /user/codespaces"],createOrUpdateOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],createOrUpdateSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}"],createWithPrForAuthenticatedUser:["POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces"],createWithRepoForAuthenticatedUser:["POST /repos/{owner}/{repo}/codespaces"],deleteForAuthenticatedUser:["DELETE /user/codespaces/{codespace_name}"],deleteFromOrganization:["DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}"],deleteOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],deleteSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}"],exportForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/exports"],getCodespacesForUserInOrg:["GET /orgs/{org}/members/{username}/codespaces"],getExportDetailsForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/exports/{export_id}"],getForAuthenticatedUser:["GET /user/codespaces/{codespace_name}"],getOrgPublicKey:["GET /orgs/{org}/codespaces/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}"],getPublicKeyForAuthenticatedUser:["GET /user/codespaces/secrets/public-key"],getRepoPublicKey:["GET /repos/{owner}/{repo}/codespaces/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],getSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}"],listDevcontainersInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/devcontainers"],listForAuthenticatedUser:["GET /user/codespaces"],listInOrganization:["GET /orgs/{org}/codespaces",{},{renamedParameters:{org_id:"org"}}],listInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces"],listOrgSecrets:["GET /orgs/{org}/codespaces/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/codespaces/secrets"],listRepositoriesForSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}/repositories"],listSecretsForAuthenticatedUser:["GET /user/codespaces/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],preFlightWithRepoForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/new"],publishForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/publish"],removeRepositoryForSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],repoMachinesForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/machines"],setRepositoriesForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],startForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/start"],stopForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/stop"],stopInOrganization:["POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop"],updateForAuthenticatedUser:["PATCH /user/codespaces/{codespace_name}"]},copilot:{addCopilotSeatsForTeams:["POST /orgs/{org}/copilot/billing/selected_teams"],addCopilotSeatsForUsers:["POST /orgs/{org}/copilot/billing/selected_users"],cancelCopilotSeatAssignmentForTeams:["DELETE /orgs/{org}/copilot/billing/selected_teams"],cancelCopilotSeatAssignmentForUsers:["DELETE /orgs/{org}/copilot/billing/selected_users"],copilotMetricsForOrganization:["GET /orgs/{org}/copilot/metrics"],copilotMetricsForTeam:["GET /orgs/{org}/team/{team_slug}/copilot/metrics"],getCopilotOrganizationDetails:["GET /orgs/{org}/copilot/billing"],getCopilotSeatDetailsForUser:["GET /orgs/{org}/members/{username}/copilot"],listCopilotSeats:["GET /orgs/{org}/copilot/billing/seats"]},credentials:{revoke:["POST /credentials/revoke"]},dependabot:{addSelectedRepoToOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],deleteOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],getAlert:["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],getOrgPublicKey:["GET /orgs/{org}/dependabot/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}"],getRepoPublicKey:["GET /repos/{owner}/{repo}/dependabot/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],listAlertsForEnterprise:["GET /enterprises/{enterprise}/dependabot/alerts"],listAlertsForOrg:["GET /orgs/{org}/dependabot/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/dependabot/alerts"],listOrgSecrets:["GET /orgs/{org}/dependabot/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/dependabot/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],repositoryAccessForOrg:["GET /organizations/{org}/dependabot/repository-access"],setRepositoryAccessDefaultLevel:["PUT /organizations/{org}/dependabot/repository-access/default-level"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],updateAlert:["PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],updateRepositoryAccessForOrg:["PATCH /organizations/{org}/dependabot/repository-access"]},dependencyGraph:{createRepositorySnapshot:["POST /repos/{owner}/{repo}/dependency-graph/snapshots"],diffRange:["GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}"],exportSbom:["GET /repos/{owner}/{repo}/dependency-graph/sbom"]},emojis:{get:["GET /emojis"]},enterpriseTeamMemberships:{add:["PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"],bulkAdd:["POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add"],bulkRemove:["POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove"],get:["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"],list:["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships"],remove:["DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"]},enterpriseTeamOrganizations:{add:["PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],bulkAdd:["POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add"],bulkRemove:["POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove"],delete:["DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],getAssignment:["GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],getAssignments:["GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations"]},enterpriseTeams:{create:["POST /enterprises/{enterprise}/teams"],delete:["DELETE /enterprises/{enterprise}/teams/{team_slug}"],get:["GET /enterprises/{enterprise}/teams/{team_slug}"],list:["GET /enterprises/{enterprise}/teams"],update:["PATCH /enterprises/{enterprise}/teams/{team_slug}"]},gists:{checkIsStarred:["GET /gists/{gist_id}/star"],create:["POST /gists"],createComment:["POST /gists/{gist_id}/comments"],delete:["DELETE /gists/{gist_id}"],deleteComment:["DELETE /gists/{gist_id}/comments/{comment_id}"],fork:["POST /gists/{gist_id}/forks"],get:["GET /gists/{gist_id}"],getComment:["GET /gists/{gist_id}/comments/{comment_id}"],getRevision:["GET /gists/{gist_id}/{sha}"],list:["GET /gists"],listComments:["GET /gists/{gist_id}/comments"],listCommits:["GET /gists/{gist_id}/commits"],listForUser:["GET /users/{username}/gists"],listForks:["GET /gists/{gist_id}/forks"],listPublic:["GET /gists/public"],listStarred:["GET /gists/starred"],star:["PUT /gists/{gist_id}/star"],unstar:["DELETE /gists/{gist_id}/star"],update:["PATCH /gists/{gist_id}"],updateComment:["PATCH /gists/{gist_id}/comments/{comment_id}"]},git:{createBlob:["POST /repos/{owner}/{repo}/git/blobs"],createCommit:["POST /repos/{owner}/{repo}/git/commits"],createRef:["POST /repos/{owner}/{repo}/git/refs"],createTag:["POST /repos/{owner}/{repo}/git/tags"],createTree:["POST /repos/{owner}/{repo}/git/trees"],deleteRef:["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],getBlob:["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],getCommit:["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],getRef:["GET /repos/{owner}/{repo}/git/ref/{ref}"],getTag:["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],getTree:["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],listMatchingRefs:["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],updateRef:["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]},gitignore:{getAllTemplates:["GET /gitignore/templates"],getTemplate:["GET /gitignore/templates/{name}"]},hostedCompute:{createNetworkConfigurationForOrg:["POST /orgs/{org}/settings/network-configurations"],deleteNetworkConfigurationFromOrg:["DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}"],getNetworkConfigurationForOrg:["GET /orgs/{org}/settings/network-configurations/{network_configuration_id}"],getNetworkSettingsForOrg:["GET /orgs/{org}/settings/network-settings/{network_settings_id}"],listNetworkConfigurationsForOrg:["GET /orgs/{org}/settings/network-configurations"],updateNetworkConfigurationForOrg:["PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}"]},interactions:{getRestrictionsForAuthenticatedUser:["GET /user/interaction-limits"],getRestrictionsForOrg:["GET /orgs/{org}/interaction-limits"],getRestrictionsForRepo:["GET /repos/{owner}/{repo}/interaction-limits"],getRestrictionsForYourPublicRepos:["GET /user/interaction-limits",{},{renamed:["interactions","getRestrictionsForAuthenticatedUser"]}],removeRestrictionsForAuthenticatedUser:["DELETE /user/interaction-limits"],removeRestrictionsForOrg:["DELETE /orgs/{org}/interaction-limits"],removeRestrictionsForRepo:["DELETE /repos/{owner}/{repo}/interaction-limits"],removeRestrictionsForYourPublicRepos:["DELETE /user/interaction-limits",{},{renamed:["interactions","removeRestrictionsForAuthenticatedUser"]}],setRestrictionsForAuthenticatedUser:["PUT /user/interaction-limits"],setRestrictionsForOrg:["PUT /orgs/{org}/interaction-limits"],setRestrictionsForRepo:["PUT /repos/{owner}/{repo}/interaction-limits"],setRestrictionsForYourPublicRepos:["PUT /user/interaction-limits",{},{renamed:["interactions","setRestrictionsForAuthenticatedUser"]}]},issues:{addAssignees:["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],addBlockedByDependency:["POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by"],addLabels:["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],addSubIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],checkUserCanBeAssigned:["GET /repos/{owner}/{repo}/assignees/{assignee}"],checkUserCanBeAssignedToIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}"],create:["POST /repos/{owner}/{repo}/issues"],createComment:["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"],createLabel:["POST /repos/{owner}/{repo}/labels"],createMilestone:["POST /repos/{owner}/{repo}/milestones"],deleteComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"],deleteLabel:["DELETE /repos/{owner}/{repo}/labels/{name}"],deleteMilestone:["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"],get:["GET /repos/{owner}/{repo}/issues/{issue_number}"],getComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],getEvent:["GET /repos/{owner}/{repo}/issues/events/{event_id}"],getLabel:["GET /repos/{owner}/{repo}/labels/{name}"],getMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],getParent:["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"],list:["GET /issues"],listAssignees:["GET /repos/{owner}/{repo}/assignees"],listComments:["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],listCommentsForRepo:["GET /repos/{owner}/{repo}/issues/comments"],listDependenciesBlockedBy:["GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by"],listDependenciesBlocking:["GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking"],listEvents:["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],listEventsForRepo:["GET /repos/{owner}/{repo}/issues/events"],listEventsForTimeline:["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"],listForAuthenticatedUser:["GET /user/issues"],listForOrg:["GET /orgs/{org}/issues"],listForRepo:["GET /repos/{owner}/{repo}/issues"],listLabelsForMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"],listLabelsForRepo:["GET /repos/{owner}/{repo}/labels"],listLabelsOnIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"],listMilestones:["GET /repos/{owner}/{repo}/milestones"],listSubIssues:["GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],lock:["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],removeAllLabels:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"],removeAssignees:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"],removeDependencyBlockedBy:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}"],removeLabel:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"],removeSubIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue"],reprioritizeSubIssue:["PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority"],setLabels:["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],unlock:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],update:["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],updateComment:["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],updateLabel:["PATCH /repos/{owner}/{repo}/labels/{name}"],updateMilestone:["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"]},licenses:{get:["GET /licenses/{license}"],getAllCommonlyUsed:["GET /licenses"],getForRepo:["GET /repos/{owner}/{repo}/license"]},markdown:{render:["POST /markdown"],renderRaw:["POST /markdown/raw",{headers:{"content-type":"text/plain; charset=utf-8"}}]},meta:{get:["GET /meta"],getAllVersions:["GET /versions"],getOctocat:["GET /octocat"],getZen:["GET /zen"],root:["GET /"]},migrations:{deleteArchiveForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/archive"],deleteArchiveForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/archive"],downloadArchiveForOrg:["GET /orgs/{org}/migrations/{migration_id}/archive"],getArchiveForAuthenticatedUser:["GET /user/migrations/{migration_id}/archive"],getStatusForAuthenticatedUser:["GET /user/migrations/{migration_id}"],getStatusForOrg:["GET /orgs/{org}/migrations/{migration_id}"],listForAuthenticatedUser:["GET /user/migrations"],listForOrg:["GET /orgs/{org}/migrations"],listReposForAuthenticatedUser:["GET /user/migrations/{migration_id}/repositories"],listReposForOrg:["GET /orgs/{org}/migrations/{migration_id}/repositories"],listReposForUser:["GET /user/migrations/{migration_id}/repositories",{},{renamed:["migrations","listReposForAuthenticatedUser"]}],startForAuthenticatedUser:["POST /user/migrations"],startForOrg:["POST /orgs/{org}/migrations"],unlockRepoForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"],unlockRepoForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"]},oidc:{getOidcCustomSubTemplateForOrg:["GET /orgs/{org}/actions/oidc/customization/sub"],updateOidcCustomSubTemplateForOrg:["PUT /orgs/{org}/actions/oidc/customization/sub"]},orgs:{addSecurityManagerTeam:["PUT /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team"}],assignTeamToOrgRole:["PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],assignUserToOrgRole:["PUT /orgs/{org}/organization-roles/users/{username}/{role_id}"],blockUser:["PUT /orgs/{org}/blocks/{username}"],cancelInvitation:["DELETE /orgs/{org}/invitations/{invitation_id}"],checkBlockedUser:["GET /orgs/{org}/blocks/{username}"],checkMembershipForUser:["GET /orgs/{org}/members/{username}"],checkPublicMembershipForUser:["GET /orgs/{org}/public_members/{username}"],convertMemberToOutsideCollaborator:["PUT /orgs/{org}/outside_collaborators/{username}"],createArtifactStorageRecord:["POST /orgs/{org}/artifacts/metadata/storage-record"],createInvitation:["POST /orgs/{org}/invitations"],createIssueType:["POST /orgs/{org}/issue-types"],createWebhook:["POST /orgs/{org}/hooks"],customPropertiesForOrgsCreateOrUpdateOrganizationValues:["PATCH /organizations/{org}/org-properties/values"],customPropertiesForOrgsGetOrganizationValues:["GET /organizations/{org}/org-properties/values"],customPropertiesForReposCreateOrUpdateOrganizationDefinition:["PUT /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposCreateOrUpdateOrganizationDefinitions:["PATCH /orgs/{org}/properties/schema"],customPropertiesForReposCreateOrUpdateOrganizationValues:["PATCH /orgs/{org}/properties/values"],customPropertiesForReposDeleteOrganizationDefinition:["DELETE /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposGetOrganizationDefinition:["GET /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposGetOrganizationDefinitions:["GET /orgs/{org}/properties/schema"],customPropertiesForReposGetOrganizationValues:["GET /orgs/{org}/properties/values"],delete:["DELETE /orgs/{org}"],deleteAttestationsBulk:["POST /orgs/{org}/attestations/delete-request"],deleteAttestationsById:["DELETE /orgs/{org}/attestations/{attestation_id}"],deleteAttestationsBySubjectDigest:["DELETE /orgs/{org}/attestations/digest/{subject_digest}"],deleteIssueType:["DELETE /orgs/{org}/issue-types/{issue_type_id}"],deleteWebhook:["DELETE /orgs/{org}/hooks/{hook_id}"],disableSelectedRepositoryImmutableReleasesOrganization:["DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}"],enableSelectedRepositoryImmutableReleasesOrganization:["PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}"],get:["GET /orgs/{org}"],getImmutableReleasesSettings:["GET /orgs/{org}/settings/immutable-releases"],getImmutableReleasesSettingsRepositories:["GET /orgs/{org}/settings/immutable-releases/repositories"],getMembershipForAuthenticatedUser:["GET /user/memberships/orgs/{org}"],getMembershipForUser:["GET /orgs/{org}/memberships/{username}"],getOrgRole:["GET /orgs/{org}/organization-roles/{role_id}"],getOrgRulesetHistory:["GET /orgs/{org}/rulesets/{ruleset_id}/history"],getOrgRulesetVersion:["GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}"],getWebhook:["GET /orgs/{org}/hooks/{hook_id}"],getWebhookConfigForOrg:["GET /orgs/{org}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"],list:["GET /organizations"],listAppInstallations:["GET /orgs/{org}/installations"],listArtifactStorageRecords:["GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records"],listAttestationRepositories:["GET /orgs/{org}/attestations/repositories"],listAttestations:["GET /orgs/{org}/attestations/{subject_digest}"],listAttestationsBulk:["POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}"],listBlockedUsers:["GET /orgs/{org}/blocks"],listFailedInvitations:["GET /orgs/{org}/failed_invitations"],listForAuthenticatedUser:["GET /user/orgs"],listForUser:["GET /users/{username}/orgs"],listInvitationTeams:["GET /orgs/{org}/invitations/{invitation_id}/teams"],listIssueTypes:["GET /orgs/{org}/issue-types"],listMembers:["GET /orgs/{org}/members"],listMembershipsForAuthenticatedUser:["GET /user/memberships/orgs"],listOrgRoleTeams:["GET /orgs/{org}/organization-roles/{role_id}/teams"],listOrgRoleUsers:["GET /orgs/{org}/organization-roles/{role_id}/users"],listOrgRoles:["GET /orgs/{org}/organization-roles"],listOrganizationFineGrainedPermissions:["GET /orgs/{org}/organization-fine-grained-permissions"],listOutsideCollaborators:["GET /orgs/{org}/outside_collaborators"],listPatGrantRepositories:["GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories"],listPatGrantRequestRepositories:["GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories"],listPatGrantRequests:["GET /orgs/{org}/personal-access-token-requests"],listPatGrants:["GET /orgs/{org}/personal-access-tokens"],listPendingInvitations:["GET /orgs/{org}/invitations"],listPublicMembers:["GET /orgs/{org}/public_members"],listSecurityManagerTeams:["GET /orgs/{org}/security-managers",{},{deprecated:"octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams"}],listWebhookDeliveries:["GET /orgs/{org}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /orgs/{org}/hooks"],pingWebhook:["POST /orgs/{org}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeMember:["DELETE /orgs/{org}/members/{username}"],removeMembershipForUser:["DELETE /orgs/{org}/memberships/{username}"],removeOutsideCollaborator:["DELETE /orgs/{org}/outside_collaborators/{username}"],removePublicMembershipForAuthenticatedUser:["DELETE /orgs/{org}/public_members/{username}"],removeSecurityManagerTeam:["DELETE /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team"}],reviewPatGrantRequest:["POST /orgs/{org}/personal-access-token-requests/{pat_request_id}"],reviewPatGrantRequestsInBulk:["POST /orgs/{org}/personal-access-token-requests"],revokeAllOrgRolesTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}"],revokeAllOrgRolesUser:["DELETE /orgs/{org}/organization-roles/users/{username}"],revokeOrgRoleTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],revokeOrgRoleUser:["DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}"],setImmutableReleasesSettings:["PUT /orgs/{org}/settings/immutable-releases"],setImmutableReleasesSettingsRepositories:["PUT /orgs/{org}/settings/immutable-releases/repositories"],setMembershipForUser:["PUT /orgs/{org}/memberships/{username}"],setPublicMembershipForAuthenticatedUser:["PUT /orgs/{org}/public_members/{username}"],unblockUser:["DELETE /orgs/{org}/blocks/{username}"],update:["PATCH /orgs/{org}"],updateIssueType:["PUT /orgs/{org}/issue-types/{issue_type_id}"],updateMembershipForAuthenticatedUser:["PATCH /user/memberships/orgs/{org}"],updatePatAccess:["POST /orgs/{org}/personal-access-tokens/{pat_id}"],updatePatAccesses:["POST /orgs/{org}/personal-access-tokens"],updateWebhook:["PATCH /orgs/{org}/hooks/{hook_id}"],updateWebhookConfigForOrg:["PATCH /orgs/{org}/hooks/{hook_id}/config"]},packages:{deletePackageForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}"],deletePackageForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}"],deletePackageForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}"],deletePackageVersionForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getAllPackageVersionsForAPackageOwnedByAnOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByOrg"]}],getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByAuthenticatedUser"]}],getAllPackageVersionsForPackageOwnedByAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions"],getPackageForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}"],getPackageForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}"],getPackageForUser:["GET /users/{username}/packages/{package_type}/{package_name}"],getPackageVersionForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],listDockerMigrationConflictingPackagesForAuthenticatedUser:["GET /user/docker/conflicts"],listDockerMigrationConflictingPackagesForOrganization:["GET /orgs/{org}/docker/conflicts"],listDockerMigrationConflictingPackagesForUser:["GET /users/{username}/docker/conflicts"],listPackagesForAuthenticatedUser:["GET /user/packages"],listPackagesForOrganization:["GET /orgs/{org}/packages"],listPackagesForUser:["GET /users/{username}/packages"],restorePackageForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForUser:["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageVersionForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForUser:["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"]},privateRegistries:{createOrgPrivateRegistry:["POST /orgs/{org}/private-registries"],deleteOrgPrivateRegistry:["DELETE /orgs/{org}/private-registries/{secret_name}"],getOrgPrivateRegistry:["GET /orgs/{org}/private-registries/{secret_name}"],getOrgPublicKey:["GET /orgs/{org}/private-registries/public-key"],listOrgPrivateRegistries:["GET /orgs/{org}/private-registries"],updateOrgPrivateRegistry:["PATCH /orgs/{org}/private-registries/{secret_name}"]},projects:{addItemForOrg:["POST /orgs/{org}/projectsV2/{project_number}/items"],addItemForUser:["POST /users/{username}/projectsV2/{project_number}/items"],deleteItemForOrg:["DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],deleteItemForUser:["DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}"],getFieldForOrg:["GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}"],getFieldForUser:["GET /users/{username}/projectsV2/{project_number}/fields/{field_id}"],getForOrg:["GET /orgs/{org}/projectsV2/{project_number}"],getForUser:["GET /users/{username}/projectsV2/{project_number}"],getOrgItem:["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],getUserItem:["GET /users/{username}/projectsV2/{project_number}/items/{item_id}"],listFieldsForOrg:["GET /orgs/{org}/projectsV2/{project_number}/fields"],listFieldsForUser:["GET /users/{username}/projectsV2/{project_number}/fields"],listForOrg:["GET /orgs/{org}/projectsV2"],listForUser:["GET /users/{username}/projectsV2"],listItemsForOrg:["GET /orgs/{org}/projectsV2/{project_number}/items"],listItemsForUser:["GET /users/{username}/projectsV2/{project_number}/items"],updateItemForOrg:["PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],updateItemForUser:["PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}"]},pulls:{checkIfMerged:["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],create:["POST /repos/{owner}/{repo}/pulls"],createReplyForReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"],createReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],createReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"],deletePendingReview:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],deleteReviewComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"],dismissReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"],get:["GET /repos/{owner}/{repo}/pulls/{pull_number}"],getReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],getReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],list:["GET /repos/{owner}/{repo}/pulls"],listCommentsForReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"],listCommits:["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],listFiles:["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],listRequestedReviewers:["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],listReviewComments:["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"],listReviewCommentsForRepo:["GET /repos/{owner}/{repo}/pulls/comments"],listReviews:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],merge:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],removeRequestedReviewers:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],requestReviewers:["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],submitReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"],update:["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],updateBranch:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"],updateReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],updateReviewComment:["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"]},rateLimit:{get:["GET /rate_limit"]},reactions:{createForCommitComment:["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"],createForIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"],createForIssueComment:["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],createForPullRequestReviewComment:["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],createForRelease:["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"],createForTeamDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],createForTeamDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"],deleteForCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"],deleteForIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"],deleteForIssueComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"],deleteForPullRequestComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"],deleteForRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}"],deleteForTeamDiscussion:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"],deleteForTeamDiscussionComment:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"],listForCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"],listForIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"],listForIssueComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],listForPullRequestReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],listForRelease:["GET /repos/{owner}/{repo}/releases/{release_id}/reactions"],listForTeamDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],listForTeamDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]},repos:{acceptInvitation:["PATCH /user/repository_invitations/{invitation_id}",{},{renamed:["repos","acceptInvitationForAuthenticatedUser"]}],acceptInvitationForAuthenticatedUser:["PATCH /user/repository_invitations/{invitation_id}"],addAppAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],addCollaborator:["PUT /repos/{owner}/{repo}/collaborators/{username}"],addStatusCheckContexts:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],addTeamAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],addUserAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],cancelPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel"],checkAutomatedSecurityFixes:["GET /repos/{owner}/{repo}/automated-security-fixes"],checkCollaborator:["GET /repos/{owner}/{repo}/collaborators/{username}"],checkImmutableReleases:["GET /repos/{owner}/{repo}/immutable-releases"],checkPrivateVulnerabilityReporting:["GET /repos/{owner}/{repo}/private-vulnerability-reporting"],checkVulnerabilityAlerts:["GET /repos/{owner}/{repo}/vulnerability-alerts"],codeownersErrors:["GET /repos/{owner}/{repo}/codeowners/errors"],compareCommits:["GET /repos/{owner}/{repo}/compare/{base}...{head}"],compareCommitsWithBasehead:["GET /repos/{owner}/{repo}/compare/{basehead}"],createAttestation:["POST /repos/{owner}/{repo}/attestations"],createAutolink:["POST /repos/{owner}/{repo}/autolinks"],createCommitComment:["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"],createCommitSignatureProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],createCommitStatus:["POST /repos/{owner}/{repo}/statuses/{sha}"],createDeployKey:["POST /repos/{owner}/{repo}/keys"],createDeployment:["POST /repos/{owner}/{repo}/deployments"],createDeploymentBranchPolicy:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],createDeploymentProtectionRule:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],createDeploymentStatus:["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],createDispatchEvent:["POST /repos/{owner}/{repo}/dispatches"],createForAuthenticatedUser:["POST /user/repos"],createFork:["POST /repos/{owner}/{repo}/forks"],createInOrg:["POST /orgs/{org}/repos"],createOrUpdateEnvironment:["PUT /repos/{owner}/{repo}/environments/{environment_name}"],createOrUpdateFileContents:["PUT /repos/{owner}/{repo}/contents/{path}"],createOrgRuleset:["POST /orgs/{org}/rulesets"],createPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments"],createPagesSite:["POST /repos/{owner}/{repo}/pages"],createRelease:["POST /repos/{owner}/{repo}/releases"],createRepoRuleset:["POST /repos/{owner}/{repo}/rulesets"],createUsingTemplate:["POST /repos/{template_owner}/{template_repo}/generate"],createWebhook:["POST /repos/{owner}/{repo}/hooks"],customPropertiesForReposCreateOrUpdateRepositoryValues:["PATCH /repos/{owner}/{repo}/properties/values"],customPropertiesForReposGetRepositoryValues:["GET /repos/{owner}/{repo}/properties/values"],declineInvitation:["DELETE /user/repository_invitations/{invitation_id}",{},{renamed:["repos","declineInvitationForAuthenticatedUser"]}],declineInvitationForAuthenticatedUser:["DELETE /user/repository_invitations/{invitation_id}"],delete:["DELETE /repos/{owner}/{repo}"],deleteAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],deleteAdminBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],deleteAnEnvironment:["DELETE /repos/{owner}/{repo}/environments/{environment_name}"],deleteAutolink:["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],deleteBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],deleteCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],deleteCommitSignatureProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],deleteDeployKey:["DELETE /repos/{owner}/{repo}/keys/{key_id}"],deleteDeployment:["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"],deleteDeploymentBranchPolicy:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],deleteFile:["DELETE /repos/{owner}/{repo}/contents/{path}"],deleteInvitation:["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"],deleteOrgRuleset:["DELETE /orgs/{org}/rulesets/{ruleset_id}"],deletePagesSite:["DELETE /repos/{owner}/{repo}/pages"],deletePullRequestReviewProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],deleteRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}"],deleteReleaseAsset:["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"],deleteRepoRuleset:["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"],deleteWebhook:["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],disableAutomatedSecurityFixes:["DELETE /repos/{owner}/{repo}/automated-security-fixes"],disableDeploymentProtectionRule:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],disableImmutableReleases:["DELETE /repos/{owner}/{repo}/immutable-releases"],disablePrivateVulnerabilityReporting:["DELETE /repos/{owner}/{repo}/private-vulnerability-reporting"],disableVulnerabilityAlerts:["DELETE /repos/{owner}/{repo}/vulnerability-alerts"],downloadArchive:["GET /repos/{owner}/{repo}/zipball/{ref}",{},{renamed:["repos","downloadZipballArchive"]}],downloadTarballArchive:["GET /repos/{owner}/{repo}/tarball/{ref}"],downloadZipballArchive:["GET /repos/{owner}/{repo}/zipball/{ref}"],enableAutomatedSecurityFixes:["PUT /repos/{owner}/{repo}/automated-security-fixes"],enableImmutableReleases:["PUT /repos/{owner}/{repo}/immutable-releases"],enablePrivateVulnerabilityReporting:["PUT /repos/{owner}/{repo}/private-vulnerability-reporting"],enableVulnerabilityAlerts:["PUT /repos/{owner}/{repo}/vulnerability-alerts"],generateReleaseNotes:["POST /repos/{owner}/{repo}/releases/generate-notes"],get:["GET /repos/{owner}/{repo}"],getAccessRestrictions:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],getAdminBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],getAllDeploymentProtectionRules:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],getAllEnvironments:["GET /repos/{owner}/{repo}/environments"],getAllStatusCheckContexts:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],getAllTopics:["GET /repos/{owner}/{repo}/topics"],getAppsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"],getAutolink:["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],getBranch:["GET /repos/{owner}/{repo}/branches/{branch}"],getBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection"],getBranchRules:["GET /repos/{owner}/{repo}/rules/branches/{branch}"],getClones:["GET /repos/{owner}/{repo}/traffic/clones"],getCodeFrequencyStats:["GET /repos/{owner}/{repo}/stats/code_frequency"],getCollaboratorPermissionLevel:["GET /repos/{owner}/{repo}/collaborators/{username}/permission"],getCombinedStatusForRef:["GET /repos/{owner}/{repo}/commits/{ref}/status"],getCommit:["GET /repos/{owner}/{repo}/commits/{ref}"],getCommitActivityStats:["GET /repos/{owner}/{repo}/stats/commit_activity"],getCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}"],getCommitSignatureProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],getCommunityProfileMetrics:["GET /repos/{owner}/{repo}/community/profile"],getContent:["GET /repos/{owner}/{repo}/contents/{path}"],getContributorsStats:["GET /repos/{owner}/{repo}/stats/contributors"],getCustomDeploymentProtectionRule:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],getDeployKey:["GET /repos/{owner}/{repo}/keys/{key_id}"],getDeployment:["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],getDeploymentBranchPolicy:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],getDeploymentStatus:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],getEnvironment:["GET /repos/{owner}/{repo}/environments/{environment_name}"],getLatestPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/latest"],getLatestRelease:["GET /repos/{owner}/{repo}/releases/latest"],getOrgRuleSuite:["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"],getOrgRuleSuites:["GET /orgs/{org}/rulesets/rule-suites"],getOrgRuleset:["GET /orgs/{org}/rulesets/{ruleset_id}"],getOrgRulesets:["GET /orgs/{org}/rulesets"],getPages:["GET /repos/{owner}/{repo}/pages"],getPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],getPagesDeployment:["GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}"],getPagesHealthCheck:["GET /repos/{owner}/{repo}/pages/health"],getParticipationStats:["GET /repos/{owner}/{repo}/stats/participation"],getPullRequestReviewProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],getPunchCardStats:["GET /repos/{owner}/{repo}/stats/punch_card"],getReadme:["GET /repos/{owner}/{repo}/readme"],getReadmeInDirectory:["GET /repos/{owner}/{repo}/readme/{dir}"],getRelease:["GET /repos/{owner}/{repo}/releases/{release_id}"],getReleaseAsset:["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],getReleaseByTag:["GET /repos/{owner}/{repo}/releases/tags/{tag}"],getRepoRuleSuite:["GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}"],getRepoRuleSuites:["GET /repos/{owner}/{repo}/rulesets/rule-suites"],getRepoRuleset:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"],getRepoRulesetHistory:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history"],getRepoRulesetVersion:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}"],getRepoRulesets:["GET /repos/{owner}/{repo}/rulesets"],getStatusChecksProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],getTeamsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"],getTopPaths:["GET /repos/{owner}/{repo}/traffic/popular/paths"],getTopReferrers:["GET /repos/{owner}/{repo}/traffic/popular/referrers"],getUsersWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"],getViews:["GET /repos/{owner}/{repo}/traffic/views"],getWebhook:["GET /repos/{owner}/{repo}/hooks/{hook_id}"],getWebhookConfigForRepo:["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"],listActivities:["GET /repos/{owner}/{repo}/activity"],listAttestations:["GET /repos/{owner}/{repo}/attestations/{subject_digest}"],listAutolinks:["GET /repos/{owner}/{repo}/autolinks"],listBranches:["GET /repos/{owner}/{repo}/branches"],listBranchesForHeadCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"],listCollaborators:["GET /repos/{owner}/{repo}/collaborators"],listCommentsForCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"],listCommitCommentsForRepo:["GET /repos/{owner}/{repo}/comments"],listCommitStatusesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/statuses"],listCommits:["GET /repos/{owner}/{repo}/commits"],listContributors:["GET /repos/{owner}/{repo}/contributors"],listCustomDeploymentRuleIntegrations:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps"],listDeployKeys:["GET /repos/{owner}/{repo}/keys"],listDeploymentBranchPolicies:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],listDeploymentStatuses:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],listDeployments:["GET /repos/{owner}/{repo}/deployments"],listForAuthenticatedUser:["GET /user/repos"],listForOrg:["GET /orgs/{org}/repos"],listForUser:["GET /users/{username}/repos"],listForks:["GET /repos/{owner}/{repo}/forks"],listInvitations:["GET /repos/{owner}/{repo}/invitations"],listInvitationsForAuthenticatedUser:["GET /user/repository_invitations"],listLanguages:["GET /repos/{owner}/{repo}/languages"],listPagesBuilds:["GET /repos/{owner}/{repo}/pages/builds"],listPublic:["GET /repositories"],listPullRequestsAssociatedWithCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"],listReleaseAssets:["GET /repos/{owner}/{repo}/releases/{release_id}/assets"],listReleases:["GET /repos/{owner}/{repo}/releases"],listTags:["GET /repos/{owner}/{repo}/tags"],listTeams:["GET /repos/{owner}/{repo}/teams"],listWebhookDeliveries:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /repos/{owner}/{repo}/hooks"],merge:["POST /repos/{owner}/{repo}/merges"],mergeUpstream:["POST /repos/{owner}/{repo}/merge-upstream"],pingWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeAppAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],removeCollaborator:["DELETE /repos/{owner}/{repo}/collaborators/{username}"],removeStatusCheckContexts:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],removeStatusCheckProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],removeTeamAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],removeUserAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],renameBranch:["POST /repos/{owner}/{repo}/branches/{branch}/rename"],replaceAllTopics:["PUT /repos/{owner}/{repo}/topics"],requestPagesBuild:["POST /repos/{owner}/{repo}/pages/builds"],setAdminBranchProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],setAppAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],setStatusCheckContexts:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],setTeamAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],setUserAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],testPushWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],transfer:["POST /repos/{owner}/{repo}/transfer"],update:["PATCH /repos/{owner}/{repo}"],updateBranchProtection:["PUT /repos/{owner}/{repo}/branches/{branch}/protection"],updateCommitComment:["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],updateDeploymentBranchPolicy:["PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],updateInformationAboutPagesSite:["PUT /repos/{owner}/{repo}/pages"],updateInvitation:["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"],updateOrgRuleset:["PUT /orgs/{org}/rulesets/{ruleset_id}"],updatePullRequestReviewProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],updateRelease:["PATCH /repos/{owner}/{repo}/releases/{release_id}"],updateReleaseAsset:["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"],updateRepoRuleset:["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"],updateStatusCheckPotection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks",{},{renamed:["repos","updateStatusCheckProtection"]}],updateStatusCheckProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],updateWebhook:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],updateWebhookConfigForRepo:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"],uploadReleaseAsset:["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}",{baseUrl:"https://uploads.github.com"}]},search:{code:["GET /search/code"],commits:["GET /search/commits"],issuesAndPullRequests:["GET /search/issues"],labels:["GET /search/labels"],repos:["GET /search/repositories"],topics:["GET /search/topics"],users:["GET /search/users"]},secretScanning:{createPushProtectionBypass:["POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses"],getAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],getScanHistory:["GET /repos/{owner}/{repo}/secret-scanning/scan-history"],listAlertsForOrg:["GET /orgs/{org}/secret-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/secret-scanning/alerts"],listLocationsForAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"],listOrgPatternConfigs:["GET /orgs/{org}/secret-scanning/pattern-configurations"],updateAlert:["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],updateOrgPatternConfigs:["PATCH /orgs/{org}/secret-scanning/pattern-configurations"]},securityAdvisories:{createFork:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks"],createPrivateVulnerabilityReport:["POST /repos/{owner}/{repo}/security-advisories/reports"],createRepositoryAdvisory:["POST /repos/{owner}/{repo}/security-advisories"],createRepositoryAdvisoryCveRequest:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve"],getGlobalAdvisory:["GET /advisories/{ghsa_id}"],getRepositoryAdvisory:["GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}"],listGlobalAdvisories:["GET /advisories"],listOrgRepositoryAdvisories:["GET /orgs/{org}/security-advisories"],listRepositoryAdvisories:["GET /repos/{owner}/{repo}/security-advisories"],updateRepositoryAdvisory:["PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}"]},teams:{addOrUpdateMembershipForUserInOrg:["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"],addOrUpdateRepoPermissionsInOrg:["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],checkPermissionsForRepoInOrg:["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],create:["POST /orgs/{org}/teams"],createDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],createDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions"],deleteDiscussionCommentInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],deleteDiscussionInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],deleteInOrg:["DELETE /orgs/{org}/teams/{team_slug}"],getByName:["GET /orgs/{org}/teams/{team_slug}"],getDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],getDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],getMembershipForUserInOrg:["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"],list:["GET /orgs/{org}/teams"],listChildInOrg:["GET /orgs/{org}/teams/{team_slug}/teams"],listDiscussionCommentsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],listDiscussionsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions"],listForAuthenticatedUser:["GET /user/teams"],listMembersInOrg:["GET /orgs/{org}/teams/{team_slug}/members"],listPendingInvitationsInOrg:["GET /orgs/{org}/teams/{team_slug}/invitations"],listReposInOrg:["GET /orgs/{org}/teams/{team_slug}/repos"],removeMembershipForUserInOrg:["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"],removeRepoInOrg:["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],updateDiscussionCommentInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],updateDiscussionInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],updateInOrg:["PATCH /orgs/{org}/teams/{team_slug}"]},users:{addEmailForAuthenticated:["POST /user/emails",{},{renamed:["users","addEmailForAuthenticatedUser"]}],addEmailForAuthenticatedUser:["POST /user/emails"],addSocialAccountForAuthenticatedUser:["POST /user/social_accounts"],block:["PUT /user/blocks/{username}"],checkBlocked:["GET /user/blocks/{username}"],checkFollowingForUser:["GET /users/{username}/following/{target_user}"],checkPersonIsFollowedByAuthenticated:["GET /user/following/{username}"],createGpgKeyForAuthenticated:["POST /user/gpg_keys",{},{renamed:["users","createGpgKeyForAuthenticatedUser"]}],createGpgKeyForAuthenticatedUser:["POST /user/gpg_keys"],createPublicSshKeyForAuthenticated:["POST /user/keys",{},{renamed:["users","createPublicSshKeyForAuthenticatedUser"]}],createPublicSshKeyForAuthenticatedUser:["POST /user/keys"],createSshSigningKeyForAuthenticatedUser:["POST /user/ssh_signing_keys"],deleteAttestationsBulk:["POST /users/{username}/attestations/delete-request"],deleteAttestationsById:["DELETE /users/{username}/attestations/{attestation_id}"],deleteAttestationsBySubjectDigest:["DELETE /users/{username}/attestations/digest/{subject_digest}"],deleteEmailForAuthenticated:["DELETE /user/emails",{},{renamed:["users","deleteEmailForAuthenticatedUser"]}],deleteEmailForAuthenticatedUser:["DELETE /user/emails"],deleteGpgKeyForAuthenticated:["DELETE /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","deleteGpgKeyForAuthenticatedUser"]}],deleteGpgKeyForAuthenticatedUser:["DELETE /user/gpg_keys/{gpg_key_id}"],deletePublicSshKeyForAuthenticated:["DELETE /user/keys/{key_id}",{},{renamed:["users","deletePublicSshKeyForAuthenticatedUser"]}],deletePublicSshKeyForAuthenticatedUser:["DELETE /user/keys/{key_id}"],deleteSocialAccountForAuthenticatedUser:["DELETE /user/social_accounts"],deleteSshSigningKeyForAuthenticatedUser:["DELETE /user/ssh_signing_keys/{ssh_signing_key_id}"],follow:["PUT /user/following/{username}"],getAuthenticated:["GET /user"],getById:["GET /user/{account_id}"],getByUsername:["GET /users/{username}"],getContextForUser:["GET /users/{username}/hovercard"],getGpgKeyForAuthenticated:["GET /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","getGpgKeyForAuthenticatedUser"]}],getGpgKeyForAuthenticatedUser:["GET /user/gpg_keys/{gpg_key_id}"],getPublicSshKeyForAuthenticated:["GET /user/keys/{key_id}",{},{renamed:["users","getPublicSshKeyForAuthenticatedUser"]}],getPublicSshKeyForAuthenticatedUser:["GET /user/keys/{key_id}"],getSshSigningKeyForAuthenticatedUser:["GET /user/ssh_signing_keys/{ssh_signing_key_id}"],list:["GET /users"],listAttestations:["GET /users/{username}/attestations/{subject_digest}"],listAttestationsBulk:["POST /users/{username}/attestations/bulk-list{?per_page,before,after}"],listBlockedByAuthenticated:["GET /user/blocks",{},{renamed:["users","listBlockedByAuthenticatedUser"]}],listBlockedByAuthenticatedUser:["GET /user/blocks"],listEmailsForAuthenticated:["GET /user/emails",{},{renamed:["users","listEmailsForAuthenticatedUser"]}],listEmailsForAuthenticatedUser:["GET /user/emails"],listFollowedByAuthenticated:["GET /user/following",{},{renamed:["users","listFollowedByAuthenticatedUser"]}],listFollowedByAuthenticatedUser:["GET /user/following"],listFollowersForAuthenticatedUser:["GET /user/followers"],listFollowersForUser:["GET /users/{username}/followers"],listFollowingForUser:["GET /users/{username}/following"],listGpgKeysForAuthenticated:["GET /user/gpg_keys",{},{renamed:["users","listGpgKeysForAuthenticatedUser"]}],listGpgKeysForAuthenticatedUser:["GET /user/gpg_keys"],listGpgKeysForUser:["GET /users/{username}/gpg_keys"],listPublicEmailsForAuthenticated:["GET /user/public_emails",{},{renamed:["users","listPublicEmailsForAuthenticatedUser"]}],listPublicEmailsForAuthenticatedUser:["GET /user/public_emails"],listPublicKeysForUser:["GET /users/{username}/keys"],listPublicSshKeysForAuthenticated:["GET /user/keys",{},{renamed:["users","listPublicSshKeysForAuthenticatedUser"]}],listPublicSshKeysForAuthenticatedUser:["GET /user/keys"],listSocialAccountsForAuthenticatedUser:["GET /user/social_accounts"],listSocialAccountsForUser:["GET /users/{username}/social_accounts"],listSshSigningKeysForAuthenticatedUser:["GET /user/ssh_signing_keys"],listSshSigningKeysForUser:["GET /users/{username}/ssh_signing_keys"],setPrimaryEmailVisibilityForAuthenticated:["PATCH /user/email/visibility",{},{renamed:["users","setPrimaryEmailVisibilityForAuthenticatedUser"]}],setPrimaryEmailVisibilityForAuthenticatedUser:["PATCH /user/email/visibility"],unblock:["DELETE /user/blocks/{username}"],unfollow:["DELETE /user/following/{username}"],updateAuthenticated:["PATCH /user"]}},l$=w1});function n_(e){let t={};for(let r of no.keys())t[r]=new Proxy({octokit:e,scope:r,cache:{}},R1);return t}function S1(e,t,r,n,s){let o=e.request.defaults(n);function i(...a){let c=o.endpoint.merge(...a);if(s.mapToData)return c=Object.assign({},c,{data:c[s.mapToData],[s.mapToData]:void 0}),o(c);if(s.renamed){let[u,d]=s.renamed;e.log.warn(`octokit.${t}.${r}() has been renamed to octokit.${u}.${d}()`)}if(s.deprecated&&e.log.warn(s.deprecated),s.renamedParameters){let u=o.endpoint.merge(...a);for(let[d,p]of Object.entries(s.renamedParameters))d in u&&(e.log.warn(`"${d}" parameter is deprecated for "octokit.${t}.${r}()". Use "${p}" instead`),p in u||(u[p]=u[d]),delete u[d]);return o(u)}return o(...a)}return Object.assign(i,o)}var no,R1,p$=A(()=>{d$();no=new Map;for(let[e,t]of Object.entries(l$))for(let[r,n]of Object.entries(t)){let[s,o,i]=n,[a,c]=s.split(/ /),u=Object.assign({method:a,url:c},o);no.has(e)||no.set(e,new Map),no.get(e).set(r,{scope:e,methodName:r,endpointDefaults:u,decorations:i})}R1={has({scope:e},t){return no.get(e).has(t)},getOwnPropertyDescriptor(e,t){return{value:this.get(e,t),configurable:!0,writable:!0,enumerable:!0}},defineProperty(e,t,r){return Object.defineProperty(e.cache,t,r),!0},deleteProperty(e,t){return delete e.cache[t],!0},ownKeys({scope:e}){return[...no.get(e).keys()]},set(e,t,r){return e.cache[t]=r},get({octokit:e,scope:t,cache:r},n){if(r[n])return r[n];let s=no.get(t).get(n);if(!s)return;let{endpointDefaults:o,decorations:i}=s;return i?r[n]=S1(e,t,n,o,i):r[n]=e.request.defaults(o),r[n]}}});function _1(e){return{rest:n_(e)}}function s_(e){let t=n_(e);return{...t,rest:t}}var m$=A(()=>{u$();p$();_1.VERSION=r_;s_.VERSION=r_});var f$,g$=A(()=>{f$="22.0.1"});var hm,o_=A(()=>{r$();o$();c$();m$();g$();hm=gm.plugin(XS,s_,t_).defaults({userAgent:`octokit-rest.js/${f$}`})});var c_=bC((i_,a_)=>{(function(e,t){typeof i_=="object"&&typeof a_<"u"?a_.exports=t():typeof define=="function"&&define.amd?define(t):e.Bottleneck=t()})(i_,(function(){"use strict";var e=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function t(Q){return Q&&Q.default||Q}var r=function(Q,x,_={}){var D,F,N;for(D in x)N=x[D],_[D]=(F=Q[D])!=null?F:N;return _},n=function(Q,x,_={}){var D,F;for(D in Q)F=Q[D],x[D]!==void 0&&(_[D]=F);return _},s={load:r,overwrite:n},o;o=class{constructor(x,_){this.incr=x,this.decr=_,this._first=null,this._last=null,this.length=0}push(x){var _;this.length++,typeof this.incr=="function"&&this.incr(),_={value:x,prev:this._last,next:null},this._last!=null?(this._last.next=_,this._last=_):this._first=this._last=_}shift(){var x;if(this._first!=null)return this.length--,typeof this.decr=="function"&&this.decr(),x=this._first.value,(this._first=this._first.next)!=null?this._first.prev=null:this._last=null,x}first(){if(this._first!=null)return this._first.value}getArray(){var x,_,D;for(x=this._first,D=[];x!=null;)D.push((_=x,x=x.next,_.value));return D}forEachShift(x){var _;for(_=this.shift();_!=null;)x(_),_=this.shift()}debug(){var x,_,D,F,N;for(x=this._first,N=[];x!=null;)N.push((_=x,x=x.next,{value:_.value,prev:(D=_.prev)!=null?D.value:void 0,next:(F=_.next)!=null?F.value:void 0}));return N}};var i=o,a;a=class{constructor(x){if(this.instance=x,this._events={},this.instance.on!=null||this.instance.once!=null||this.instance.removeAllListeners!=null)throw new Error("An Emitter already exists for this object");this.instance.on=(_,D)=>this._addListener(_,"many",D),this.instance.once=(_,D)=>this._addListener(_,"once",D),this.instance.removeAllListeners=(_=null)=>_!=null?delete this._events[_]:this._events={}}_addListener(x,_,D){var F;return(F=this._events)[x]==null&&(F[x]=[]),this._events[x].push({cb:D,status:_}),this.instance}listenerCount(x){return this._events[x]!=null?this._events[x].length:0}async trigger(x,..._){var D,F;try{return x!=="debug"&&this.trigger("debug",`Event triggered: ${x}`,_),this._events[x]==null?void 0:(this._events[x]=this._events[x].filter(function(N){return N.status!=="none"}),F=this._events[x].map(async N=>{var z,J;if(N.status!=="none"){N.status==="once"&&(N.status="none");try{return J=typeof N.cb=="function"?N.cb(..._):void 0,typeof J?.then=="function"?await J:J}catch(De){return z=De,this.trigger("error",z),null}}}),(await Promise.all(F)).find(function(N){return N!=null}))}catch(N){return D=N,this.trigger("error",D),null}}};var c=a,u,d,p;u=i,d=c,p=class{constructor(x){var _;this.Events=new d(this),this._length=0,this._lists=(function(){var D,F,N;for(N=[],_=D=1,F=x;1<=F?D<=F:D>=F;_=1<=F?++D:--D)N.push(new u((()=>this.incr()),(()=>this.decr())));return N}).call(this)}incr(){if(this._length++===0)return this.Events.trigger("leftzero")}decr(){if(--this._length===0)return this.Events.trigger("zero")}push(x){return this._lists[x.options.priority].push(x)}queued(x){return x!=null?this._lists[x].length:this._length}shiftAll(x){return this._lists.forEach(function(_){return _.forEachShift(x)})}getFirst(x=this._lists){var _,D,F;for(_=0,D=x.length;_<D;_++)if(F=x[_],F.length>0)return F;return[]}shiftLastFrom(x){return this.getFirst(this._lists.slice(x).reverse()).shift()}};var m=p,f;f=class extends Error{};var g=f,h,b,w,y,S;y=10,b=5,S=s,h=g,w=class{constructor(x,_,D,F,N,z,J,De){this.task=x,this.args=_,this.rejectOnDrop=N,this.Events=z,this._states=J,this.Promise=De,this.options=S.load(D,F),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===F.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise((Rt,At)=>{this._resolve=Rt,this._reject=At}),this.retryCount=0}_sanitizePriority(x){var _;return _=~~x!==x?b:x,_<0?0:_>y-1?y-1:_}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:x,message:_="This job has been dropped by Bottleneck"}={}){return this._states.remove(this.options.id)?(this.rejectOnDrop&&this._reject(x??new h(_)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0):!1}_assertStatus(x){var _;if(_=this._states.jobStatus(this.options.id),!(_===x||x==="DONE"&&_===null))throw new h(`Invalid job status ${_}, expected ${x}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`)}doReceive(){return this._states.start(this.options.id),this.Events.trigger("received",{args:this.args,options:this.options})}doQueue(x,_){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:x,blocked:_})}doRun(){return this.retryCount===0?(this._assertStatus("QUEUED"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),this.Events.trigger("scheduled",{args:this.args,options:this.options})}async doExecute(x,_,D,F){var N,z,J;this.retryCount===0?(this._assertStatus("RUNNING"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),z={args:this.args,options:this.options,retryCount:this.retryCount},this.Events.trigger("executing",z);try{if(J=await(x!=null?x.schedule(this.options,this.task,...this.args):this.task(...this.args)),_())return this.doDone(z),await F(this.options,z),this._assertStatus("DONE"),this._resolve(J)}catch(De){return N=De,this._onFailure(N,z,_,D,F)}}doExpire(x,_,D){var F,N;return this._states.jobStatus(this.options.id==="RUNNING")&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),N={args:this.args,options:this.options,retryCount:this.retryCount},F=new h(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(F,N,x,_,D)}async _onFailure(x,_,D,F,N){var z,J;if(D())return z=await this.Events.trigger("failed",x,_),z!=null?(J=~~z,this.Events.trigger("retry",`Retrying ${this.options.id} after ${J} ms`,_),this.retryCount++,F(J)):(this.doDone(_),await N(this.options,_),this._assertStatus("DONE"),this._reject(x))}doDone(x){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",x)}};var k=w,R,P,C;C=s,R=g,P=class{constructor(x,_,D){this.instance=x,this.storeOptions=_,this.clientId=this.instance._randomIndex(),C.load(D,D,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var x;return this.heartbeat==null&&(this.storeOptions.reservoirRefreshInterval!=null&&this.storeOptions.reservoirRefreshAmount!=null||this.storeOptions.reservoirIncreaseInterval!=null&&this.storeOptions.reservoirIncreaseAmount!=null)?typeof(x=this.heartbeat=setInterval(()=>{var _,D,F,N,z;if(N=Date.now(),this.storeOptions.reservoirRefreshInterval!=null&&N>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=N,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),this.storeOptions.reservoirIncreaseInterval!=null&&N>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval&&({reservoirIncreaseAmount:_,reservoirIncreaseMaximum:F,reservoir:z}=this.storeOptions,this._lastReservoirIncrease=N,D=F!=null?Math.min(_,F-z):_,D>0))return this.storeOptions.reservoir+=D,this.instance._drainAll(this.computeCapacity())},this.heartbeatInterval)).unref=="function"?x.unref():void 0:clearInterval(this.heartbeat)}async __publish__(x){return await this.yieldLoop(),this.instance.Events.trigger("message",x.toString())}async __disconnect__(x){return await this.yieldLoop(),clearInterval(this.heartbeat),this.Promise.resolve()}yieldLoop(x=0){return new this.Promise(function(_,D){return setTimeout(_,x)})}computePenalty(){var x;return(x=this.storeOptions.penalty)!=null?x:15*this.storeOptions.minTime||5e3}async __updateSettings__(x){return await this.yieldLoop(),C.overwrite(x,x,this.storeOptions),this._startHeartbeat(),this.instance._drainAll(this.computeCapacity()),!0}async __running__(){return await this.yieldLoop(),this._running}async __queued__(){return await this.yieldLoop(),this.instance.queued()}async __done__(){return await this.yieldLoop(),this._done}async __groupCheck__(x){return await this.yieldLoop(),this._nextRequest+this.timeout<x}computeCapacity(){var x,_;return{maxConcurrent:x,reservoir:_}=this.storeOptions,x!=null&&_!=null?Math.min(x-this._running,_):x!=null?x-this._running:_??null}conditionsCheck(x){var _;return _=this.computeCapacity(),_==null||x<=_}async __incrementReservoir__(x){var _;return await this.yieldLoop(),_=this.storeOptions.reservoir+=x,this.instance._drainAll(this.computeCapacity()),_}async __currentReservoir__(){return await this.yieldLoop(),this.storeOptions.reservoir}isBlocked(x){return this._unblockTime>=x}check(x,_){return this.conditionsCheck(x)&&this._nextRequest-_<=0}async __check__(x){var _;return await this.yieldLoop(),_=Date.now(),this.check(x,_)}async __register__(x,_,D){var F,N;return await this.yieldLoop(),F=Date.now(),this.conditionsCheck(_)?(this._running+=_,this.storeOptions.reservoir!=null&&(this.storeOptions.reservoir-=_),N=Math.max(this._nextRequest-F,0),this._nextRequest=F+N+this.storeOptions.minTime,{success:!0,wait:N,reservoir:this.storeOptions.reservoir}):{success:!1}}strategyIsBlock(){return this.storeOptions.strategy===3}async __submit__(x,_){var D,F,N;if(await this.yieldLoop(),this.storeOptions.maxConcurrent!=null&&_>this.storeOptions.maxConcurrent)throw new R(`Impossible to add a job having a weight of ${_} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`);return F=Date.now(),N=this.storeOptions.highWater!=null&&x===this.storeOptions.highWater&&!this.check(_,F),D=this.strategyIsBlock()&&(N||this.isBlocked(F)),D&&(this._unblockTime=F+this.computePenalty(),this._nextRequest=this._unblockTime+this.storeOptions.minTime,this.instance._dropAllQueued()),{reachedHWM:N,blocked:D,strategy:this.storeOptions.strategy}}async __free__(x,_){return await this.yieldLoop(),this._running-=_,this._done+=_,this.instance._drainAll(this.computeCapacity()),{running:this._running}}};var E=P,T,M;T=g,M=class{constructor(x){this.status=x,this._jobs={},this.counts=this.status.map(function(){return 0})}next(x){var _,D;if(_=this._jobs[x],D=_+1,_!=null&&D<this.status.length)return this.counts[_]--,this.counts[D]++,this._jobs[x]++;if(_!=null)return this.counts[_]--,delete this._jobs[x]}start(x){var _;return _=0,this._jobs[x]=_,this.counts[_]++}remove(x){var _;return _=this._jobs[x],_!=null&&(this.counts[_]--,delete this._jobs[x]),_!=null}jobStatus(x){var _;return(_=this.status[this._jobs[x]])!=null?_:null}statusJobs(x){var _,D,F,N,z;if(x!=null){if(D=this.status.indexOf(x),D<0)throw new T(`status must be one of ${this.status.join(", ")}`);F=this._jobs,N=[];for(_ in F)z=F[_],z===D&&N.push(_);return N}else return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce(((x,_,D)=>(x[this.status[D]]=_,x)),{})}};var G=M,X,ve;X=i,ve=class{constructor(x,_){this.schedule=this.schedule.bind(this),this.name=x,this.Promise=_,this._running=0,this._queue=new X}isEmpty(){return this._queue.length===0}async _tryToRun(){var x,_,D,F,N,z,J;if(this._running<1&&this._queue.length>0)return this._running++,{task:J,args:x,resolve:N,reject:F}=this._queue.shift(),_=await(async function(){try{return z=await J(...x),function(){return N(z)}}catch(De){return D=De,function(){return F(D)}}})(),this._running--,this._tryToRun(),_()}schedule(x,..._){var D,F,N;return N=F=null,D=new this.Promise(function(z,J){return N=z,F=J}),this._queue.push({task:x,args:_,resolve:N,reject:F}),this._tryToRun(),D}};var he=ve,oe="2.19.5",Z={version:oe},$e=Object.freeze({version:oe,default:Z}),Re=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Xe=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Ke=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),tt,ct,sr,et,Je,Fr;Fr=s,tt=c,et=Re,sr=Xe,Je=Ke,ct=(function(){class Q{constructor(_={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=_,Fr.load(this.limiterOptions,this.defaults,this),this.Events=new tt(this),this.instances={},this.Bottleneck=hC,this._startAutoCleanup(),this.sharedConnection=this.connection!=null,this.connection==null&&(this.limiterOptions.datastore==="redis"?this.connection=new et(Object.assign({},this.limiterOptions,{Events:this.Events})):this.limiterOptions.datastore==="ioredis"&&(this.connection=new sr(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(_=""){var D;return(D=this.instances[_])!=null?D:(()=>{var F;return F=this.instances[_]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${_}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",F,_),F})()}async deleteKey(_=""){var D,F;return F=this.instances[_],this.connection&&(D=await this.connection.__runCommand__(["del",...Je.allKeys(`${this.id}-${_}`)])),F!=null&&(delete this.instances[_],await F.disconnect()),F!=null||D>0}limiters(){var _,D,F,N;D=this.instances,F=[];for(_ in D)N=D[_],F.push({key:_,limiter:N});return F}keys(){return Object.keys(this.instances)}async clusterKeys(){var _,D,F,N,z,J,De,Rt,At;if(this.connection==null)return this.Promise.resolve(this.keys());for(J=[],_=null,At=`b_${this.id}-`.length,D=9;_!==0;)for([Rt,F]=await this.connection.__runCommand__(["scan",_??0,"match",`b_${this.id}-*_settings`,"count",1e4]),_=~~Rt,N=0,De=F.length;N<De;N++)z=F[N],J.push(z.slice(At,-D));return J}_startAutoCleanup(){var _;return clearInterval(this.interval),typeof(_=this.interval=setInterval(async()=>{var D,F,N,z,J,De;J=Date.now(),N=this.instances,z=[];for(F in N){De=N[F];try{await De._store.__groupCheck__(J)?z.push(this.deleteKey(F)):z.push(void 0)}catch(Rt){D=Rt,z.push(De.Events.trigger("error",D))}}return z},this.timeout/2)).unref=="function"?_.unref():void 0}updateSettings(_={}){if(Fr.overwrite(_,this.defaults,this),Fr.overwrite(_,_,this.limiterOptions),_.timeout!=null)return this._startAutoCleanup()}disconnect(_=!0){var D;if(!this.sharedConnection)return(D=this.connection)!=null?D.disconnect(_):void 0}}return Q.prototype.defaults={timeout:1e3*60*5,connection:null,Promise,id:"group-key"},Q}).call(e);var Ps=ct,Es,Fn,Wo;Wo=s,Fn=c,Es=(function(){class Q{constructor(_={}){this.options=_,Wo.load(this.options,this.defaults,this),this.Events=new Fn(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise((_,D)=>this._resolve=_)}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(_){var D;return this._arr.push(_),D=this._promise,this._arr.length===this.maxSize?this._flush():this.maxTime!=null&&this._arr.length===1&&(this._timeout=setTimeout(()=>this._flush(),this.maxTime)),D}}return Q.prototype.defaults={maxTime:null,maxSize:null,Promise},Q}).call(e);var Vo=Es,qo=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),K=t($e),He,Wt,qe,xt,yr,Et,Xa,un,fC,xg,Nr,gC=[].splice;Et=10,Wt=5,Nr=s,Xa=m,xt=k,yr=E,un=qo,qe=c,fC=G,xg=he,He=(function(){class Q{constructor(_={},...D){var F,N;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(_,D),Nr.load(_,this.instanceDefaults,this),this._queues=new Xa(Et),this._scheduled={},this._states=new fC(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new qe(this),this._submitLock=new xg("submit",this.Promise),this._registerLock=new xg("register",this.Promise),N=Nr.load(_,this.storeDefaults,{}),this._store=(function(){if(this.datastore==="redis"||this.datastore==="ioredis"||this.connection!=null)return F=Nr.load(_,this.redisStoreDefaults,{}),new un(this,N,F);if(this.datastore==="local")return F=Nr.load(_,this.localStoreDefaults,{}),new yr(this,N,F);throw new Q.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}).call(this),this._queues.on("leftzero",()=>{var z;return(z=this._store.heartbeat)!=null&&typeof z.ref=="function"?z.ref():void 0}),this._queues.on("zero",()=>{var z;return(z=this._store.heartbeat)!=null&&typeof z.unref=="function"?z.unref():void 0})}_validateOptions(_,D){if(!(_!=null&&typeof _=="object"&&D.length===0))throw new Q.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(_){return this._store.__publish__(_)}disconnect(_=!0){return this._store.__disconnect__(_)}chain(_){return this._limiter=_,this}queued(_){return this._queues.queued(_)}clusterQueued(){return this._store.__queued__()}empty(){return this.queued()===0&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(_){return this._states.jobStatus(_)}jobs(_){return this._states.statusJobs(_)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(_=1){return this._store.__check__(_)}_clearGlobalState(_){return this._scheduled[_]!=null?(clearTimeout(this._scheduled[_].expiration),delete this._scheduled[_],!0):!1}async _free(_,D,F,N){var z,J;try{if({running:J}=await this._store.__free__(_,F.weight),this.Events.trigger("debug",`Freed ${F.id}`,N),J===0&&this.empty())return this.Events.trigger("idle")}catch(De){return z=De,this.Events.trigger("error",z)}}_run(_,D,F){var N,z,J;return D.doRun(),N=this._clearGlobalState.bind(this,_),J=this._run.bind(this,_,D),z=this._free.bind(this,_,D),this._scheduled[_]={timeout:setTimeout(()=>D.doExecute(this._limiter,N,J,z),F),expiration:D.options.expiration!=null?setTimeout(function(){return D.doExpire(N,J,z)},F+D.options.expiration):void 0,job:D}}_drainOne(_){return this._registerLock.schedule(()=>{var D,F,N,z,J;return this.queued()===0?this.Promise.resolve(null):(J=this._queues.getFirst(),{options:z,args:D}=N=J.first(),_!=null&&z.weight>_?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${z.id}`,{args:D,options:z}),F=this._randomIndex(),this._store.__register__(F,z.weight,z.expiration).then(({success:De,wait:Rt,reservoir:At})=>{var ec;return this.Events.trigger("debug",`Drained ${z.id}`,{success:De,args:D,options:z}),De?(J.shift(),ec=this.empty(),ec&&this.Events.trigger("empty"),At===0&&this.Events.trigger("depleted",ec),this._run(F,N,Rt),this.Promise.resolve(z.weight)):this.Promise.resolve(null)})))})}_drainAll(_,D=0){return this._drainOne(_).then(F=>{var N;return F!=null?(N=_!=null?_-F:_,this._drainAll(N,D+F)):this.Promise.resolve(D)}).catch(F=>this.Events.trigger("error",F))}_dropAllQueued(_){return this._queues.shiftAll(function(D){return D.doDrop({message:_})})}stop(_={}){var D,F;return _=Nr.load(_,this.stopDefaults),F=N=>{var z;return z=()=>{var J;return J=this._states.counts,J[0]+J[1]+J[2]+J[3]===N},new this.Promise((J,De)=>z()?J():this.on("done",()=>{if(z())return this.removeAllListeners("done"),J()}))},D=_.dropWaitingJobs?(this._run=function(N,z){return z.doDrop({message:_.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var N,z,J;z=this._scheduled;for(N in z)J=z[N],this.jobStatus(J.job.options.id)==="RUNNING"&&(clearTimeout(J.timeout),clearTimeout(J.expiration),J.job.doDrop({message:_.dropErrorMessage}));return this._dropAllQueued(_.dropErrorMessage),F(0)}))):this.schedule({priority:Et-1,weight:0},()=>F(1)),this._receive=function(N){return N._reject(new Q.prototype.BottleneckError(_.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new Q.prototype.BottleneckError("stop() has already been called")),D}async _addToQueue(_){var D,F,N,z,J,De,Rt;({args:D,options:z}=_);try{({reachedHWM:J,blocked:F,strategy:Rt}=await this._store.__submit__(this.queued(),z.weight))}catch(At){return N=At,this.Events.trigger("debug",`Could not queue ${z.id}`,{args:D,options:z,error:N}),_.doDrop({error:N}),!1}return F?(_.doDrop(),!0):J&&(De=Rt===Q.prototype.strategy.LEAK?this._queues.shiftLastFrom(z.priority):Rt===Q.prototype.strategy.OVERFLOW_PRIORITY?this._queues.shiftLastFrom(z.priority+1):Rt===Q.prototype.strategy.OVERFLOW?_:void 0,De?.doDrop(),De==null||Rt===Q.prototype.strategy.OVERFLOW)?(De==null&&_.doDrop(),J):(_.doQueue(J,F),this._queues.push(_),await this._drainAll(),J)}_receive(_){return this._states.jobStatus(_.options.id)!=null?(_._reject(new Q.prototype.BottleneckError(`A job with the same id already exists (id=${_.options.id})`)),!1):(_.doReceive(),this._submitLock.schedule(this._addToQueue,_))}submit(..._){var D,F,N,z,J,De,Rt;return typeof _[0]=="function"?(J=_,[F,..._]=J,[D]=gC.call(_,-1),z=Nr.load({},this.jobDefaults)):(De=_,[z,F,..._]=De,[D]=gC.call(_,-1),z=Nr.load(z,this.jobDefaults)),Rt=(...At)=>new this.Promise(function(ec,TF){return F(...At,function(...yC){return(yC[0]!=null?TF:ec)(yC)})}),N=new xt(Rt,_,z,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),N.promise.then(function(At){return typeof D=="function"?D(...At):void 0}).catch(function(At){return Array.isArray(At)?typeof D=="function"?D(...At):void 0:typeof D=="function"?D(At):void 0}),this._receive(N)}schedule(..._){var D,F,N;return typeof _[0]=="function"?([N,..._]=_,F={}):[F,N,..._]=_,D=new xt(N,_,F,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(D),D.promise}wrap(_){var D,F;return D=this.schedule.bind(this),F=function(...N){return D(_.bind(this),...N)},F.withOptions=function(N,...z){return D(N,_,...z)},F}async updateSettings(_={}){return await this._store.__updateSettings__(Nr.overwrite(_,this.storeDefaults)),Nr.overwrite(_,this.instanceDefaults,this),this}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(_=0){return this._store.__incrementReservoir__(_)}}return Q.default=Q,Q.Events=qe,Q.version=Q.prototype.version=K.version,Q.strategy=Q.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},Q.BottleneckError=Q.prototype.BottleneckError=g,Q.Group=Q.prototype.Group=Ps,Q.RedisConnection=Q.prototype.RedisConnection=Re,Q.IORedisConnection=Q.prototype.IORedisConnection=Xe,Q.Batcher=Q.prototype.Batcher=Vo,Q.prototype.jobDefaults={priority:Wt,weight:1,expiration:null,id:"<no-id>"},Q.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:Q.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},Q.prototype.localStoreDefaults={Promise,timeout:null,heartbeatInterval:250},Q.prototype.redisStoreDefaults={Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},Q.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise},Q.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},Q}).call(e);var hC=He,AF=hC;return AF}))});function k1(e,t,r){return e.retryLimiter.schedule(C1,e,t,r)}async function C1(e,t,r){let{pathname:n}=new URL(r.url,"http://github.test"),s=P1(r.method,n),o=!s&&r.method!=="GET"&&r.method!=="HEAD",i=r.method==="GET"&&n.startsWith("/search/"),a=n.startsWith("/graphql"),u=~~t.retryCount>0?{priority:0,weight:0}:{};e.clustering&&(u.expiration=1e3*60),(o||a)&&await e.write.key(e.id).schedule(u,u_),o&&e.triggersNotification(n)&&await e.notifications.key(e.id).schedule(u,u_),i&&await e.search.key(e.id).schedule(u,u_);let d=(s?e.auth:e.global).key(e.id).schedule(u,t,r);if(a){let p=await d;if(p.data.errors!=null&&p.data.errors.some(m=>m.type==="RATE_LIMITED"))throw Object.assign(new Error("GraphQL Rate Limit Exceeded"),{response:p,data:p.data})}return d}function P1(e,t){return e==="PATCH"&&/^\/applications\/[^/]+\/token\/scoped$/.test(t)||e==="POST"&&(/^\/applications\/[^/]+\/token$/.test(t)||/^\/app\/installations\/[^/]+\/access_tokens$/.test(t)||t==="/login/oauth/access_token")}function A1(e){let r=`^(?:${e.map(n=>n.split("/").map(s=>s.startsWith("{")?"(?:.+?)":s).join("/")).map(n=>`(?:${n})`).join("|")})[^/]*$`;return new RegExp(r,"i")}function Xi(e,t){let{enabled:r=!0,Bottleneck:n=y$.default,id:s="no-id",timeout:o=1e3*60*2,connection:i}=t.throttle||{};if(!r)return{};let a={timeout:o};typeof i<"u"&&(a.connection=i);let c=Object.assign({clustering:i!=null,triggersNotification:b$,fallbackSecondaryRateRetryAfter:60,retryAfterBaseValue:1e3,id:s},t.throttle);if(typeof c.onSecondaryRateLimit!="function"||typeof c.onRateLimit!="function")throw new Error(`octokit/plugin-throttling error:
68
+ `)}function u1(e,t,r){if(r){if(typeof t=="string"&&"query"in r)return Promise.reject(new Error('[@octokit/graphql] "query" cannot be used as variable name'));for(let i in r)if(c1.includes(i))return Promise.reject(new Error(`[@octokit/graphql] "${i}" cannot be used as variable name`))}let n=typeof t=="string"?Object.assign({query:t},r):t,s=Object.keys(n).reduce((i,a)=>a1.includes(a)?(i[a]=n[a],i):(i.variables||(i.variables={}),i.variables[a]=n[a],i),{}),o=n.baseUrl||e.endpoint.DEFAULTS.baseUrl;return VT.test(o)&&(s.url=o.replace(VT,"/api/graphql")),e(s).then(i=>{if(i.data.errors){let a={};for(let c of Object.keys(i.headers))a[c]=i.headers[c];throw new i1(s,a,i.data)}return i.data.data})}function JS(e,t){let r=e.defaults(t);return Object.assign((s,o)=>u1(r,s,o),{defaults:JS.bind(null,r),endpoint:r.endpoint})}function qT(e){return JS(e,{method:"POST",url:"/graphql"})}var s1,i1,a1,c1,VT,Y5,ZT=A(()=>{KS();gu();s1="0.0.0-development";i1=class extends Error{constructor(e,t,r){super(o1(r)),this.request=e,this.headers=t,this.response=r,this.errors=r.errors,this.data=r.data,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}name="GraphqlResponseError";errors;data},a1=["method","baseUrl","url","headers","request","query","mediaType","operationName"],c1=["query","method","url"],VT=/\/api\/v3\/?$/;Y5=JS(bu,{headers:{"user-agent":`octokit-graphql.js/${s1} ${ns()}`},method:"POST",url:"/graphql"})});async function d1(e){let t=l1(e),r=e.startsWith("v1.")||e.startsWith("ghs_"),n=e.startsWith("ghu_");return{type:"token",token:e,tokenType:t?"app":r?"installation":n?"user-to-server":"oauth"}}function p1(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function m1(e,t,r,n){let s=t.endpoint.merge(r,n);return s.headers.authorization=p1(e),t(s)}var YS,KT,JT,l1,YT,QT=A(()=>{YS="(?:[a-zA-Z0-9_-]+)",KT="\\.",JT=new RegExp(`^${YS}${KT}${YS}${KT}${YS}$`),l1=JT.test.bind(JT);YT=function(t){if(!t)throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");if(typeof t!="string")throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");return t=t.replace(/^(token|bearer) +/i,""),Object.assign(d1.bind(null,t),{hook:m1.bind(null,t)})}});var QS,XT=A(()=>{QS="7.0.6"});function h1(e={}){return typeof e.debug!="function"&&(e.debug=e$),typeof e.info!="function"&&(e.info=e$),typeof e.warn!="function"&&(e.warn=f1),typeof e.error!="function"&&(e.error=g1),e}var e$,f1,g1,t$,gm,r$=A(()=>{gu();vT();KS();ZT();QT();XT();e$=()=>{},f1=console.warn.bind(console),g1=console.error.bind(console);t$=`octokit-core.js/${QS} ${ns()}`,gm=class{static VERSION=QS;static defaults(t){return class extends this{constructor(...n){let s=n[0]||{};if(typeof t=="function"){super(t(s));return}super(Object.assign({},t,s,s.userAgent&&t.userAgent?{userAgent:`${s.userAgent} ${t.userAgent}`}:null))}}}static plugins=[];static plugin(...t){let r=this.plugins;return class extends this{static plugins=r.concat(t.filter(s=>!r.includes(s)))}}constructor(t={}){let r=new _T.Collection,n={baseUrl:bu.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},t.request,{hook:r.bind(null,"request")}),mediaType:{previews:[],format:""}};if(n.headers["user-agent"]=t.userAgent?`${t.userAgent} ${t$}`:t$,t.baseUrl&&(n.baseUrl=t.baseUrl),t.previews&&(n.mediaType.previews=t.previews),t.timeZone&&(n.headers["time-zone"]=t.timeZone),this.request=bu.defaults(n),this.graphql=qT(this.request).defaults(n),this.log=h1(t.log),this.hook=r,t.authStrategy){let{authStrategy:o,...i}=t,a=o(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:i},t.auth));r.wrap("request",a.hook),this.auth=a}else if(!t.auth)this.auth=async()=>({type:"unauthenticated"});else{let o=YT(t.auth);r.wrap("request",o.hook),this.auth=o}let s=this.constructor;for(let o=0;o<s.plugins.length;++o)Object.assign(this,s.plugins[o](this,t))}request;graphql;log;hook;auth}});var n$,s$=A(()=>{n$="6.0.0"});function XS(e){e.hook.wrap("request",(t,r)=>{e.log.debug("request",r);let n=Date.now(),s=e.request.endpoint.parse(r),o=s.url.replace(r.baseUrl,"");return t(r).then(i=>{let a=i.headers["x-github-request-id"];return e.log.info(`${s.method} ${o} - ${i.status} with id ${a} in ${Date.now()-n}ms`),i}).catch(i=>{let a=i.response?.headers["x-github-request-id"]||"UNKNOWN";throw e.log.error(`${s.method} ${o} - ${i.status} with id ${a} in ${Date.now()-n}ms`),i})})}var o$=A(()=>{s$();XS.VERSION=n$});function b1(e){if(!e.data)return{...e,data:[]};if(!(("total_count"in e.data||"total_commits"in e.data)&&!("url"in e.data)))return e;let r=e.data.incomplete_results,n=e.data.repository_selection,s=e.data.total_count,o=e.data.total_commits;delete e.data.incomplete_results,delete e.data.repository_selection,delete e.data.total_count,delete e.data.total_commits;let i=Object.keys(e.data)[0],a=e.data[i];return e.data=a,typeof r<"u"&&(e.data.incomplete_results=r),typeof n<"u"&&(e.data.repository_selection=n),e.data.total_count=s,e.data.total_commits=o,e}function e_(e,t,r){let n=typeof t=="function"?t.endpoint(r):e.request.endpoint(t,r),s=typeof t=="function"?t:e.request,o=n.method,i=n.headers,a=n.url;return{[Symbol.asyncIterator]:()=>({async next(){if(!a)return{done:!0};try{let c=await s({method:o,url:a,headers:i}),u=b1(c);if(a=((u.headers.link||"").match(/<([^<>]+)>;\s*rel="next"/)||[])[1],!a&&"total_commits"in u.data){let d=new URL(u.url),p=d.searchParams,m=parseInt(p.get("page")||"1",10),f=parseInt(p.get("per_page")||"250",10);m*f<u.data.total_commits&&(p.set("page",String(m+1)),a=d.toString())}return{value:u}}catch(c){if(c.status!==409)throw c;return a="",{value:{status:200,headers:{},data:[]}}}}})}}function i$(e,t,r,n){return typeof r=="function"&&(n=r,r=void 0),a$(e,[],e_(e,t,r)[Symbol.asyncIterator](),n)}function a$(e,t,r,n){return r.next().then(s=>{if(s.done)return t;let o=!1;function i(){o=!0}return t=t.concat(n?n(s.value,i):s.value.data),o?t:a$(e,t,r,n)})}function t_(e){return{paginate:Object.assign(i$.bind(null,e),{iterator:e_.bind(null,e)})}}var y1,fY,c$=A(()=>{y1="0.0.0-development";fY=Object.assign(i$,{iterator:e_});t_.VERSION=y1});var r_,u$=A(()=>{r_="17.0.0"});var w1,l$,d$=A(()=>{w1={actions:{addCustomLabelsToSelfHostedRunnerForOrg:["POST /orgs/{org}/actions/runners/{runner_id}/labels"],addCustomLabelsToSelfHostedRunnerForRepo:["POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],addRepoAccessToSelfHostedRunnerGroupInOrg:["PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],approveWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"],cancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],createEnvironmentVariable:["POST /repos/{owner}/{repo}/environments/{environment_name}/variables"],createHostedRunnerForOrg:["POST /orgs/{org}/actions/hosted-runners"],createOrUpdateEnvironmentSecret:["PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],createOrgVariable:["POST /orgs/{org}/actions/variables"],createRegistrationTokenForOrg:["POST /orgs/{org}/actions/runners/registration-token"],createRegistrationTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/registration-token"],createRemoveTokenForOrg:["POST /orgs/{org}/actions/runners/remove-token"],createRemoveTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/remove-token"],createRepoVariable:["POST /repos/{owner}/{repo}/actions/variables"],createWorkflowDispatch:["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],deleteActionsCacheById:["DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}"],deleteActionsCacheByKey:["DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}"],deleteArtifact:["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],deleteCustomImageFromOrg:["DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}"],deleteCustomImageVersionFromOrg:["DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}"],deleteEnvironmentSecret:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],deleteEnvironmentVariable:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],deleteHostedRunnerForOrg:["DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],deleteOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}"],deleteOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],deleteRepoVariable:["DELETE /repos/{owner}/{repo}/actions/variables/{name}"],deleteSelfHostedRunnerFromOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}"],deleteSelfHostedRunnerFromRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"],deleteWorkflowRun:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],deleteWorkflowRunLogs:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],disableSelectedRepositoryGithubActionsOrganization:["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"],disableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"],downloadArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"],downloadJobLogsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"],downloadWorkflowRunAttemptLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"],downloadWorkflowRunLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],enableSelectedRepositoryGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"],enableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"],forceCancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel"],generateRunnerJitconfigForOrg:["POST /orgs/{org}/actions/runners/generate-jitconfig"],generateRunnerJitconfigForRepo:["POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig"],getActionsCacheList:["GET /repos/{owner}/{repo}/actions/caches"],getActionsCacheUsage:["GET /repos/{owner}/{repo}/actions/cache/usage"],getActionsCacheUsageByRepoForOrg:["GET /orgs/{org}/actions/cache/usage-by-repository"],getActionsCacheUsageForOrg:["GET /orgs/{org}/actions/cache/usage"],getAllowedActionsOrganization:["GET /orgs/{org}/actions/permissions/selected-actions"],getAllowedActionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"],getArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],getCustomImageForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}"],getCustomImageVersionForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}"],getCustomOidcSubClaimForRepo:["GET /repos/{owner}/{repo}/actions/oidc/customization/sub"],getEnvironmentPublicKey:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key"],getEnvironmentSecret:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],getEnvironmentVariable:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],getGithubActionsDefaultWorkflowPermissionsOrganization:["GET /orgs/{org}/actions/permissions/workflow"],getGithubActionsDefaultWorkflowPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/workflow"],getGithubActionsPermissionsOrganization:["GET /orgs/{org}/actions/permissions"],getGithubActionsPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions"],getHostedRunnerForOrg:["GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],getHostedRunnersGithubOwnedImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/github-owned"],getHostedRunnersLimitsForOrg:["GET /orgs/{org}/actions/hosted-runners/limits"],getHostedRunnersMachineSpecsForOrg:["GET /orgs/{org}/actions/hosted-runners/machine-sizes"],getHostedRunnersPartnerImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/partner"],getHostedRunnersPlatformsForOrg:["GET /orgs/{org}/actions/hosted-runners/platforms"],getJobForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],getOrgPublicKey:["GET /orgs/{org}/actions/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}"],getOrgVariable:["GET /orgs/{org}/actions/variables/{name}"],getPendingDeploymentsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],getRepoPermissions:["GET /repos/{owner}/{repo}/actions/permissions",{},{renamed:["actions","getGithubActionsPermissionsRepository"]}],getRepoPublicKey:["GET /repos/{owner}/{repo}/actions/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],getRepoVariable:["GET /repos/{owner}/{repo}/actions/variables/{name}"],getReviewsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"],getSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}"],getSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],getWorkflow:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],getWorkflowAccessToRepository:["GET /repos/{owner}/{repo}/actions/permissions/access"],getWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],getWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"],getWorkflowRunUsage:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],getWorkflowUsage:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],listArtifactsForRepo:["GET /repos/{owner}/{repo}/actions/artifacts"],listCustomImageVersionsForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions"],listCustomImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom"],listEnvironmentSecrets:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets"],listEnvironmentVariables:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables"],listGithubHostedRunnersInGroupForOrg:["GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners"],listHostedRunnersForOrg:["GET /orgs/{org}/actions/hosted-runners"],listJobsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],listJobsForWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"],listLabelsForSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}/labels"],listLabelsForSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],listOrgSecrets:["GET /orgs/{org}/actions/secrets"],listOrgVariables:["GET /orgs/{org}/actions/variables"],listRepoOrganizationSecrets:["GET /repos/{owner}/{repo}/actions/organization-secrets"],listRepoOrganizationVariables:["GET /repos/{owner}/{repo}/actions/organization-variables"],listRepoSecrets:["GET /repos/{owner}/{repo}/actions/secrets"],listRepoVariables:["GET /repos/{owner}/{repo}/actions/variables"],listRepoWorkflows:["GET /repos/{owner}/{repo}/actions/workflows"],listRunnerApplicationsForOrg:["GET /orgs/{org}/actions/runners/downloads"],listRunnerApplicationsForRepo:["GET /repos/{owner}/{repo}/actions/runners/downloads"],listSelectedReposForOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"],listSelectedReposForOrgVariable:["GET /orgs/{org}/actions/variables/{name}/repositories"],listSelectedRepositoriesEnabledGithubActionsOrganization:["GET /orgs/{org}/actions/permissions/repositories"],listSelfHostedRunnersForOrg:["GET /orgs/{org}/actions/runners"],listSelfHostedRunnersForRepo:["GET /repos/{owner}/{repo}/actions/runners"],listWorkflowRunArtifacts:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"],listWorkflowRuns:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"],listWorkflowRunsForRepo:["GET /repos/{owner}/{repo}/actions/runs"],reRunJobForWorkflowRun:["POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun"],reRunWorkflow:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],reRunWorkflowFailedJobs:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs"],removeAllCustomLabelsFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels"],removeAllCustomLabelsFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],removeCustomLabelFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}"],removeCustomLabelFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],reviewCustomGatesForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule"],reviewPendingDeploymentsForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],setAllowedActionsOrganization:["PUT /orgs/{org}/actions/permissions/selected-actions"],setAllowedActionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"],setCustomLabelsForSelfHostedRunnerForOrg:["PUT /orgs/{org}/actions/runners/{runner_id}/labels"],setCustomLabelsForSelfHostedRunnerForRepo:["PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],setCustomOidcSubClaimForRepo:["PUT /repos/{owner}/{repo}/actions/oidc/customization/sub"],setGithubActionsDefaultWorkflowPermissionsOrganization:["PUT /orgs/{org}/actions/permissions/workflow"],setGithubActionsDefaultWorkflowPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/workflow"],setGithubActionsPermissionsOrganization:["PUT /orgs/{org}/actions/permissions"],setGithubActionsPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"],setSelectedReposForOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories"],setSelectedRepositoriesEnabledGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories"],setWorkflowAccessToRepository:["PUT /repos/{owner}/{repo}/actions/permissions/access"],updateEnvironmentVariable:["PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],updateHostedRunnerForOrg:["PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],updateOrgVariable:["PATCH /orgs/{org}/actions/variables/{name}"],updateRepoVariable:["PATCH /repos/{owner}/{repo}/actions/variables/{name}"]},activity:{checkRepoIsStarredByAuthenticatedUser:["GET /user/starred/{owner}/{repo}"],deleteRepoSubscription:["DELETE /repos/{owner}/{repo}/subscription"],deleteThreadSubscription:["DELETE /notifications/threads/{thread_id}/subscription"],getFeeds:["GET /feeds"],getRepoSubscription:["GET /repos/{owner}/{repo}/subscription"],getThread:["GET /notifications/threads/{thread_id}"],getThreadSubscriptionForAuthenticatedUser:["GET /notifications/threads/{thread_id}/subscription"],listEventsForAuthenticatedUser:["GET /users/{username}/events"],listNotificationsForAuthenticatedUser:["GET /notifications"],listOrgEventsForAuthenticatedUser:["GET /users/{username}/events/orgs/{org}"],listPublicEvents:["GET /events"],listPublicEventsForRepoNetwork:["GET /networks/{owner}/{repo}/events"],listPublicEventsForUser:["GET /users/{username}/events/public"],listPublicOrgEvents:["GET /orgs/{org}/events"],listReceivedEventsForUser:["GET /users/{username}/received_events"],listReceivedPublicEventsForUser:["GET /users/{username}/received_events/public"],listRepoEvents:["GET /repos/{owner}/{repo}/events"],listRepoNotificationsForAuthenticatedUser:["GET /repos/{owner}/{repo}/notifications"],listReposStarredByAuthenticatedUser:["GET /user/starred"],listReposStarredByUser:["GET /users/{username}/starred"],listReposWatchedByUser:["GET /users/{username}/subscriptions"],listStargazersForRepo:["GET /repos/{owner}/{repo}/stargazers"],listWatchedReposForAuthenticatedUser:["GET /user/subscriptions"],listWatchersForRepo:["GET /repos/{owner}/{repo}/subscribers"],markNotificationsAsRead:["PUT /notifications"],markRepoNotificationsAsRead:["PUT /repos/{owner}/{repo}/notifications"],markThreadAsDone:["DELETE /notifications/threads/{thread_id}"],markThreadAsRead:["PATCH /notifications/threads/{thread_id}"],setRepoSubscription:["PUT /repos/{owner}/{repo}/subscription"],setThreadSubscription:["PUT /notifications/threads/{thread_id}/subscription"],starRepoForAuthenticatedUser:["PUT /user/starred/{owner}/{repo}"],unstarRepoForAuthenticatedUser:["DELETE /user/starred/{owner}/{repo}"]},apps:{addRepoToInstallation:["PUT /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","addRepoToInstallationForAuthenticatedUser"]}],addRepoToInstallationForAuthenticatedUser:["PUT /user/installations/{installation_id}/repositories/{repository_id}"],checkToken:["POST /applications/{client_id}/token"],createFromManifest:["POST /app-manifests/{code}/conversions"],createInstallationAccessToken:["POST /app/installations/{installation_id}/access_tokens"],deleteAuthorization:["DELETE /applications/{client_id}/grant"],deleteInstallation:["DELETE /app/installations/{installation_id}"],deleteToken:["DELETE /applications/{client_id}/token"],getAuthenticated:["GET /app"],getBySlug:["GET /apps/{app_slug}"],getInstallation:["GET /app/installations/{installation_id}"],getOrgInstallation:["GET /orgs/{org}/installation"],getRepoInstallation:["GET /repos/{owner}/{repo}/installation"],getSubscriptionPlanForAccount:["GET /marketplace_listing/accounts/{account_id}"],getSubscriptionPlanForAccountStubbed:["GET /marketplace_listing/stubbed/accounts/{account_id}"],getUserInstallation:["GET /users/{username}/installation"],getWebhookConfigForApp:["GET /app/hook/config"],getWebhookDelivery:["GET /app/hook/deliveries/{delivery_id}"],listAccountsForPlan:["GET /marketplace_listing/plans/{plan_id}/accounts"],listAccountsForPlanStubbed:["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"],listInstallationReposForAuthenticatedUser:["GET /user/installations/{installation_id}/repositories"],listInstallationRequestsForAuthenticatedApp:["GET /app/installation-requests"],listInstallations:["GET /app/installations"],listInstallationsForAuthenticatedUser:["GET /user/installations"],listPlans:["GET /marketplace_listing/plans"],listPlansStubbed:["GET /marketplace_listing/stubbed/plans"],listReposAccessibleToInstallation:["GET /installation/repositories"],listSubscriptionsForAuthenticatedUser:["GET /user/marketplace_purchases"],listSubscriptionsForAuthenticatedUserStubbed:["GET /user/marketplace_purchases/stubbed"],listWebhookDeliveries:["GET /app/hook/deliveries"],redeliverWebhookDelivery:["POST /app/hook/deliveries/{delivery_id}/attempts"],removeRepoFromInstallation:["DELETE /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","removeRepoFromInstallationForAuthenticatedUser"]}],removeRepoFromInstallationForAuthenticatedUser:["DELETE /user/installations/{installation_id}/repositories/{repository_id}"],resetToken:["PATCH /applications/{client_id}/token"],revokeInstallationAccessToken:["DELETE /installation/token"],scopeToken:["POST /applications/{client_id}/token/scoped"],suspendInstallation:["PUT /app/installations/{installation_id}/suspended"],unsuspendInstallation:["DELETE /app/installations/{installation_id}/suspended"],updateWebhookConfigForApp:["PATCH /app/hook/config"]},billing:{getGithubActionsBillingOrg:["GET /orgs/{org}/settings/billing/actions"],getGithubActionsBillingUser:["GET /users/{username}/settings/billing/actions"],getGithubBillingPremiumRequestUsageReportOrg:["GET /organizations/{org}/settings/billing/premium_request/usage"],getGithubBillingPremiumRequestUsageReportUser:["GET /users/{username}/settings/billing/premium_request/usage"],getGithubBillingUsageReportOrg:["GET /organizations/{org}/settings/billing/usage"],getGithubBillingUsageReportUser:["GET /users/{username}/settings/billing/usage"],getGithubPackagesBillingOrg:["GET /orgs/{org}/settings/billing/packages"],getGithubPackagesBillingUser:["GET /users/{username}/settings/billing/packages"],getSharedStorageBillingOrg:["GET /orgs/{org}/settings/billing/shared-storage"],getSharedStorageBillingUser:["GET /users/{username}/settings/billing/shared-storage"]},campaigns:{createCampaign:["POST /orgs/{org}/campaigns"],deleteCampaign:["DELETE /orgs/{org}/campaigns/{campaign_number}"],getCampaignSummary:["GET /orgs/{org}/campaigns/{campaign_number}"],listOrgCampaigns:["GET /orgs/{org}/campaigns"],updateCampaign:["PATCH /orgs/{org}/campaigns/{campaign_number}"]},checks:{create:["POST /repos/{owner}/{repo}/check-runs"],createSuite:["POST /repos/{owner}/{repo}/check-suites"],get:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],getSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],listAnnotations:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"],listForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],listForSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"],listSuitesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],rerequestRun:["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"],rerequestSuite:["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"],setSuitesPreferences:["PATCH /repos/{owner}/{repo}/check-suites/preferences"],update:["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]},codeScanning:{commitAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits"],createAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],createVariantAnalysis:["POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses"],deleteAnalysis:["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"],deleteCodeqlDatabase:["DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getAlert:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}",{},{renamedParameters:{alert_id:"alert_number"}}],getAnalysis:["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"],getAutofix:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],getCodeqlDatabase:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getDefaultSetup:["GET /repos/{owner}/{repo}/code-scanning/default-setup"],getSarif:["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],getVariantAnalysis:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}"],getVariantAnalysisRepoTask:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}"],listAlertInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"],listAlertsForOrg:["GET /orgs/{org}/code-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/code-scanning/alerts"],listAlertsInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",{},{renamed:["codeScanning","listAlertInstances"]}],listCodeqlDatabases:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases"],listRecentAnalyses:["GET /repos/{owner}/{repo}/code-scanning/analyses"],updateAlert:["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"],updateDefaultSetup:["PATCH /repos/{owner}/{repo}/code-scanning/default-setup"],uploadSarif:["POST /repos/{owner}/{repo}/code-scanning/sarifs"]},codeSecurity:{attachConfiguration:["POST /orgs/{org}/code-security/configurations/{configuration_id}/attach"],attachEnterpriseConfiguration:["POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach"],createConfiguration:["POST /orgs/{org}/code-security/configurations"],createConfigurationForEnterprise:["POST /enterprises/{enterprise}/code-security/configurations"],deleteConfiguration:["DELETE /orgs/{org}/code-security/configurations/{configuration_id}"],deleteConfigurationForEnterprise:["DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],detachConfiguration:["DELETE /orgs/{org}/code-security/configurations/detach"],getConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}"],getConfigurationForRepository:["GET /repos/{owner}/{repo}/code-security-configuration"],getConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations"],getConfigurationsForOrg:["GET /orgs/{org}/code-security/configurations"],getDefaultConfigurations:["GET /orgs/{org}/code-security/configurations/defaults"],getDefaultConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/defaults"],getRepositoriesForConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories"],getRepositoriesForEnterpriseConfiguration:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories"],getSingleConfigurationForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],setConfigurationAsDefault:["PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults"],setConfigurationAsDefaultForEnterprise:["PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults"],updateConfiguration:["PATCH /orgs/{org}/code-security/configurations/{configuration_id}"],updateEnterpriseConfiguration:["PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}"]},codesOfConduct:{getAllCodesOfConduct:["GET /codes_of_conduct"],getConductCode:["GET /codes_of_conduct/{key}"]},codespaces:{addRepositoryForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],checkPermissionsForDevcontainer:["GET /repos/{owner}/{repo}/codespaces/permissions_check"],codespaceMachinesForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/machines"],createForAuthenticatedUser:["POST /user/codespaces"],createOrUpdateOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],createOrUpdateSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}"],createWithPrForAuthenticatedUser:["POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces"],createWithRepoForAuthenticatedUser:["POST /repos/{owner}/{repo}/codespaces"],deleteForAuthenticatedUser:["DELETE /user/codespaces/{codespace_name}"],deleteFromOrganization:["DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}"],deleteOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],deleteSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}"],exportForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/exports"],getCodespacesForUserInOrg:["GET /orgs/{org}/members/{username}/codespaces"],getExportDetailsForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/exports/{export_id}"],getForAuthenticatedUser:["GET /user/codespaces/{codespace_name}"],getOrgPublicKey:["GET /orgs/{org}/codespaces/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}"],getPublicKeyForAuthenticatedUser:["GET /user/codespaces/secrets/public-key"],getRepoPublicKey:["GET /repos/{owner}/{repo}/codespaces/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],getSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}"],listDevcontainersInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/devcontainers"],listForAuthenticatedUser:["GET /user/codespaces"],listInOrganization:["GET /orgs/{org}/codespaces",{},{renamedParameters:{org_id:"org"}}],listInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces"],listOrgSecrets:["GET /orgs/{org}/codespaces/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/codespaces/secrets"],listRepositoriesForSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}/repositories"],listSecretsForAuthenticatedUser:["GET /user/codespaces/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],preFlightWithRepoForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/new"],publishForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/publish"],removeRepositoryForSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],repoMachinesForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/machines"],setRepositoriesForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],startForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/start"],stopForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/stop"],stopInOrganization:["POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop"],updateForAuthenticatedUser:["PATCH /user/codespaces/{codespace_name}"]},copilot:{addCopilotSeatsForTeams:["POST /orgs/{org}/copilot/billing/selected_teams"],addCopilotSeatsForUsers:["POST /orgs/{org}/copilot/billing/selected_users"],cancelCopilotSeatAssignmentForTeams:["DELETE /orgs/{org}/copilot/billing/selected_teams"],cancelCopilotSeatAssignmentForUsers:["DELETE /orgs/{org}/copilot/billing/selected_users"],copilotMetricsForOrganization:["GET /orgs/{org}/copilot/metrics"],copilotMetricsForTeam:["GET /orgs/{org}/team/{team_slug}/copilot/metrics"],getCopilotOrganizationDetails:["GET /orgs/{org}/copilot/billing"],getCopilotSeatDetailsForUser:["GET /orgs/{org}/members/{username}/copilot"],listCopilotSeats:["GET /orgs/{org}/copilot/billing/seats"]},credentials:{revoke:["POST /credentials/revoke"]},dependabot:{addSelectedRepoToOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],deleteOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],getAlert:["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],getOrgPublicKey:["GET /orgs/{org}/dependabot/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}"],getRepoPublicKey:["GET /repos/{owner}/{repo}/dependabot/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],listAlertsForEnterprise:["GET /enterprises/{enterprise}/dependabot/alerts"],listAlertsForOrg:["GET /orgs/{org}/dependabot/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/dependabot/alerts"],listOrgSecrets:["GET /orgs/{org}/dependabot/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/dependabot/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],repositoryAccessForOrg:["GET /organizations/{org}/dependabot/repository-access"],setRepositoryAccessDefaultLevel:["PUT /organizations/{org}/dependabot/repository-access/default-level"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],updateAlert:["PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],updateRepositoryAccessForOrg:["PATCH /organizations/{org}/dependabot/repository-access"]},dependencyGraph:{createRepositorySnapshot:["POST /repos/{owner}/{repo}/dependency-graph/snapshots"],diffRange:["GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}"],exportSbom:["GET /repos/{owner}/{repo}/dependency-graph/sbom"]},emojis:{get:["GET /emojis"]},enterpriseTeamMemberships:{add:["PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"],bulkAdd:["POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add"],bulkRemove:["POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove"],get:["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"],list:["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships"],remove:["DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"]},enterpriseTeamOrganizations:{add:["PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],bulkAdd:["POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add"],bulkRemove:["POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove"],delete:["DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],getAssignment:["GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],getAssignments:["GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations"]},enterpriseTeams:{create:["POST /enterprises/{enterprise}/teams"],delete:["DELETE /enterprises/{enterprise}/teams/{team_slug}"],get:["GET /enterprises/{enterprise}/teams/{team_slug}"],list:["GET /enterprises/{enterprise}/teams"],update:["PATCH /enterprises/{enterprise}/teams/{team_slug}"]},gists:{checkIsStarred:["GET /gists/{gist_id}/star"],create:["POST /gists"],createComment:["POST /gists/{gist_id}/comments"],delete:["DELETE /gists/{gist_id}"],deleteComment:["DELETE /gists/{gist_id}/comments/{comment_id}"],fork:["POST /gists/{gist_id}/forks"],get:["GET /gists/{gist_id}"],getComment:["GET /gists/{gist_id}/comments/{comment_id}"],getRevision:["GET /gists/{gist_id}/{sha}"],list:["GET /gists"],listComments:["GET /gists/{gist_id}/comments"],listCommits:["GET /gists/{gist_id}/commits"],listForUser:["GET /users/{username}/gists"],listForks:["GET /gists/{gist_id}/forks"],listPublic:["GET /gists/public"],listStarred:["GET /gists/starred"],star:["PUT /gists/{gist_id}/star"],unstar:["DELETE /gists/{gist_id}/star"],update:["PATCH /gists/{gist_id}"],updateComment:["PATCH /gists/{gist_id}/comments/{comment_id}"]},git:{createBlob:["POST /repos/{owner}/{repo}/git/blobs"],createCommit:["POST /repos/{owner}/{repo}/git/commits"],createRef:["POST /repos/{owner}/{repo}/git/refs"],createTag:["POST /repos/{owner}/{repo}/git/tags"],createTree:["POST /repos/{owner}/{repo}/git/trees"],deleteRef:["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],getBlob:["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],getCommit:["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],getRef:["GET /repos/{owner}/{repo}/git/ref/{ref}"],getTag:["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],getTree:["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],listMatchingRefs:["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],updateRef:["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]},gitignore:{getAllTemplates:["GET /gitignore/templates"],getTemplate:["GET /gitignore/templates/{name}"]},hostedCompute:{createNetworkConfigurationForOrg:["POST /orgs/{org}/settings/network-configurations"],deleteNetworkConfigurationFromOrg:["DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}"],getNetworkConfigurationForOrg:["GET /orgs/{org}/settings/network-configurations/{network_configuration_id}"],getNetworkSettingsForOrg:["GET /orgs/{org}/settings/network-settings/{network_settings_id}"],listNetworkConfigurationsForOrg:["GET /orgs/{org}/settings/network-configurations"],updateNetworkConfigurationForOrg:["PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}"]},interactions:{getRestrictionsForAuthenticatedUser:["GET /user/interaction-limits"],getRestrictionsForOrg:["GET /orgs/{org}/interaction-limits"],getRestrictionsForRepo:["GET /repos/{owner}/{repo}/interaction-limits"],getRestrictionsForYourPublicRepos:["GET /user/interaction-limits",{},{renamed:["interactions","getRestrictionsForAuthenticatedUser"]}],removeRestrictionsForAuthenticatedUser:["DELETE /user/interaction-limits"],removeRestrictionsForOrg:["DELETE /orgs/{org}/interaction-limits"],removeRestrictionsForRepo:["DELETE /repos/{owner}/{repo}/interaction-limits"],removeRestrictionsForYourPublicRepos:["DELETE /user/interaction-limits",{},{renamed:["interactions","removeRestrictionsForAuthenticatedUser"]}],setRestrictionsForAuthenticatedUser:["PUT /user/interaction-limits"],setRestrictionsForOrg:["PUT /orgs/{org}/interaction-limits"],setRestrictionsForRepo:["PUT /repos/{owner}/{repo}/interaction-limits"],setRestrictionsForYourPublicRepos:["PUT /user/interaction-limits",{},{renamed:["interactions","setRestrictionsForAuthenticatedUser"]}]},issues:{addAssignees:["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],addBlockedByDependency:["POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by"],addLabels:["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],addSubIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],checkUserCanBeAssigned:["GET /repos/{owner}/{repo}/assignees/{assignee}"],checkUserCanBeAssignedToIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}"],create:["POST /repos/{owner}/{repo}/issues"],createComment:["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"],createLabel:["POST /repos/{owner}/{repo}/labels"],createMilestone:["POST /repos/{owner}/{repo}/milestones"],deleteComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"],deleteLabel:["DELETE /repos/{owner}/{repo}/labels/{name}"],deleteMilestone:["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"],get:["GET /repos/{owner}/{repo}/issues/{issue_number}"],getComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],getEvent:["GET /repos/{owner}/{repo}/issues/events/{event_id}"],getLabel:["GET /repos/{owner}/{repo}/labels/{name}"],getMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],getParent:["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"],list:["GET /issues"],listAssignees:["GET /repos/{owner}/{repo}/assignees"],listComments:["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],listCommentsForRepo:["GET /repos/{owner}/{repo}/issues/comments"],listDependenciesBlockedBy:["GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by"],listDependenciesBlocking:["GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking"],listEvents:["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],listEventsForRepo:["GET /repos/{owner}/{repo}/issues/events"],listEventsForTimeline:["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"],listForAuthenticatedUser:["GET /user/issues"],listForOrg:["GET /orgs/{org}/issues"],listForRepo:["GET /repos/{owner}/{repo}/issues"],listLabelsForMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"],listLabelsForRepo:["GET /repos/{owner}/{repo}/labels"],listLabelsOnIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"],listMilestones:["GET /repos/{owner}/{repo}/milestones"],listSubIssues:["GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],lock:["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],removeAllLabels:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"],removeAssignees:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"],removeDependencyBlockedBy:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}"],removeLabel:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"],removeSubIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue"],reprioritizeSubIssue:["PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority"],setLabels:["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],unlock:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],update:["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],updateComment:["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],updateLabel:["PATCH /repos/{owner}/{repo}/labels/{name}"],updateMilestone:["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"]},licenses:{get:["GET /licenses/{license}"],getAllCommonlyUsed:["GET /licenses"],getForRepo:["GET /repos/{owner}/{repo}/license"]},markdown:{render:["POST /markdown"],renderRaw:["POST /markdown/raw",{headers:{"content-type":"text/plain; charset=utf-8"}}]},meta:{get:["GET /meta"],getAllVersions:["GET /versions"],getOctocat:["GET /octocat"],getZen:["GET /zen"],root:["GET /"]},migrations:{deleteArchiveForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/archive"],deleteArchiveForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/archive"],downloadArchiveForOrg:["GET /orgs/{org}/migrations/{migration_id}/archive"],getArchiveForAuthenticatedUser:["GET /user/migrations/{migration_id}/archive"],getStatusForAuthenticatedUser:["GET /user/migrations/{migration_id}"],getStatusForOrg:["GET /orgs/{org}/migrations/{migration_id}"],listForAuthenticatedUser:["GET /user/migrations"],listForOrg:["GET /orgs/{org}/migrations"],listReposForAuthenticatedUser:["GET /user/migrations/{migration_id}/repositories"],listReposForOrg:["GET /orgs/{org}/migrations/{migration_id}/repositories"],listReposForUser:["GET /user/migrations/{migration_id}/repositories",{},{renamed:["migrations","listReposForAuthenticatedUser"]}],startForAuthenticatedUser:["POST /user/migrations"],startForOrg:["POST /orgs/{org}/migrations"],unlockRepoForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"],unlockRepoForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"]},oidc:{getOidcCustomSubTemplateForOrg:["GET /orgs/{org}/actions/oidc/customization/sub"],updateOidcCustomSubTemplateForOrg:["PUT /orgs/{org}/actions/oidc/customization/sub"]},orgs:{addSecurityManagerTeam:["PUT /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team"}],assignTeamToOrgRole:["PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],assignUserToOrgRole:["PUT /orgs/{org}/organization-roles/users/{username}/{role_id}"],blockUser:["PUT /orgs/{org}/blocks/{username}"],cancelInvitation:["DELETE /orgs/{org}/invitations/{invitation_id}"],checkBlockedUser:["GET /orgs/{org}/blocks/{username}"],checkMembershipForUser:["GET /orgs/{org}/members/{username}"],checkPublicMembershipForUser:["GET /orgs/{org}/public_members/{username}"],convertMemberToOutsideCollaborator:["PUT /orgs/{org}/outside_collaborators/{username}"],createArtifactStorageRecord:["POST /orgs/{org}/artifacts/metadata/storage-record"],createInvitation:["POST /orgs/{org}/invitations"],createIssueType:["POST /orgs/{org}/issue-types"],createWebhook:["POST /orgs/{org}/hooks"],customPropertiesForOrgsCreateOrUpdateOrganizationValues:["PATCH /organizations/{org}/org-properties/values"],customPropertiesForOrgsGetOrganizationValues:["GET /organizations/{org}/org-properties/values"],customPropertiesForReposCreateOrUpdateOrganizationDefinition:["PUT /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposCreateOrUpdateOrganizationDefinitions:["PATCH /orgs/{org}/properties/schema"],customPropertiesForReposCreateOrUpdateOrganizationValues:["PATCH /orgs/{org}/properties/values"],customPropertiesForReposDeleteOrganizationDefinition:["DELETE /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposGetOrganizationDefinition:["GET /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposGetOrganizationDefinitions:["GET /orgs/{org}/properties/schema"],customPropertiesForReposGetOrganizationValues:["GET /orgs/{org}/properties/values"],delete:["DELETE /orgs/{org}"],deleteAttestationsBulk:["POST /orgs/{org}/attestations/delete-request"],deleteAttestationsById:["DELETE /orgs/{org}/attestations/{attestation_id}"],deleteAttestationsBySubjectDigest:["DELETE /orgs/{org}/attestations/digest/{subject_digest}"],deleteIssueType:["DELETE /orgs/{org}/issue-types/{issue_type_id}"],deleteWebhook:["DELETE /orgs/{org}/hooks/{hook_id}"],disableSelectedRepositoryImmutableReleasesOrganization:["DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}"],enableSelectedRepositoryImmutableReleasesOrganization:["PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}"],get:["GET /orgs/{org}"],getImmutableReleasesSettings:["GET /orgs/{org}/settings/immutable-releases"],getImmutableReleasesSettingsRepositories:["GET /orgs/{org}/settings/immutable-releases/repositories"],getMembershipForAuthenticatedUser:["GET /user/memberships/orgs/{org}"],getMembershipForUser:["GET /orgs/{org}/memberships/{username}"],getOrgRole:["GET /orgs/{org}/organization-roles/{role_id}"],getOrgRulesetHistory:["GET /orgs/{org}/rulesets/{ruleset_id}/history"],getOrgRulesetVersion:["GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}"],getWebhook:["GET /orgs/{org}/hooks/{hook_id}"],getWebhookConfigForOrg:["GET /orgs/{org}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"],list:["GET /organizations"],listAppInstallations:["GET /orgs/{org}/installations"],listArtifactStorageRecords:["GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records"],listAttestationRepositories:["GET /orgs/{org}/attestations/repositories"],listAttestations:["GET /orgs/{org}/attestations/{subject_digest}"],listAttestationsBulk:["POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}"],listBlockedUsers:["GET /orgs/{org}/blocks"],listFailedInvitations:["GET /orgs/{org}/failed_invitations"],listForAuthenticatedUser:["GET /user/orgs"],listForUser:["GET /users/{username}/orgs"],listInvitationTeams:["GET /orgs/{org}/invitations/{invitation_id}/teams"],listIssueTypes:["GET /orgs/{org}/issue-types"],listMembers:["GET /orgs/{org}/members"],listMembershipsForAuthenticatedUser:["GET /user/memberships/orgs"],listOrgRoleTeams:["GET /orgs/{org}/organization-roles/{role_id}/teams"],listOrgRoleUsers:["GET /orgs/{org}/organization-roles/{role_id}/users"],listOrgRoles:["GET /orgs/{org}/organization-roles"],listOrganizationFineGrainedPermissions:["GET /orgs/{org}/organization-fine-grained-permissions"],listOutsideCollaborators:["GET /orgs/{org}/outside_collaborators"],listPatGrantRepositories:["GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories"],listPatGrantRequestRepositories:["GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories"],listPatGrantRequests:["GET /orgs/{org}/personal-access-token-requests"],listPatGrants:["GET /orgs/{org}/personal-access-tokens"],listPendingInvitations:["GET /orgs/{org}/invitations"],listPublicMembers:["GET /orgs/{org}/public_members"],listSecurityManagerTeams:["GET /orgs/{org}/security-managers",{},{deprecated:"octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams"}],listWebhookDeliveries:["GET /orgs/{org}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /orgs/{org}/hooks"],pingWebhook:["POST /orgs/{org}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeMember:["DELETE /orgs/{org}/members/{username}"],removeMembershipForUser:["DELETE /orgs/{org}/memberships/{username}"],removeOutsideCollaborator:["DELETE /orgs/{org}/outside_collaborators/{username}"],removePublicMembershipForAuthenticatedUser:["DELETE /orgs/{org}/public_members/{username}"],removeSecurityManagerTeam:["DELETE /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team"}],reviewPatGrantRequest:["POST /orgs/{org}/personal-access-token-requests/{pat_request_id}"],reviewPatGrantRequestsInBulk:["POST /orgs/{org}/personal-access-token-requests"],revokeAllOrgRolesTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}"],revokeAllOrgRolesUser:["DELETE /orgs/{org}/organization-roles/users/{username}"],revokeOrgRoleTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],revokeOrgRoleUser:["DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}"],setImmutableReleasesSettings:["PUT /orgs/{org}/settings/immutable-releases"],setImmutableReleasesSettingsRepositories:["PUT /orgs/{org}/settings/immutable-releases/repositories"],setMembershipForUser:["PUT /orgs/{org}/memberships/{username}"],setPublicMembershipForAuthenticatedUser:["PUT /orgs/{org}/public_members/{username}"],unblockUser:["DELETE /orgs/{org}/blocks/{username}"],update:["PATCH /orgs/{org}"],updateIssueType:["PUT /orgs/{org}/issue-types/{issue_type_id}"],updateMembershipForAuthenticatedUser:["PATCH /user/memberships/orgs/{org}"],updatePatAccess:["POST /orgs/{org}/personal-access-tokens/{pat_id}"],updatePatAccesses:["POST /orgs/{org}/personal-access-tokens"],updateWebhook:["PATCH /orgs/{org}/hooks/{hook_id}"],updateWebhookConfigForOrg:["PATCH /orgs/{org}/hooks/{hook_id}/config"]},packages:{deletePackageForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}"],deletePackageForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}"],deletePackageForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}"],deletePackageVersionForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getAllPackageVersionsForAPackageOwnedByAnOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByOrg"]}],getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByAuthenticatedUser"]}],getAllPackageVersionsForPackageOwnedByAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions"],getPackageForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}"],getPackageForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}"],getPackageForUser:["GET /users/{username}/packages/{package_type}/{package_name}"],getPackageVersionForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],listDockerMigrationConflictingPackagesForAuthenticatedUser:["GET /user/docker/conflicts"],listDockerMigrationConflictingPackagesForOrganization:["GET /orgs/{org}/docker/conflicts"],listDockerMigrationConflictingPackagesForUser:["GET /users/{username}/docker/conflicts"],listPackagesForAuthenticatedUser:["GET /user/packages"],listPackagesForOrganization:["GET /orgs/{org}/packages"],listPackagesForUser:["GET /users/{username}/packages"],restorePackageForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForUser:["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageVersionForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForUser:["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"]},privateRegistries:{createOrgPrivateRegistry:["POST /orgs/{org}/private-registries"],deleteOrgPrivateRegistry:["DELETE /orgs/{org}/private-registries/{secret_name}"],getOrgPrivateRegistry:["GET /orgs/{org}/private-registries/{secret_name}"],getOrgPublicKey:["GET /orgs/{org}/private-registries/public-key"],listOrgPrivateRegistries:["GET /orgs/{org}/private-registries"],updateOrgPrivateRegistry:["PATCH /orgs/{org}/private-registries/{secret_name}"]},projects:{addItemForOrg:["POST /orgs/{org}/projectsV2/{project_number}/items"],addItemForUser:["POST /users/{username}/projectsV2/{project_number}/items"],deleteItemForOrg:["DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],deleteItemForUser:["DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}"],getFieldForOrg:["GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}"],getFieldForUser:["GET /users/{username}/projectsV2/{project_number}/fields/{field_id}"],getForOrg:["GET /orgs/{org}/projectsV2/{project_number}"],getForUser:["GET /users/{username}/projectsV2/{project_number}"],getOrgItem:["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],getUserItem:["GET /users/{username}/projectsV2/{project_number}/items/{item_id}"],listFieldsForOrg:["GET /orgs/{org}/projectsV2/{project_number}/fields"],listFieldsForUser:["GET /users/{username}/projectsV2/{project_number}/fields"],listForOrg:["GET /orgs/{org}/projectsV2"],listForUser:["GET /users/{username}/projectsV2"],listItemsForOrg:["GET /orgs/{org}/projectsV2/{project_number}/items"],listItemsForUser:["GET /users/{username}/projectsV2/{project_number}/items"],updateItemForOrg:["PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],updateItemForUser:["PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}"]},pulls:{checkIfMerged:["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],create:["POST /repos/{owner}/{repo}/pulls"],createReplyForReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"],createReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],createReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"],deletePendingReview:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],deleteReviewComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"],dismissReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"],get:["GET /repos/{owner}/{repo}/pulls/{pull_number}"],getReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],getReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],list:["GET /repos/{owner}/{repo}/pulls"],listCommentsForReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"],listCommits:["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],listFiles:["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],listRequestedReviewers:["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],listReviewComments:["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"],listReviewCommentsForRepo:["GET /repos/{owner}/{repo}/pulls/comments"],listReviews:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],merge:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],removeRequestedReviewers:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],requestReviewers:["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],submitReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"],update:["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],updateBranch:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"],updateReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],updateReviewComment:["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"]},rateLimit:{get:["GET /rate_limit"]},reactions:{createForCommitComment:["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"],createForIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"],createForIssueComment:["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],createForPullRequestReviewComment:["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],createForRelease:["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"],createForTeamDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],createForTeamDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"],deleteForCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"],deleteForIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"],deleteForIssueComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"],deleteForPullRequestComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"],deleteForRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}"],deleteForTeamDiscussion:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"],deleteForTeamDiscussionComment:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"],listForCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"],listForIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"],listForIssueComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],listForPullRequestReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],listForRelease:["GET /repos/{owner}/{repo}/releases/{release_id}/reactions"],listForTeamDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],listForTeamDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]},repos:{acceptInvitation:["PATCH /user/repository_invitations/{invitation_id}",{},{renamed:["repos","acceptInvitationForAuthenticatedUser"]}],acceptInvitationForAuthenticatedUser:["PATCH /user/repository_invitations/{invitation_id}"],addAppAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],addCollaborator:["PUT /repos/{owner}/{repo}/collaborators/{username}"],addStatusCheckContexts:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],addTeamAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],addUserAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],cancelPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel"],checkAutomatedSecurityFixes:["GET /repos/{owner}/{repo}/automated-security-fixes"],checkCollaborator:["GET /repos/{owner}/{repo}/collaborators/{username}"],checkImmutableReleases:["GET /repos/{owner}/{repo}/immutable-releases"],checkPrivateVulnerabilityReporting:["GET /repos/{owner}/{repo}/private-vulnerability-reporting"],checkVulnerabilityAlerts:["GET /repos/{owner}/{repo}/vulnerability-alerts"],codeownersErrors:["GET /repos/{owner}/{repo}/codeowners/errors"],compareCommits:["GET /repos/{owner}/{repo}/compare/{base}...{head}"],compareCommitsWithBasehead:["GET /repos/{owner}/{repo}/compare/{basehead}"],createAttestation:["POST /repos/{owner}/{repo}/attestations"],createAutolink:["POST /repos/{owner}/{repo}/autolinks"],createCommitComment:["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"],createCommitSignatureProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],createCommitStatus:["POST /repos/{owner}/{repo}/statuses/{sha}"],createDeployKey:["POST /repos/{owner}/{repo}/keys"],createDeployment:["POST /repos/{owner}/{repo}/deployments"],createDeploymentBranchPolicy:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],createDeploymentProtectionRule:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],createDeploymentStatus:["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],createDispatchEvent:["POST /repos/{owner}/{repo}/dispatches"],createForAuthenticatedUser:["POST /user/repos"],createFork:["POST /repos/{owner}/{repo}/forks"],createInOrg:["POST /orgs/{org}/repos"],createOrUpdateEnvironment:["PUT /repos/{owner}/{repo}/environments/{environment_name}"],createOrUpdateFileContents:["PUT /repos/{owner}/{repo}/contents/{path}"],createOrgRuleset:["POST /orgs/{org}/rulesets"],createPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments"],createPagesSite:["POST /repos/{owner}/{repo}/pages"],createRelease:["POST /repos/{owner}/{repo}/releases"],createRepoRuleset:["POST /repos/{owner}/{repo}/rulesets"],createUsingTemplate:["POST /repos/{template_owner}/{template_repo}/generate"],createWebhook:["POST /repos/{owner}/{repo}/hooks"],customPropertiesForReposCreateOrUpdateRepositoryValues:["PATCH /repos/{owner}/{repo}/properties/values"],customPropertiesForReposGetRepositoryValues:["GET /repos/{owner}/{repo}/properties/values"],declineInvitation:["DELETE /user/repository_invitations/{invitation_id}",{},{renamed:["repos","declineInvitationForAuthenticatedUser"]}],declineInvitationForAuthenticatedUser:["DELETE /user/repository_invitations/{invitation_id}"],delete:["DELETE /repos/{owner}/{repo}"],deleteAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],deleteAdminBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],deleteAnEnvironment:["DELETE /repos/{owner}/{repo}/environments/{environment_name}"],deleteAutolink:["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],deleteBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],deleteCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],deleteCommitSignatureProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],deleteDeployKey:["DELETE /repos/{owner}/{repo}/keys/{key_id}"],deleteDeployment:["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"],deleteDeploymentBranchPolicy:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],deleteFile:["DELETE /repos/{owner}/{repo}/contents/{path}"],deleteInvitation:["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"],deleteOrgRuleset:["DELETE /orgs/{org}/rulesets/{ruleset_id}"],deletePagesSite:["DELETE /repos/{owner}/{repo}/pages"],deletePullRequestReviewProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],deleteRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}"],deleteReleaseAsset:["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"],deleteRepoRuleset:["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"],deleteWebhook:["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],disableAutomatedSecurityFixes:["DELETE /repos/{owner}/{repo}/automated-security-fixes"],disableDeploymentProtectionRule:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],disableImmutableReleases:["DELETE /repos/{owner}/{repo}/immutable-releases"],disablePrivateVulnerabilityReporting:["DELETE /repos/{owner}/{repo}/private-vulnerability-reporting"],disableVulnerabilityAlerts:["DELETE /repos/{owner}/{repo}/vulnerability-alerts"],downloadArchive:["GET /repos/{owner}/{repo}/zipball/{ref}",{},{renamed:["repos","downloadZipballArchive"]}],downloadTarballArchive:["GET /repos/{owner}/{repo}/tarball/{ref}"],downloadZipballArchive:["GET /repos/{owner}/{repo}/zipball/{ref}"],enableAutomatedSecurityFixes:["PUT /repos/{owner}/{repo}/automated-security-fixes"],enableImmutableReleases:["PUT /repos/{owner}/{repo}/immutable-releases"],enablePrivateVulnerabilityReporting:["PUT /repos/{owner}/{repo}/private-vulnerability-reporting"],enableVulnerabilityAlerts:["PUT /repos/{owner}/{repo}/vulnerability-alerts"],generateReleaseNotes:["POST /repos/{owner}/{repo}/releases/generate-notes"],get:["GET /repos/{owner}/{repo}"],getAccessRestrictions:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],getAdminBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],getAllDeploymentProtectionRules:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],getAllEnvironments:["GET /repos/{owner}/{repo}/environments"],getAllStatusCheckContexts:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],getAllTopics:["GET /repos/{owner}/{repo}/topics"],getAppsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"],getAutolink:["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],getBranch:["GET /repos/{owner}/{repo}/branches/{branch}"],getBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection"],getBranchRules:["GET /repos/{owner}/{repo}/rules/branches/{branch}"],getClones:["GET /repos/{owner}/{repo}/traffic/clones"],getCodeFrequencyStats:["GET /repos/{owner}/{repo}/stats/code_frequency"],getCollaboratorPermissionLevel:["GET /repos/{owner}/{repo}/collaborators/{username}/permission"],getCombinedStatusForRef:["GET /repos/{owner}/{repo}/commits/{ref}/status"],getCommit:["GET /repos/{owner}/{repo}/commits/{ref}"],getCommitActivityStats:["GET /repos/{owner}/{repo}/stats/commit_activity"],getCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}"],getCommitSignatureProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],getCommunityProfileMetrics:["GET /repos/{owner}/{repo}/community/profile"],getContent:["GET /repos/{owner}/{repo}/contents/{path}"],getContributorsStats:["GET /repos/{owner}/{repo}/stats/contributors"],getCustomDeploymentProtectionRule:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],getDeployKey:["GET /repos/{owner}/{repo}/keys/{key_id}"],getDeployment:["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],getDeploymentBranchPolicy:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],getDeploymentStatus:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],getEnvironment:["GET /repos/{owner}/{repo}/environments/{environment_name}"],getLatestPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/latest"],getLatestRelease:["GET /repos/{owner}/{repo}/releases/latest"],getOrgRuleSuite:["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"],getOrgRuleSuites:["GET /orgs/{org}/rulesets/rule-suites"],getOrgRuleset:["GET /orgs/{org}/rulesets/{ruleset_id}"],getOrgRulesets:["GET /orgs/{org}/rulesets"],getPages:["GET /repos/{owner}/{repo}/pages"],getPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],getPagesDeployment:["GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}"],getPagesHealthCheck:["GET /repos/{owner}/{repo}/pages/health"],getParticipationStats:["GET /repos/{owner}/{repo}/stats/participation"],getPullRequestReviewProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],getPunchCardStats:["GET /repos/{owner}/{repo}/stats/punch_card"],getReadme:["GET /repos/{owner}/{repo}/readme"],getReadmeInDirectory:["GET /repos/{owner}/{repo}/readme/{dir}"],getRelease:["GET /repos/{owner}/{repo}/releases/{release_id}"],getReleaseAsset:["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],getReleaseByTag:["GET /repos/{owner}/{repo}/releases/tags/{tag}"],getRepoRuleSuite:["GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}"],getRepoRuleSuites:["GET /repos/{owner}/{repo}/rulesets/rule-suites"],getRepoRuleset:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"],getRepoRulesetHistory:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history"],getRepoRulesetVersion:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}"],getRepoRulesets:["GET /repos/{owner}/{repo}/rulesets"],getStatusChecksProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],getTeamsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"],getTopPaths:["GET /repos/{owner}/{repo}/traffic/popular/paths"],getTopReferrers:["GET /repos/{owner}/{repo}/traffic/popular/referrers"],getUsersWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"],getViews:["GET /repos/{owner}/{repo}/traffic/views"],getWebhook:["GET /repos/{owner}/{repo}/hooks/{hook_id}"],getWebhookConfigForRepo:["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"],listActivities:["GET /repos/{owner}/{repo}/activity"],listAttestations:["GET /repos/{owner}/{repo}/attestations/{subject_digest}"],listAutolinks:["GET /repos/{owner}/{repo}/autolinks"],listBranches:["GET /repos/{owner}/{repo}/branches"],listBranchesForHeadCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"],listCollaborators:["GET /repos/{owner}/{repo}/collaborators"],listCommentsForCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"],listCommitCommentsForRepo:["GET /repos/{owner}/{repo}/comments"],listCommitStatusesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/statuses"],listCommits:["GET /repos/{owner}/{repo}/commits"],listContributors:["GET /repos/{owner}/{repo}/contributors"],listCustomDeploymentRuleIntegrations:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps"],listDeployKeys:["GET /repos/{owner}/{repo}/keys"],listDeploymentBranchPolicies:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],listDeploymentStatuses:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],listDeployments:["GET /repos/{owner}/{repo}/deployments"],listForAuthenticatedUser:["GET /user/repos"],listForOrg:["GET /orgs/{org}/repos"],listForUser:["GET /users/{username}/repos"],listForks:["GET /repos/{owner}/{repo}/forks"],listInvitations:["GET /repos/{owner}/{repo}/invitations"],listInvitationsForAuthenticatedUser:["GET /user/repository_invitations"],listLanguages:["GET /repos/{owner}/{repo}/languages"],listPagesBuilds:["GET /repos/{owner}/{repo}/pages/builds"],listPublic:["GET /repositories"],listPullRequestsAssociatedWithCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"],listReleaseAssets:["GET /repos/{owner}/{repo}/releases/{release_id}/assets"],listReleases:["GET /repos/{owner}/{repo}/releases"],listTags:["GET /repos/{owner}/{repo}/tags"],listTeams:["GET /repos/{owner}/{repo}/teams"],listWebhookDeliveries:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /repos/{owner}/{repo}/hooks"],merge:["POST /repos/{owner}/{repo}/merges"],mergeUpstream:["POST /repos/{owner}/{repo}/merge-upstream"],pingWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeAppAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],removeCollaborator:["DELETE /repos/{owner}/{repo}/collaborators/{username}"],removeStatusCheckContexts:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],removeStatusCheckProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],removeTeamAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],removeUserAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],renameBranch:["POST /repos/{owner}/{repo}/branches/{branch}/rename"],replaceAllTopics:["PUT /repos/{owner}/{repo}/topics"],requestPagesBuild:["POST /repos/{owner}/{repo}/pages/builds"],setAdminBranchProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],setAppAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],setStatusCheckContexts:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],setTeamAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],setUserAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],testPushWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],transfer:["POST /repos/{owner}/{repo}/transfer"],update:["PATCH /repos/{owner}/{repo}"],updateBranchProtection:["PUT /repos/{owner}/{repo}/branches/{branch}/protection"],updateCommitComment:["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],updateDeploymentBranchPolicy:["PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],updateInformationAboutPagesSite:["PUT /repos/{owner}/{repo}/pages"],updateInvitation:["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"],updateOrgRuleset:["PUT /orgs/{org}/rulesets/{ruleset_id}"],updatePullRequestReviewProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],updateRelease:["PATCH /repos/{owner}/{repo}/releases/{release_id}"],updateReleaseAsset:["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"],updateRepoRuleset:["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"],updateStatusCheckPotection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks",{},{renamed:["repos","updateStatusCheckProtection"]}],updateStatusCheckProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],updateWebhook:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],updateWebhookConfigForRepo:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"],uploadReleaseAsset:["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}",{baseUrl:"https://uploads.github.com"}]},search:{code:["GET /search/code"],commits:["GET /search/commits"],issuesAndPullRequests:["GET /search/issues"],labels:["GET /search/labels"],repos:["GET /search/repositories"],topics:["GET /search/topics"],users:["GET /search/users"]},secretScanning:{createPushProtectionBypass:["POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses"],getAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],getScanHistory:["GET /repos/{owner}/{repo}/secret-scanning/scan-history"],listAlertsForOrg:["GET /orgs/{org}/secret-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/secret-scanning/alerts"],listLocationsForAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"],listOrgPatternConfigs:["GET /orgs/{org}/secret-scanning/pattern-configurations"],updateAlert:["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],updateOrgPatternConfigs:["PATCH /orgs/{org}/secret-scanning/pattern-configurations"]},securityAdvisories:{createFork:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks"],createPrivateVulnerabilityReport:["POST /repos/{owner}/{repo}/security-advisories/reports"],createRepositoryAdvisory:["POST /repos/{owner}/{repo}/security-advisories"],createRepositoryAdvisoryCveRequest:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve"],getGlobalAdvisory:["GET /advisories/{ghsa_id}"],getRepositoryAdvisory:["GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}"],listGlobalAdvisories:["GET /advisories"],listOrgRepositoryAdvisories:["GET /orgs/{org}/security-advisories"],listRepositoryAdvisories:["GET /repos/{owner}/{repo}/security-advisories"],updateRepositoryAdvisory:["PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}"]},teams:{addOrUpdateMembershipForUserInOrg:["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"],addOrUpdateRepoPermissionsInOrg:["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],checkPermissionsForRepoInOrg:["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],create:["POST /orgs/{org}/teams"],createDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],createDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions"],deleteDiscussionCommentInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],deleteDiscussionInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],deleteInOrg:["DELETE /orgs/{org}/teams/{team_slug}"],getByName:["GET /orgs/{org}/teams/{team_slug}"],getDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],getDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],getMembershipForUserInOrg:["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"],list:["GET /orgs/{org}/teams"],listChildInOrg:["GET /orgs/{org}/teams/{team_slug}/teams"],listDiscussionCommentsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],listDiscussionsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions"],listForAuthenticatedUser:["GET /user/teams"],listMembersInOrg:["GET /orgs/{org}/teams/{team_slug}/members"],listPendingInvitationsInOrg:["GET /orgs/{org}/teams/{team_slug}/invitations"],listReposInOrg:["GET /orgs/{org}/teams/{team_slug}/repos"],removeMembershipForUserInOrg:["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"],removeRepoInOrg:["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],updateDiscussionCommentInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],updateDiscussionInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],updateInOrg:["PATCH /orgs/{org}/teams/{team_slug}"]},users:{addEmailForAuthenticated:["POST /user/emails",{},{renamed:["users","addEmailForAuthenticatedUser"]}],addEmailForAuthenticatedUser:["POST /user/emails"],addSocialAccountForAuthenticatedUser:["POST /user/social_accounts"],block:["PUT /user/blocks/{username}"],checkBlocked:["GET /user/blocks/{username}"],checkFollowingForUser:["GET /users/{username}/following/{target_user}"],checkPersonIsFollowedByAuthenticated:["GET /user/following/{username}"],createGpgKeyForAuthenticated:["POST /user/gpg_keys",{},{renamed:["users","createGpgKeyForAuthenticatedUser"]}],createGpgKeyForAuthenticatedUser:["POST /user/gpg_keys"],createPublicSshKeyForAuthenticated:["POST /user/keys",{},{renamed:["users","createPublicSshKeyForAuthenticatedUser"]}],createPublicSshKeyForAuthenticatedUser:["POST /user/keys"],createSshSigningKeyForAuthenticatedUser:["POST /user/ssh_signing_keys"],deleteAttestationsBulk:["POST /users/{username}/attestations/delete-request"],deleteAttestationsById:["DELETE /users/{username}/attestations/{attestation_id}"],deleteAttestationsBySubjectDigest:["DELETE /users/{username}/attestations/digest/{subject_digest}"],deleteEmailForAuthenticated:["DELETE /user/emails",{},{renamed:["users","deleteEmailForAuthenticatedUser"]}],deleteEmailForAuthenticatedUser:["DELETE /user/emails"],deleteGpgKeyForAuthenticated:["DELETE /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","deleteGpgKeyForAuthenticatedUser"]}],deleteGpgKeyForAuthenticatedUser:["DELETE /user/gpg_keys/{gpg_key_id}"],deletePublicSshKeyForAuthenticated:["DELETE /user/keys/{key_id}",{},{renamed:["users","deletePublicSshKeyForAuthenticatedUser"]}],deletePublicSshKeyForAuthenticatedUser:["DELETE /user/keys/{key_id}"],deleteSocialAccountForAuthenticatedUser:["DELETE /user/social_accounts"],deleteSshSigningKeyForAuthenticatedUser:["DELETE /user/ssh_signing_keys/{ssh_signing_key_id}"],follow:["PUT /user/following/{username}"],getAuthenticated:["GET /user"],getById:["GET /user/{account_id}"],getByUsername:["GET /users/{username}"],getContextForUser:["GET /users/{username}/hovercard"],getGpgKeyForAuthenticated:["GET /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","getGpgKeyForAuthenticatedUser"]}],getGpgKeyForAuthenticatedUser:["GET /user/gpg_keys/{gpg_key_id}"],getPublicSshKeyForAuthenticated:["GET /user/keys/{key_id}",{},{renamed:["users","getPublicSshKeyForAuthenticatedUser"]}],getPublicSshKeyForAuthenticatedUser:["GET /user/keys/{key_id}"],getSshSigningKeyForAuthenticatedUser:["GET /user/ssh_signing_keys/{ssh_signing_key_id}"],list:["GET /users"],listAttestations:["GET /users/{username}/attestations/{subject_digest}"],listAttestationsBulk:["POST /users/{username}/attestations/bulk-list{?per_page,before,after}"],listBlockedByAuthenticated:["GET /user/blocks",{},{renamed:["users","listBlockedByAuthenticatedUser"]}],listBlockedByAuthenticatedUser:["GET /user/blocks"],listEmailsForAuthenticated:["GET /user/emails",{},{renamed:["users","listEmailsForAuthenticatedUser"]}],listEmailsForAuthenticatedUser:["GET /user/emails"],listFollowedByAuthenticated:["GET /user/following",{},{renamed:["users","listFollowedByAuthenticatedUser"]}],listFollowedByAuthenticatedUser:["GET /user/following"],listFollowersForAuthenticatedUser:["GET /user/followers"],listFollowersForUser:["GET /users/{username}/followers"],listFollowingForUser:["GET /users/{username}/following"],listGpgKeysForAuthenticated:["GET /user/gpg_keys",{},{renamed:["users","listGpgKeysForAuthenticatedUser"]}],listGpgKeysForAuthenticatedUser:["GET /user/gpg_keys"],listGpgKeysForUser:["GET /users/{username}/gpg_keys"],listPublicEmailsForAuthenticated:["GET /user/public_emails",{},{renamed:["users","listPublicEmailsForAuthenticatedUser"]}],listPublicEmailsForAuthenticatedUser:["GET /user/public_emails"],listPublicKeysForUser:["GET /users/{username}/keys"],listPublicSshKeysForAuthenticated:["GET /user/keys",{},{renamed:["users","listPublicSshKeysForAuthenticatedUser"]}],listPublicSshKeysForAuthenticatedUser:["GET /user/keys"],listSocialAccountsForAuthenticatedUser:["GET /user/social_accounts"],listSocialAccountsForUser:["GET /users/{username}/social_accounts"],listSshSigningKeysForAuthenticatedUser:["GET /user/ssh_signing_keys"],listSshSigningKeysForUser:["GET /users/{username}/ssh_signing_keys"],setPrimaryEmailVisibilityForAuthenticated:["PATCH /user/email/visibility",{},{renamed:["users","setPrimaryEmailVisibilityForAuthenticatedUser"]}],setPrimaryEmailVisibilityForAuthenticatedUser:["PATCH /user/email/visibility"],unblock:["DELETE /user/blocks/{username}"],unfollow:["DELETE /user/following/{username}"],updateAuthenticated:["PATCH /user"]}},l$=w1});function n_(e){let t={};for(let r of no.keys())t[r]=new Proxy({octokit:e,scope:r,cache:{}},R1);return t}function S1(e,t,r,n,s){let o=e.request.defaults(n);function i(...a){let c=o.endpoint.merge(...a);if(s.mapToData)return c=Object.assign({},c,{data:c[s.mapToData],[s.mapToData]:void 0}),o(c);if(s.renamed){let[u,d]=s.renamed;e.log.warn(`octokit.${t}.${r}() has been renamed to octokit.${u}.${d}()`)}if(s.deprecated&&e.log.warn(s.deprecated),s.renamedParameters){let u=o.endpoint.merge(...a);for(let[d,p]of Object.entries(s.renamedParameters))d in u&&(e.log.warn(`"${d}" parameter is deprecated for "octokit.${t}.${r}()". Use "${p}" instead`),p in u||(u[p]=u[d]),delete u[d]);return o(u)}return o(...a)}return Object.assign(i,o)}var no,R1,p$=A(()=>{d$();no=new Map;for(let[e,t]of Object.entries(l$))for(let[r,n]of Object.entries(t)){let[s,o,i]=n,[a,c]=s.split(/ /),u=Object.assign({method:a,url:c},o);no.has(e)||no.set(e,new Map),no.get(e).set(r,{scope:e,methodName:r,endpointDefaults:u,decorations:i})}R1={has({scope:e},t){return no.get(e).has(t)},getOwnPropertyDescriptor(e,t){return{value:this.get(e,t),configurable:!0,writable:!0,enumerable:!0}},defineProperty(e,t,r){return Object.defineProperty(e.cache,t,r),!0},deleteProperty(e,t){return delete e.cache[t],!0},ownKeys({scope:e}){return[...no.get(e).keys()]},set(e,t,r){return e.cache[t]=r},get({octokit:e,scope:t,cache:r},n){if(r[n])return r[n];let s=no.get(t).get(n);if(!s)return;let{endpointDefaults:o,decorations:i}=s;return i?r[n]=S1(e,t,n,o,i):r[n]=e.request.defaults(o),r[n]}}});function _1(e){return{rest:n_(e)}}function s_(e){let t=n_(e);return{...t,rest:t}}var m$=A(()=>{u$();p$();_1.VERSION=r_;s_.VERSION=r_});var f$,g$=A(()=>{f$="22.0.1"});var hm,o_=A(()=>{r$();o$();c$();m$();g$();hm=gm.plugin(XS,s_,t_).defaults({userAgent:`octokit-rest.js/${f$}`})});var c_=bC((i_,a_)=>{(function(e,t){typeof i_=="object"&&typeof a_<"u"?a_.exports=t():typeof define=="function"&&define.amd?define(t):e.Bottleneck=t()})(i_,(function(){"use strict";var e=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function t(Q){return Q&&Q.default||Q}var r=function(Q,x,_={}){var D,F,N;for(D in x)N=x[D],_[D]=(F=Q[D])!=null?F:N;return _},n=function(Q,x,_={}){var D,F;for(D in Q)F=Q[D],x[D]!==void 0&&(_[D]=F);return _},s={load:r,overwrite:n},o;o=class{constructor(x,_){this.incr=x,this.decr=_,this._first=null,this._last=null,this.length=0}push(x){var _;this.length++,typeof this.incr=="function"&&this.incr(),_={value:x,prev:this._last,next:null},this._last!=null?(this._last.next=_,this._last=_):this._first=this._last=_}shift(){var x;if(this._first!=null)return this.length--,typeof this.decr=="function"&&this.decr(),x=this._first.value,(this._first=this._first.next)!=null?this._first.prev=null:this._last=null,x}first(){if(this._first!=null)return this._first.value}getArray(){var x,_,D;for(x=this._first,D=[];x!=null;)D.push((_=x,x=x.next,_.value));return D}forEachShift(x){var _;for(_=this.shift();_!=null;)x(_),_=this.shift()}debug(){var x,_,D,F,N;for(x=this._first,N=[];x!=null;)N.push((_=x,x=x.next,{value:_.value,prev:(D=_.prev)!=null?D.value:void 0,next:(F=_.next)!=null?F.value:void 0}));return N}};var i=o,a;a=class{constructor(x){if(this.instance=x,this._events={},this.instance.on!=null||this.instance.once!=null||this.instance.removeAllListeners!=null)throw new Error("An Emitter already exists for this object");this.instance.on=(_,D)=>this._addListener(_,"many",D),this.instance.once=(_,D)=>this._addListener(_,"once",D),this.instance.removeAllListeners=(_=null)=>_!=null?delete this._events[_]:this._events={}}_addListener(x,_,D){var F;return(F=this._events)[x]==null&&(F[x]=[]),this._events[x].push({cb:D,status:_}),this.instance}listenerCount(x){return this._events[x]!=null?this._events[x].length:0}async trigger(x,..._){var D,F;try{return x!=="debug"&&this.trigger("debug",`Event triggered: ${x}`,_),this._events[x]==null?void 0:(this._events[x]=this._events[x].filter(function(N){return N.status!=="none"}),F=this._events[x].map(async N=>{var z,J;if(N.status!=="none"){N.status==="once"&&(N.status="none");try{return J=typeof N.cb=="function"?N.cb(..._):void 0,typeof J?.then=="function"?await J:J}catch(De){return z=De,this.trigger("error",z),null}}}),(await Promise.all(F)).find(function(N){return N!=null}))}catch(N){return D=N,this.trigger("error",D),null}}};var c=a,u,d,p;u=i,d=c,p=class{constructor(x){var _;this.Events=new d(this),this._length=0,this._lists=(function(){var D,F,N;for(N=[],_=D=1,F=x;1<=F?D<=F:D>=F;_=1<=F?++D:--D)N.push(new u((()=>this.incr()),(()=>this.decr())));return N}).call(this)}incr(){if(this._length++===0)return this.Events.trigger("leftzero")}decr(){if(--this._length===0)return this.Events.trigger("zero")}push(x){return this._lists[x.options.priority].push(x)}queued(x){return x!=null?this._lists[x].length:this._length}shiftAll(x){return this._lists.forEach(function(_){return _.forEachShift(x)})}getFirst(x=this._lists){var _,D,F;for(_=0,D=x.length;_<D;_++)if(F=x[_],F.length>0)return F;return[]}shiftLastFrom(x){return this.getFirst(this._lists.slice(x).reverse()).shift()}};var m=p,f;f=class extends Error{};var g=f,h,b,w,y,S;y=10,b=5,S=s,h=g,w=class{constructor(x,_,D,F,N,z,J,De){this.task=x,this.args=_,this.rejectOnDrop=N,this.Events=z,this._states=J,this.Promise=De,this.options=S.load(D,F),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===F.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise((Rt,At)=>{this._resolve=Rt,this._reject=At}),this.retryCount=0}_sanitizePriority(x){var _;return _=~~x!==x?b:x,_<0?0:_>y-1?y-1:_}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:x,message:_="This job has been dropped by Bottleneck"}={}){return this._states.remove(this.options.id)?(this.rejectOnDrop&&this._reject(x??new h(_)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0):!1}_assertStatus(x){var _;if(_=this._states.jobStatus(this.options.id),!(_===x||x==="DONE"&&_===null))throw new h(`Invalid job status ${_}, expected ${x}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`)}doReceive(){return this._states.start(this.options.id),this.Events.trigger("received",{args:this.args,options:this.options})}doQueue(x,_){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:x,blocked:_})}doRun(){return this.retryCount===0?(this._assertStatus("QUEUED"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),this.Events.trigger("scheduled",{args:this.args,options:this.options})}async doExecute(x,_,D,F){var N,z,J;this.retryCount===0?(this._assertStatus("RUNNING"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),z={args:this.args,options:this.options,retryCount:this.retryCount},this.Events.trigger("executing",z);try{if(J=await(x!=null?x.schedule(this.options,this.task,...this.args):this.task(...this.args)),_())return this.doDone(z),await F(this.options,z),this._assertStatus("DONE"),this._resolve(J)}catch(De){return N=De,this._onFailure(N,z,_,D,F)}}doExpire(x,_,D){var F,N;return this._states.jobStatus(this.options.id==="RUNNING")&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),N={args:this.args,options:this.options,retryCount:this.retryCount},F=new h(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(F,N,x,_,D)}async _onFailure(x,_,D,F,N){var z,J;if(D())return z=await this.Events.trigger("failed",x,_),z!=null?(J=~~z,this.Events.trigger("retry",`Retrying ${this.options.id} after ${J} ms`,_),this.retryCount++,F(J)):(this.doDone(_),await N(this.options,_),this._assertStatus("DONE"),this._reject(x))}doDone(x){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",x)}};var k=w,R,P,C;C=s,R=g,P=class{constructor(x,_,D){this.instance=x,this.storeOptions=_,this.clientId=this.instance._randomIndex(),C.load(D,D,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var x;return this.heartbeat==null&&(this.storeOptions.reservoirRefreshInterval!=null&&this.storeOptions.reservoirRefreshAmount!=null||this.storeOptions.reservoirIncreaseInterval!=null&&this.storeOptions.reservoirIncreaseAmount!=null)?typeof(x=this.heartbeat=setInterval(()=>{var _,D,F,N,z;if(N=Date.now(),this.storeOptions.reservoirRefreshInterval!=null&&N>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=N,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),this.storeOptions.reservoirIncreaseInterval!=null&&N>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval&&({reservoirIncreaseAmount:_,reservoirIncreaseMaximum:F,reservoir:z}=this.storeOptions,this._lastReservoirIncrease=N,D=F!=null?Math.min(_,F-z):_,D>0))return this.storeOptions.reservoir+=D,this.instance._drainAll(this.computeCapacity())},this.heartbeatInterval)).unref=="function"?x.unref():void 0:clearInterval(this.heartbeat)}async __publish__(x){return await this.yieldLoop(),this.instance.Events.trigger("message",x.toString())}async __disconnect__(x){return await this.yieldLoop(),clearInterval(this.heartbeat),this.Promise.resolve()}yieldLoop(x=0){return new this.Promise(function(_,D){return setTimeout(_,x)})}computePenalty(){var x;return(x=this.storeOptions.penalty)!=null?x:15*this.storeOptions.minTime||5e3}async __updateSettings__(x){return await this.yieldLoop(),C.overwrite(x,x,this.storeOptions),this._startHeartbeat(),this.instance._drainAll(this.computeCapacity()),!0}async __running__(){return await this.yieldLoop(),this._running}async __queued__(){return await this.yieldLoop(),this.instance.queued()}async __done__(){return await this.yieldLoop(),this._done}async __groupCheck__(x){return await this.yieldLoop(),this._nextRequest+this.timeout<x}computeCapacity(){var x,_;return{maxConcurrent:x,reservoir:_}=this.storeOptions,x!=null&&_!=null?Math.min(x-this._running,_):x!=null?x-this._running:_??null}conditionsCheck(x){var _;return _=this.computeCapacity(),_==null||x<=_}async __incrementReservoir__(x){var _;return await this.yieldLoop(),_=this.storeOptions.reservoir+=x,this.instance._drainAll(this.computeCapacity()),_}async __currentReservoir__(){return await this.yieldLoop(),this.storeOptions.reservoir}isBlocked(x){return this._unblockTime>=x}check(x,_){return this.conditionsCheck(x)&&this._nextRequest-_<=0}async __check__(x){var _;return await this.yieldLoop(),_=Date.now(),this.check(x,_)}async __register__(x,_,D){var F,N;return await this.yieldLoop(),F=Date.now(),this.conditionsCheck(_)?(this._running+=_,this.storeOptions.reservoir!=null&&(this.storeOptions.reservoir-=_),N=Math.max(this._nextRequest-F,0),this._nextRequest=F+N+this.storeOptions.minTime,{success:!0,wait:N,reservoir:this.storeOptions.reservoir}):{success:!1}}strategyIsBlock(){return this.storeOptions.strategy===3}async __submit__(x,_){var D,F,N;if(await this.yieldLoop(),this.storeOptions.maxConcurrent!=null&&_>this.storeOptions.maxConcurrent)throw new R(`Impossible to add a job having a weight of ${_} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`);return F=Date.now(),N=this.storeOptions.highWater!=null&&x===this.storeOptions.highWater&&!this.check(_,F),D=this.strategyIsBlock()&&(N||this.isBlocked(F)),D&&(this._unblockTime=F+this.computePenalty(),this._nextRequest=this._unblockTime+this.storeOptions.minTime,this.instance._dropAllQueued()),{reachedHWM:N,blocked:D,strategy:this.storeOptions.strategy}}async __free__(x,_){return await this.yieldLoop(),this._running-=_,this._done+=_,this.instance._drainAll(this.computeCapacity()),{running:this._running}}};var E=P,T,M;T=g,M=class{constructor(x){this.status=x,this._jobs={},this.counts=this.status.map(function(){return 0})}next(x){var _,D;if(_=this._jobs[x],D=_+1,_!=null&&D<this.status.length)return this.counts[_]--,this.counts[D]++,this._jobs[x]++;if(_!=null)return this.counts[_]--,delete this._jobs[x]}start(x){var _;return _=0,this._jobs[x]=_,this.counts[_]++}remove(x){var _;return _=this._jobs[x],_!=null&&(this.counts[_]--,delete this._jobs[x]),_!=null}jobStatus(x){var _;return(_=this.status[this._jobs[x]])!=null?_:null}statusJobs(x){var _,D,F,N,z;if(x!=null){if(D=this.status.indexOf(x),D<0)throw new T(`status must be one of ${this.status.join(", ")}`);F=this._jobs,N=[];for(_ in F)z=F[_],z===D&&N.push(_);return N}else return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce(((x,_,D)=>(x[this.status[D]]=_,x)),{})}};var G=M,X,ve;X=i,ve=class{constructor(x,_){this.schedule=this.schedule.bind(this),this.name=x,this.Promise=_,this._running=0,this._queue=new X}isEmpty(){return this._queue.length===0}async _tryToRun(){var x,_,D,F,N,z,J;if(this._running<1&&this._queue.length>0)return this._running++,{task:J,args:x,resolve:N,reject:F}=this._queue.shift(),_=await(async function(){try{return z=await J(...x),function(){return N(z)}}catch(De){return D=De,function(){return F(D)}}})(),this._running--,this._tryToRun(),_()}schedule(x,..._){var D,F,N;return N=F=null,D=new this.Promise(function(z,J){return N=z,F=J}),this._queue.push({task:x,args:_,resolve:N,reject:F}),this._tryToRun(),D}};var he=ve,oe="2.19.5",Z={version:oe},$e=Object.freeze({version:oe,default:Z}),Re=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Xe=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Ke=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),tt,ct,sr,et,Je,Fr;Fr=s,tt=c,et=Re,sr=Xe,Je=Ke,ct=(function(){class Q{constructor(_={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=_,Fr.load(this.limiterOptions,this.defaults,this),this.Events=new tt(this),this.instances={},this.Bottleneck=hC,this._startAutoCleanup(),this.sharedConnection=this.connection!=null,this.connection==null&&(this.limiterOptions.datastore==="redis"?this.connection=new et(Object.assign({},this.limiterOptions,{Events:this.Events})):this.limiterOptions.datastore==="ioredis"&&(this.connection=new sr(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(_=""){var D;return(D=this.instances[_])!=null?D:(()=>{var F;return F=this.instances[_]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${_}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",F,_),F})()}async deleteKey(_=""){var D,F;return F=this.instances[_],this.connection&&(D=await this.connection.__runCommand__(["del",...Je.allKeys(`${this.id}-${_}`)])),F!=null&&(delete this.instances[_],await F.disconnect()),F!=null||D>0}limiters(){var _,D,F,N;D=this.instances,F=[];for(_ in D)N=D[_],F.push({key:_,limiter:N});return F}keys(){return Object.keys(this.instances)}async clusterKeys(){var _,D,F,N,z,J,De,Rt,At;if(this.connection==null)return this.Promise.resolve(this.keys());for(J=[],_=null,At=`b_${this.id}-`.length,D=9;_!==0;)for([Rt,F]=await this.connection.__runCommand__(["scan",_??0,"match",`b_${this.id}-*_settings`,"count",1e4]),_=~~Rt,N=0,De=F.length;N<De;N++)z=F[N],J.push(z.slice(At,-D));return J}_startAutoCleanup(){var _;return clearInterval(this.interval),typeof(_=this.interval=setInterval(async()=>{var D,F,N,z,J,De;J=Date.now(),N=this.instances,z=[];for(F in N){De=N[F];try{await De._store.__groupCheck__(J)?z.push(this.deleteKey(F)):z.push(void 0)}catch(Rt){D=Rt,z.push(De.Events.trigger("error",D))}}return z},this.timeout/2)).unref=="function"?_.unref():void 0}updateSettings(_={}){if(Fr.overwrite(_,this.defaults,this),Fr.overwrite(_,_,this.limiterOptions),_.timeout!=null)return this._startAutoCleanup()}disconnect(_=!0){var D;if(!this.sharedConnection)return(D=this.connection)!=null?D.disconnect(_):void 0}}return Q.prototype.defaults={timeout:1e3*60*5,connection:null,Promise,id:"group-key"},Q}).call(e);var Ps=ct,Es,Fn,Wo;Wo=s,Fn=c,Es=(function(){class Q{constructor(_={}){this.options=_,Wo.load(this.options,this.defaults,this),this.Events=new Fn(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise((_,D)=>this._resolve=_)}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(_){var D;return this._arr.push(_),D=this._promise,this._arr.length===this.maxSize?this._flush():this.maxTime!=null&&this._arr.length===1&&(this._timeout=setTimeout(()=>this._flush(),this.maxTime)),D}}return Q.prototype.defaults={maxTime:null,maxSize:null,Promise},Q}).call(e);var Vo=Es,qo=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),K=t($e),He,Wt,qe,xt,yr,Et,Xa,un,fC,xg,Nr,gC=[].splice;Et=10,Wt=5,Nr=s,Xa=m,xt=k,yr=E,un=qo,qe=c,fC=G,xg=he,He=(function(){class Q{constructor(_={},...D){var F,N;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(_,D),Nr.load(_,this.instanceDefaults,this),this._queues=new Xa(Et),this._scheduled={},this._states=new fC(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new qe(this),this._submitLock=new xg("submit",this.Promise),this._registerLock=new xg("register",this.Promise),N=Nr.load(_,this.storeDefaults,{}),this._store=(function(){if(this.datastore==="redis"||this.datastore==="ioredis"||this.connection!=null)return F=Nr.load(_,this.redisStoreDefaults,{}),new un(this,N,F);if(this.datastore==="local")return F=Nr.load(_,this.localStoreDefaults,{}),new yr(this,N,F);throw new Q.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}).call(this),this._queues.on("leftzero",()=>{var z;return(z=this._store.heartbeat)!=null&&typeof z.ref=="function"?z.ref():void 0}),this._queues.on("zero",()=>{var z;return(z=this._store.heartbeat)!=null&&typeof z.unref=="function"?z.unref():void 0})}_validateOptions(_,D){if(!(_!=null&&typeof _=="object"&&D.length===0))throw new Q.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(_){return this._store.__publish__(_)}disconnect(_=!0){return this._store.__disconnect__(_)}chain(_){return this._limiter=_,this}queued(_){return this._queues.queued(_)}clusterQueued(){return this._store.__queued__()}empty(){return this.queued()===0&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(_){return this._states.jobStatus(_)}jobs(_){return this._states.statusJobs(_)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(_=1){return this._store.__check__(_)}_clearGlobalState(_){return this._scheduled[_]!=null?(clearTimeout(this._scheduled[_].expiration),delete this._scheduled[_],!0):!1}async _free(_,D,F,N){var z,J;try{if({running:J}=await this._store.__free__(_,F.weight),this.Events.trigger("debug",`Freed ${F.id}`,N),J===0&&this.empty())return this.Events.trigger("idle")}catch(De){return z=De,this.Events.trigger("error",z)}}_run(_,D,F){var N,z,J;return D.doRun(),N=this._clearGlobalState.bind(this,_),J=this._run.bind(this,_,D),z=this._free.bind(this,_,D),this._scheduled[_]={timeout:setTimeout(()=>D.doExecute(this._limiter,N,J,z),F),expiration:D.options.expiration!=null?setTimeout(function(){return D.doExpire(N,J,z)},F+D.options.expiration):void 0,job:D}}_drainOne(_){return this._registerLock.schedule(()=>{var D,F,N,z,J;return this.queued()===0?this.Promise.resolve(null):(J=this._queues.getFirst(),{options:z,args:D}=N=J.first(),_!=null&&z.weight>_?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${z.id}`,{args:D,options:z}),F=this._randomIndex(),this._store.__register__(F,z.weight,z.expiration).then(({success:De,wait:Rt,reservoir:At})=>{var ec;return this.Events.trigger("debug",`Drained ${z.id}`,{success:De,args:D,options:z}),De?(J.shift(),ec=this.empty(),ec&&this.Events.trigger("empty"),At===0&&this.Events.trigger("depleted",ec),this._run(F,N,Rt),this.Promise.resolve(z.weight)):this.Promise.resolve(null)})))})}_drainAll(_,D=0){return this._drainOne(_).then(F=>{var N;return F!=null?(N=_!=null?_-F:_,this._drainAll(N,D+F)):this.Promise.resolve(D)}).catch(F=>this.Events.trigger("error",F))}_dropAllQueued(_){return this._queues.shiftAll(function(D){return D.doDrop({message:_})})}stop(_={}){var D,F;return _=Nr.load(_,this.stopDefaults),F=N=>{var z;return z=()=>{var J;return J=this._states.counts,J[0]+J[1]+J[2]+J[3]===N},new this.Promise((J,De)=>z()?J():this.on("done",()=>{if(z())return this.removeAllListeners("done"),J()}))},D=_.dropWaitingJobs?(this._run=function(N,z){return z.doDrop({message:_.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var N,z,J;z=this._scheduled;for(N in z)J=z[N],this.jobStatus(J.job.options.id)==="RUNNING"&&(clearTimeout(J.timeout),clearTimeout(J.expiration),J.job.doDrop({message:_.dropErrorMessage}));return this._dropAllQueued(_.dropErrorMessage),F(0)}))):this.schedule({priority:Et-1,weight:0},()=>F(1)),this._receive=function(N){return N._reject(new Q.prototype.BottleneckError(_.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new Q.prototype.BottleneckError("stop() has already been called")),D}async _addToQueue(_){var D,F,N,z,J,De,Rt;({args:D,options:z}=_);try{({reachedHWM:J,blocked:F,strategy:Rt}=await this._store.__submit__(this.queued(),z.weight))}catch(At){return N=At,this.Events.trigger("debug",`Could not queue ${z.id}`,{args:D,options:z,error:N}),_.doDrop({error:N}),!1}return F?(_.doDrop(),!0):J&&(De=Rt===Q.prototype.strategy.LEAK?this._queues.shiftLastFrom(z.priority):Rt===Q.prototype.strategy.OVERFLOW_PRIORITY?this._queues.shiftLastFrom(z.priority+1):Rt===Q.prototype.strategy.OVERFLOW?_:void 0,De?.doDrop(),De==null||Rt===Q.prototype.strategy.OVERFLOW)?(De==null&&_.doDrop(),J):(_.doQueue(J,F),this._queues.push(_),await this._drainAll(),J)}_receive(_){return this._states.jobStatus(_.options.id)!=null?(_._reject(new Q.prototype.BottleneckError(`A job with the same id already exists (id=${_.options.id})`)),!1):(_.doReceive(),this._submitLock.schedule(this._addToQueue,_))}submit(..._){var D,F,N,z,J,De,Rt;return typeof _[0]=="function"?(J=_,[F,..._]=J,[D]=gC.call(_,-1),z=Nr.load({},this.jobDefaults)):(De=_,[z,F,..._]=De,[D]=gC.call(_,-1),z=Nr.load(z,this.jobDefaults)),Rt=(...At)=>new this.Promise(function(ec,TF){return F(...At,function(...yC){return(yC[0]!=null?TF:ec)(yC)})}),N=new xt(Rt,_,z,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),N.promise.then(function(At){return typeof D=="function"?D(...At):void 0}).catch(function(At){return Array.isArray(At)?typeof D=="function"?D(...At):void 0:typeof D=="function"?D(At):void 0}),this._receive(N)}schedule(..._){var D,F,N;return typeof _[0]=="function"?([N,..._]=_,F={}):[F,N,..._]=_,D=new xt(N,_,F,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(D),D.promise}wrap(_){var D,F;return D=this.schedule.bind(this),F=function(...N){return D(_.bind(this),...N)},F.withOptions=function(N,...z){return D(N,_,...z)},F}async updateSettings(_={}){return await this._store.__updateSettings__(Nr.overwrite(_,this.storeDefaults)),Nr.overwrite(_,this.instanceDefaults,this),this}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(_=0){return this._store.__incrementReservoir__(_)}}return Q.default=Q,Q.Events=qe,Q.version=Q.prototype.version=K.version,Q.strategy=Q.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},Q.BottleneckError=Q.prototype.BottleneckError=g,Q.Group=Q.prototype.Group=Ps,Q.RedisConnection=Q.prototype.RedisConnection=Re,Q.IORedisConnection=Q.prototype.IORedisConnection=Xe,Q.Batcher=Q.prototype.Batcher=Vo,Q.prototype.jobDefaults={priority:Wt,weight:1,expiration:null,id:"<no-id>"},Q.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:Q.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},Q.prototype.localStoreDefaults={Promise,timeout:null,heartbeatInterval:250},Q.prototype.redisStoreDefaults={Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},Q.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise},Q.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},Q}).call(e);var hC=He,AF=hC;return AF}))});function k1(e,t,r){return e.retryLimiter.schedule(C1,e,t,r)}async function C1(e,t,r){let{pathname:n}=new URL(r.url,"http://github.test"),s=P1(r.method,n),o=!s&&r.method!=="GET"&&r.method!=="HEAD",i=r.method==="GET"&&n.startsWith("/search/"),a=n.startsWith("/graphql"),u=~~t.retryCount>0?{priority:0,weight:0}:{};e.clustering&&(u.expiration=1e3*60),(o||a)&&await e.write.key(e.id).schedule(u,u_),o&&e.triggersNotification(n)&&await e.notifications.key(e.id).schedule(u,u_),i&&await e.search.key(e.id).schedule(u,u_);let d=(s?e.auth:e.global).key(e.id).schedule(u,t,r);if(a){let p=await d;if(p.data.errors!=null&&p.data.errors.some(m=>m.type==="RATE_LIMITED"))throw Object.assign(new Error("GraphQL Rate Limit Exceeded"),{response:p,data:p.data})}return d}function P1(e,t){return e==="PATCH"&&/^\/applications\/[^/]+\/token\/scoped$/.test(t)||e==="POST"&&(/^\/applications\/[^/]+\/token$/.test(t)||/^\/app\/installations\/[^/]+\/access_tokens$/.test(t)||t==="/login/oauth/access_token")}function A1(e){let r=`^(?:${e.map(n=>n.split("/").map(s=>s.startsWith("{")?"(?:.+?)":s).join("/")).map(n=>`(?:${n})`).join("|")})[^/]*$`;return new RegExp(r,"i")}function Xi(e,t){let{enabled:r=!0,Bottleneck:n=y$.default,id:s="no-id",timeout:o=1e3*60*2,connection:i}=t.throttle||{};if(!r)return{};let a={timeout:o};typeof i<"u"&&(a.connection=i);let c=Object.assign({clustering:i!=null,triggersNotification:b$,fallbackSecondaryRateRetryAfter:60,retryAfterBaseValue:1e3,id:s},t.throttle);if(typeof c.onSecondaryRateLimit!="function"||typeof c.onRateLimit!="function")throw new Error(`octokit/plugin-throttling error:
69
69
  You must pass the onSecondaryRateLimit and onRateLimit error handlers.
70
70
  See https://octokit.github.io/rest.js/#throttling
71
71
 
@@ -75,7 +75,7 @@ Could not preserve the rejected content; do not push without inspecting the Gist
75
75
  onRateLimit: (retryAfter, options) => {/* ... */}
76
76
  }
77
77
  })
78
- `);let u=!1,d=()=>{if(u)return;u=!0,Ir.global==null&&T1(n,a),c.global=c.global??Ir.global,c.auth=c.auth??Ir.auth,c.search=c.search??Ir.search,c.write=c.write??Ir.write,c.notifications=c.notifications??Ir.notifications,c.retryLimiter=c.retryLimiter??new n;let p={},m=new n.Events(p);p.on("secondary-limit",c.onSecondaryRateLimit),p.on("rate-limit",c.onRateLimit),p.on("error",f=>e.log.warn("Error in throttling-plugin limit handler",f)),c.retryLimiter.on("failed",async function(f,g){let[h,b,w]=g.args,{pathname:y}=new URL(w.url,"http://github.test");if(!(y.startsWith("/graphql")&&f.status!==401||f.status===403||f.status===429))return;let k=~~b.retryCount;b.retryCount=k,w.request.retryCount=k;let{wantRetry:R,retryAfter:P=0}=await(async function(){if(/\bsecondary rate\b/i.test(f.message)){let C=Number(f.response.headers["retry-after"])||h.fallbackSecondaryRateRetryAfter;return{wantRetry:await m.trigger("secondary-limit",C,w,e,k),retryAfter:C}}if(f.response.headers!=null&&f.response.headers["x-ratelimit-remaining"]==="0"||(f.response.data?.errors??[]).some(C=>C.type==="RATE_LIMITED")){let C=new Date(~~f.response.headers["x-ratelimit-reset"]*1e3).getTime(),E=Math.max(Math.ceil((C-Date.now())/1e3)+1,0);return{wantRetry:await m.trigger("rate-limit",E,w,e,k),retryAfter:E}}return{}})();if(R)return b.retryCount++,P*h.retryAfterBaseValue})};return e.hook.wrap("request",(p,m)=>(d(),k1(c,p,m))),{}}var y$,v1,u_,E1,h$,b$,Ir,T1,l_=A(()=>{y$=B(c_(),1),v1="0.0.0-development",u_=()=>Promise.resolve();E1=["/orgs/{org}/invitations","/orgs/{org}/invitations/{invitation_id}","/orgs/{org}/teams/{team_slug}/discussions","/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments","/repos/{owner}/{repo}/collaborators/{username}","/repos/{owner}/{repo}/commits/{commit_sha}/comments","/repos/{owner}/{repo}/issues","/repos/{owner}/{repo}/issues/{issue_number}/comments","/repos/{owner}/{repo}/issues/{issue_number}/sub_issue","/repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority","/repos/{owner}/{repo}/pulls","/repos/{owner}/{repo}/pulls/{pull_number}/comments","/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies","/repos/{owner}/{repo}/pulls/{pull_number}/merge","/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers","/repos/{owner}/{repo}/pulls/{pull_number}/reviews","/repos/{owner}/{repo}/releases","/teams/{team_id}/discussions","/teams/{team_id}/discussions/{discussion_number}/comments"];h$=A1(E1),b$=h$.test.bind(h$),Ir={},T1=function(e,t){Ir.global=new e.Group({id:"octokit-global",maxConcurrent:10,...t}),Ir.auth=new e.Group({id:"octokit-auth",maxConcurrent:1,...t}),Ir.search=new e.Group({id:"octokit-search",maxConcurrent:1,minTime:2e3,...t}),Ir.write=new e.Group({id:"octokit-write",maxConcurrent:1,minTime:1e3,...t}),Ir.notifications=new e.Group({id:"octokit-notifications",maxConcurrent:1,minTime:3e3,...t})};Xi.VERSION=v1;Xi.triggersNotification=b$});function O1(e){return e.request!==void 0}async function w$(e,t,r,n){if(!O1(r)||!r?.request.request)throw r;if(r.status>=400&&!e.doNotRetry.includes(r.status)){let s=n.request.retries!=null?n.request.retries:e.retries,o=Math.pow((n.request.retryCount||0)+1,2);throw t.retry.retryRequest(r,s,o)}throw r}async function I1(e,t,r,n){let s=new R$.default;return s.on("failed",function(o,i){let a=~~o.request.request?.retries,c=~~o.request.request?.retryAfter;if(n.request.retryCount=i.retryCount+1,a>i.retryCount)return c*e.retryAfterBaseValue}),s.schedule(x1.bind(null,e,t,r),n)}async function x1(e,t,r,n){let s=await r(n);if(s.data&&s.data.errors&&s.data.errors.length>0&&/Something went wrong while executing your query/.test(s.data.errors[0].message)){let o=new Rn(s.data.errors[0].message,500,{request:n,response:s});return w$(e,t,o,n)}return s}function wu(e,t){let r=Object.assign({enabled:!0,retryAfterBaseValue:1e3,doNotRetry:[400,401,403,404,410,422,451],retries:3},t.retry),n={retry:{retryRequest:(s,o,i)=>(s.request.request=Object.assign({},s.request.request,{retries:o,retryAfter:i}),s)}};return r.enabled&&(e.hook.error("request",w$.bind(null,r,n)),e.hook.wrap("request",I1.bind(null,r,n))),n}var R$,$1,d_=A(()=>{R$=B(c_(),1);VS();$1="0.0.0-development";wu.VERSION=$1});var v$={};re(v$,{checkRateLimit:()=>p_,getOctokit:()=>be,getRateLimitCallbacks:()=>_$});function wm(e){return e.toLocaleTimeString("en-US",{hour12:!1})}function _$(){return{onRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return n<2?(v(ym,`Rate limit hit (retry ${n+1}/2, waiting ${e}s, resets at ${wm(o)}) \u2014 ${s.method} ${s.url}`),!0):(v(ym,`Rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${wm(o)})`),!1)},onSecondaryRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return n<3?(v(ym,`Secondary rate limit hit (retry ${n+1}/3, waiting ${e}s, resets at ${wm(o)}) \u2014 ${s.method} ${s.url}`),!0):(v(ym,`Secondary rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${wm(o)})`),!1)}}}function be(e){if(bm&&S$===e)return bm;let t=_$();return bm=new D1({auth:e,throttle:t,retry:{doNotRetry:[400,401,403,404,410,422,429,451]}}),S$=e,bm}async function p_(e){let t=be(e),{data:r}=await t.rateLimit.get(),n=r.resources.search;return{remaining:n.remaining,limit:n.limit,resetAt:new Date(n.reset*1e3).toISOString()}}var ym,D1,bm,S$,so=A(()=>{"use strict";o_();l_();d_();ce();ym="github",D1=hm.plugin(wu,Xi),bm=null,S$=null});function C$(e,t){let r=[],n=0;for(let s of e){if(q(s.url)===null){v(Ne,`Dropping ${t} PR with invalid URL: ${s.url}`),n++;continue}r.push(s)}return{valid:r,dropped:n}}function P$(e,t){let r=!1;for(let n of L1)t[n]!==void 0&&e[n]===void 0&&(e[n]=t[n],r=!0);return r}async function we(e,t,r){if(!e.isGistMode())return null;r?.();try{return await E$(e,t)}catch(n){return n instanceof Qt&&r?F1(e,t,r,n):Rm(t,n)}}async function E$(e,t){if(await e.checkpoint())return null;let r="Gist checkpoint push failed after retry; the local mutation is saved and will sync on the next successful push";return v(t,r),r}async function F1(e,t,r,n){let s;try{s=await e.runMutation(()=>e.refreshFromGist({force:!0}))}catch(o){return Rm(t,o)}if(!s)return Rm(t,n);try{r()}catch(o){let i=`Gist conflict recovery failed; state was refreshed from the Gist and re-applying the mutation threw, so the mutation was LOST, re-run the command: ${I(o)}`;return v(t,i),i}try{return await E$(e,t)}catch(o){return Rm(t,o)}}function Rm(e,t){let r=`Gist checkpoint failed; the local mutation is saved but NOT synced to the Gist, re-run the command to retry: ${I(t)}`;return v(e,r),r}function L(){return Sn||(Sn=new ea),Sn}async function m_(e){return Sn&&(!e||Sn.isGistMode()&&!Sn.isGistDegraded())?Sn:oo||(e?(oo=ea.createWithGist(e).then(t=>(Sn=t,oo=null,t)).catch(t=>{if(oo=null,t instanceof Te||!im(t))throw t;return v(Ne,`Gist initialization failed (transient network error), falling back to local-only mode: ${t}`),L()}),oo):L())}async function ta(e){let t;try{let n=ss.readFileSync(jt(),"utf8");t=JSON.parse(n)?.config?.persistence}catch(n){if(n.code!=="ENOENT")return v(Ne,`State file unreadable during gist-persistence check (will retry): ${I(n)}`),"state-unreadable";let s=N1();if(s==="local")return"local-mode";if(s==="unreadable")return"state-unreadable";t="gist"}if(t!=="gist")return"local-mode";if(!e)return"no-token";let r=await m_(e);return r.isGistMode()&&!r.isGistDegraded()?"gist":"degraded"}function N1(){try{let e=ss.readFileSync(es(),"utf8");return JSON.parse(e)?.config?.persistence==="gist"?"gist":"local"}catch(e){if(e.code!=="ENOENT")return v(Ne,`State cache unreadable during gist-persistence check (will retry): ${I(e)}`),"unreadable"}try{return ss.existsSync(Qs())?"gist":"local"}catch(e){return v(Ne,`Gist ID check failed during gist-persistence check (will retry): ${I(e)}`),"unreadable"}}async function A$(e){let t=null;try{let r=await ta(null);r==="no-token"&&(r=await ta(await e())),r==="no-token"?t="no-token":r==="state-unreadable"?t="state-unreadable":r==="degraded"&&(t="init-fallback")}catch(r){let n=`Gist initialization failed: ${I(r)}`;r instanceof $r?n=`Gist initialization failed (${I(r)}). To fix it, ${om}.`:r instanceof Te&&(n=`Gist initialization failed (${I(r)}) \u2014 fix the Gist setup (check the token's gist scope, or run state-show / setup) before relying on sync`),t={reason:n}}return t===null?null:Ji(t)}function Sm(){Sn=null,oo=null}var ss,k$,Ne,L1,M1,ea,Sn,oo,os=A(()=>{"use strict";ss=B(require("node:fs"),1);gn();$S();Ui();pu();LS();ce();ee();NS();jS();zS();Vr();nt();pu();k$="overnight-report.md",Ne="state";L1=["openedAt","firstMaintainerResponseAt","issueUrl","pick","lastReviewDecision","lastCiStatus","backfilledAt","responseRule","closeReason","selfCloseReason"];M1=300;ea=class e{state;inMemoryOnly;lastLoadedMtimeMs=0;_batching=!1;_batchDirty=!1;gistStore=null;gistDegraded=!1;staleness=null;lastSuccessfulRefreshAt=null;mutationDepth=0;unpushed=!1;refreshCount=0;loadRecovery=null;constructor(t=!1){if(this.inMemoryOnly=t,t)this.state=bn();else{let r=cm();this.state=r.state,this.lastLoadedMtimeMs=r.mtimeMs,this.loadRecovery=r.recovery??null,this.tryReconcilePRCounts()}}static async createWithGist(t){let{getOctokit:r}=await Promise.resolve().then(()=>(so(),v$)),n=r(t),s=new Zi(n),o=jt(),i,a=null;if(ss.existsSync(o)){let u=cm();a=u.recovery??null;let d=await s.bootstrapWithMigration(u.state);if(i=d,d.migrated)try{let p=o+".pre-gist-migration";ss.renameSync(o,p),O(Ne,`Renamed ${o} to ${p} after Gist migration`)}catch(p){v(Ne,`Failed to rename state.json after Gist migration: ${p}`)}}else i=await s.bootstrap();let c=new e(!0);return c.state=i.state,i.gistId&&(c.state.gistId=i.gistId),c.gistStore=s,c.gistDegraded=i.degraded??!1,c.inMemoryOnly=!1,c.loadRecovery=a,i.degraded&&(c.staleness={source:"cache",reason:"initial Gist bootstrap fell back to local cache",lastSuccessfulRefresh:null,detectedAt:new Date().toISOString()}),c}tryReconcilePRCounts(){try{this.reconcilePRCounts()}catch(t){v(Ne,`PR count reconciliation failed (will retry on next load): ${I(t)}`),O(Ne,`Reconciliation error details: ${t instanceof Error?t.stack:String(t)}`)}}batch(t){if(this._batching){t();return}this._batching=!0,this._batchDirty=!1;try{t(),this._batchDirty&&this.save()}finally{this._batching=!1,this._batchDirty=!1}}autoSave(){if(this._batching){this._batchDirty=!0;return}this.save()}isSetupComplete(){return this.state.config.setupComplete===!0}markSetupComplete(){this.state.config.setupComplete=!0,this.state.config.setupCompletedAt=new Date().toISOString(),this.autoSave()}initializeWithDefaults(t){if(this.state.config.setupComplete){O(Ne,`Setup already complete, skipping initializeWithDefaults for "${t}"`);return}this.batch(()=>{this.updateConfig({githubUsername:t}),this.markSetupComplete(),O(Ne,`Initialized with defaults for user "${t}"`)})}save(t={}){if(this.state.lastRunAt=new Date().toISOString(),this.gistStore&&(this.unpushed=!0),!this.inMemoryOnly){if(this.gistStore){try{Or(es(),Ar(this.state),384)}catch(r){v(Ne,`Failed to write Gist local cache: ${I(r)}`)}return}try{this.lastLoadedMtimeMs=VA(this.state,this.lastLoadedMtimeMs)}catch(r){if(r instanceof Tr&&t.allowReloadAndLoseMutation){v(Ne,`Concurrent external write detected; reloading and discarding in-memory mutation. ${r.message}`),this.reloadIfChanged();return}throw r}}}async checkpoint(){if(!this.gistStore)return!0;this.gistStore.setState(Ar(this.state));let t;try{t=await this.gistStore.push()}catch(r){throw r instanceof $r&&(this.gistDegraded=!0),r}return this.gistDegraded=!t,t&&(this.unpushed=!1),t}isGistMode(){return this.gistStore!==null}isGistDegraded(){return this.gistDegraded}getGistHealth(){return this.gistStore===null?{mode:"local",degraded:this.state.config.persistence==="gist"?{cause:"configured-but-local",recoverable:!0}:null}:this.gistDegraded?{mode:"gist",degraded:{cause:"bootstrap-degraded",...this.staleness&&{since:this.staleness.detectedAt},recoverable:!0}}:{mode:"gist",degraded:null}}isGuidelinesAvailable(){return this.gistStore!==null}getGuidelines(t){return lT(this.gistStore,t)}setGuidelines(t,r){dT(this.gistStore,t,r),this.autoSave()}deleteGuidelines(t){pT(this.gistStore,t),this.autoSave()}listGuidelinesRepos(){return mT(this.gistStore)}getState(){return this.state}reloadIfChanged(){if(this.inMemoryOnly||this.gistStore)return!1;let t=qA(this.lastLoadedMtimeMs);return t?(this.state=t.state,this.lastLoadedMtimeMs=t.mtimeMs,this.loadRecovery=t.recovery??null,this.tryReconcilePRCounts(),!0):!1}getLoadRecovery(){return this.loadRecovery}async runMutation(t){this.mutationDepth++;try{return await t()}finally{this.mutationDepth--}}get refreshGeneration(){return this.refreshCount}hasUnpushedChanges(){return this.unpushed}forgetUnpushedChanges(){this.unpushed=!1}async refreshFromGist(t={}){if(!this.gistStore||this.mutationDepth>0&&!t.force)return!1;if(t.force&&this.mutationDepth===0&&this.unpushed)return v(Ne,"Forced Gist refresh refused: local changes are not pushed yet and nothing would re-apply them"),!1;let n=(await this.gistStore.refreshFromGist(t)).status==="refreshed";if(n){let s=this.gistStore.cachedFiles.get("state.json");if(!s)return v(Ne,"Gist refreshed but state.json missing from cache"),this.staleness={source:"cache",reason:"Gist refresh returned no state.json file",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1;let o=this.unpushed,i;try{i=JSON.parse(s),this.state=Gt.parse(i)}catch(c){return v(Ne,`Failed to parse refreshed Gist state: ${I(c)}`),this.staleness={source:"cache",reason:`Gist refresh succeeded but payload was invalid: ${I(c)}`,lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1}Xs(i,this.state,"Gist state"),this.tryReconcilePRCounts(),this.unpushed=!1;let a=new Date;if(this.lastSuccessfulRefreshAt=a.toISOString(),this.staleness=null,this.refreshCount++,o&&!t.force){let c="A Gist refresh replaced local state that still had un-pushed changes; they were NOT synced. Re-run the command that made the change.";v(Ne,c),this.staleness={reason:c,source:"cache",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:a.toISOString()}}}else this.gistStore.lastRefreshError&&(this.staleness={source:"cache",reason:I(this.gistStore.lastRefreshError),lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()});return n}getStateStaleness(){return this.staleness}setLastDigest(t){this.state.lastDigest=t,this.state.lastDigestAt=t.generatedAt,this.autoSave()}setLastStrategyAt(t){this.state.lastStrategyAt=t,this.autoSave()}setMonthlyMergedCounts(t){this.state.monthlyMergedCounts=t,this.autoSave()}setMonthlyClosedCounts(t){this.state.monthlyClosedCounts=t,this.autoSave()}setMonthlyOpenedCounts(t){this.state.monthlyOpenedCounts=t,this.autoSave()}setLocalRepoCache(t){this.state.localRepoCache=t,this.autoSave()}getMergedPRs(){return this.state.mergedPRs??[]}addMergedPRs(t){if(t.length===0)return{added:0,dropped:0};let{valid:r,dropped:n}=C$(t,"merged"),s=r.map(c=>this.withPick(c));if(s.length===0)return{added:0,dropped:n};this.state.mergedPRs||(this.state.mergedPRs=[]);let o=new Map(this.state.mergedPRs.map(c=>[c.url,c])),i=[],a=!1;for(let c of s){let u=o.get(c.url);u?a=P$(u,c)||a:(i.push(c),o.set(c.url,c))}return i.length===0&&!a?{added:0,dropped:n}:(this.state.mergedPRs.push(...i),this.state.mergedPRs.sort((c,u)=>u.mergedAt.localeCompare(c.mergedAt)),O(Ne,`Added ${i.length} merged PRs (total: ${this.state.mergedPRs.length})`),this.autoSave(),{added:i.length,dropped:n})}withPick(t){if(!t.issueUrl||t.pick)return t;let r=t.issueUrl.toLowerCase(),n=this.getPickSnapshots().find(s=>s.issueUrl.toLowerCase()===r);return n?{...t,pick:n}:t}getMergedPRWatermark(){return this.state.mergedPRs?.[0]?.mergedAt||void 0}getClosedPRs(){return this.state.closedPRs??[]}addClosedPRs(t){if(t.length===0)return{added:0,dropped:0};let{valid:r,dropped:n}=C$(t,"closed"),s=r.map(c=>this.withPick(c));if(s.length===0)return{added:0,dropped:n};this.state.closedPRs||(this.state.closedPRs=[]);let o=new Map(this.state.closedPRs.map(c=>[c.url,c])),i=[],a=!1;for(let c of s){let u=o.get(c.url);u?a=P$(u,c)||a:(i.push(c),o.set(c.url,c))}return i.length===0&&!a?{added:0,dropped:n}:(this.state.closedPRs.push(...i),this.state.closedPRs.sort((c,u)=>u.closedAt.localeCompare(c.closedAt)),O(Ne,`Added ${i.length} closed PRs (total: ${this.state.closedPRs.length})`),this.autoSave(),{added:i.length,dropped:n})}getClosedPRWatermark(){return this.state.closedPRs?.[0]?.closedAt||void 0}markPRCommentsFetched(t,r){let n=this.state.mergedPRs?.find(o=>o.url===t);if(n){n.commentsFetchedAt=r,this.autoSave();return}let s=this.state.closedPRs?.find(o=>o.url===t);s&&(s.commentsFetchedAt=r,this.autoSave())}setLedgerResponse(t,r,n){let s=this.state.mergedPRs?.find(o=>o.url===t)??this.state.closedPRs?.find(o=>o.url===t);s&&(r===void 0?delete s.firstMaintainerResponseAt:s.firstMaintainerResponseAt=r,s.responseRule=n,this.autoSave())}markPRLearningsExtracted(t,r){let n=this.state.mergedPRs?.find(o=>o.url===t);if(n){n.learningsExtractedAt=r,this.autoSave();return}let s=this.state.closedPRs?.find(o=>o.url===t);s&&(s.learningsExtractedAt=r,this.autoSave())}updateConfig(t){this.state.config={...this.state.config,...t},this.autoSave()}addIssue(t){let r=We(t.url),n=this.state.activeIssues.find(s=>r?We(s.url)===r:s.url===t.url);if(n){n.status=t.status,n.updatedAt=t.updatedAt,O(Ne,`Issue ${t.url} already tracked; refreshed claim stamp to ${t.updatedAt}`),this.autoSave();return}this.state.activeIssues.push(t),O(Ne,`Added issue: ${t.repo}#${t.number}`),this.autoSave()}releaseIssue(t,r){let n=We(t),s=this.state.activeIssues.findIndex(i=>n?We(i.url)===n:i.url===t);if(s===-1)return O(Ne,`releaseIssue: ${t} is not tracked; nothing to release`),"not_tracked";let o=this.state.activeIssues[s];if(r!==void 0){let i=Date.parse(o.updatedAt),a=Date.parse(r);if(Number.isNaN(i)||Number.isNaN(a)||i>=a)return O(Ne,`releaseIssue: keeping ${o.repo}#${o.number}; claim stamp ${o.updatedAt} is not before ${r}`),"newer_claim"}return this.state.activeIssues.splice(s,1),O(Ne,`Released issue claim: ${o.repo}#${o.number}`),this.autoSave(),"released"}addTrustedProject(t){this.state.config.trustedProjects.includes(t)||(this.state.config.trustedProjects.push(t),O(Ne,`Added trusted project: ${t}`),this.autoSave())}static matchesExclusion(t,r,n){let s=t.toLowerCase();return!!(r.some(o=>o.toLowerCase()===s)||n?.some(o=>o.toLowerCase()===s.split("/",1)[0]))}cleanupExcludedData(t,r){let n=i=>e.matchesExclusion(i,t,r),s=this.state.config.trustedProjects.length;this.state.config.trustedProjects=this.state.config.trustedProjects.filter(i=>!n(i));let o=s-this.state.config.trustedProjects.length;o>0&&(O(Ne,`Removed ${o} trusted project(s) for excluded repos/orgs`),this.autoSave())}getStarredRepos(){return this.state.config.starredRepos||[]}setStarredRepos(t){this.state.config.starredRepos=t,this.state.config.starredReposLastFetched=new Date().toISOString(),O(Ne,`Updated starred repos: ${t.length} repositories`),this.autoSave()}isStarredReposStale(){let t=this.state.config.starredReposLastFetched;if(!t)return!0;let r=1440*60*1e3,n=new Date(t);return new Date().getTime()-n.getTime()>r}shelvePR(t){return this.state.config.shelvedPRUrls||(this.state.config.shelvedPRUrls=[]),this.state.config.shelvedPRUrls.includes(t)?!1:(this.state.config.shelvedPRUrls.push(t),this.autoSave(),!0)}unshelvePR(t){if(!this.state.config.shelvedPRUrls)return!1;let r=this.state.config.shelvedPRUrls.indexOf(t);return r===-1?!1:(this.state.config.shelvedPRUrls.splice(r,1),this.autoSave(),!0)}isPRShelved(t){return this.state.config.shelvedPRUrls?.includes(t)??!1}dismissIssue(t,r,n={}){return this.state.config.dismissedIssues||(this.state.config.dismissedIssues={}),t in this.state.config.dismissedIssues&&!n.refresh?!1:(this.state.config.dismissedIssues[t]=r,this.setDismissedPRHead(t,n.headSha),this.autoSave(),!0)}undismissIssue(t){return!this.state.config.dismissedIssues||!(t in this.state.config.dismissedIssues)?!1:(delete this.state.config.dismissedIssues[t],this.setDismissedPRHead(t,void 0),this.autoSave(),!0)}getIssueDismissedAt(t){return this.state.config.dismissedIssues?.[t]}getDismissedPRHead(t){return this.state.config.dismissedPRHeads?.[t]}setDismissedPRHead(t,r){this.state.config.dismissedPRHeads||(this.state.config.dismissedPRHeads={}),r===void 0?delete this.state.config.dismissedPRHeads[t]:this.state.config.dismissedPRHeads[t]=r}getPickSnapshots(){return this.state.pickSnapshots??[]}recordPickSnapshots(t){let r=new Set(this.getPickSnapshots().map(s=>s.issueUrl.toLowerCase())),n=t.filter(s=>{let o=s.issueUrl.toLowerCase();return r.has(o)?!1:(r.add(o),!0)});n.length!==0&&(this.state.pickSnapshots=[...this.getPickSnapshots(),...n].slice(-M1),this.autoSave())}getSearchSeen(){return this.state.searchSeen??[]}setSearchSeen(t){this.state.searchSeen=t,this.autoSave()}getOvernightReportDocument(){let t=this.gistStore?.getDocument(k$)??null;return t===""?null:t}setOvernightReportDocument(t){this.gistStore?.setDocument(k$,t)}getLastOvernight(){return this.state.lastOvernight}setLastOvernight(t){this.state.lastOvernight=t,this.autoSave()}getSearchRotation(){return this.state.searchRotation}setSearchRotation(t){this.state.searchRotation=t,this.autoSave()}getWorkClaims(){return this.state.workClaims??[]}getActiveWorkClaims(t=Date.now()){return cr(this.getWorkClaims(),t)}pruneWorkClaims(t){let r=this.getWorkClaims();for(let n of r)Number.isFinite(Date.parse(n.expiresAt))||v(Ne,`Pruning work claim on ${n.url} (session ${n.session}): expiresAt "${n.expiresAt}" is not a date`);return cr(r,t)}upsertWorkClaim(t,r=Date.now()){let n=Yt(t.url),s=this.pruneWorkClaims(r),o=s.some(i=>Yt(i.url)===n);return this.state.workClaims=[...s.filter(i=>Yt(i.url)!==n),t],this.autoSave(),o}finishWorkClaim(t,r,n=Date.now()){let s=Yt(t),o=this.pruneWorkClaims(n),i=o.find(c=>Yt(c.url)===s);if(!i)return;let a=Zp(i,r);return this.state.workClaims=o.map(c=>c===i?a:c),this.autoSave(),a}releaseWorkClaims(t,r=Date.now()){let n=t.url===void 0?void 0:Yt(t.url),s=a=>n!==void 0&&Yt(a.url)!==n||t.session!==void 0&&a.session!==t.session?!1:t.kind===void 0||a.kind===t.kind,o=this.pruneWorkClaims(r),i=o.filter(a=>s(a)).map(a=>a.url);return i.length>0&&(this.state.workClaims=o.filter(a=>!s(a)),this.autoSave()),i}setStatusOverride(t,r,n){this.state.config.statusOverrides||(this.state.config.statusOverrides={}),this.state.config.statusOverrides[t]={status:r,setAt:new Date().toISOString(),lastActivityAt:n},this.autoSave()}clearStatusOverride(t){return!this.state.config.statusOverrides||!(t in this.state.config.statusOverrides)?!1:(delete this.state.config.statusOverrides[t],this.autoSave(),!0)}getStatusOverride(t,r){let n=this.state.config.statusOverrides?.[t];if(n){if(r&&r>n.lastActivityAt){this.clearStatusOverride(t);return}return n}}getRepoScore(t){return QA(this.state,t)}updateRepoScore(t,r){DS(this.state,t,r),this.autoSave()}getReposWithMergedPRs(){return XA(this.state)}getReposWithOpenPRs(){return eT(this.state)}getHighScoringRepos(t){return tT(this.state,t)}getLowScoringRepos(t){return rT(this.state,t)}getStats(){return iT(this.state)}renameRepo(t,r){oT(this.state,t,r),this.autoSave()}reconcilePRCounts(){let t=this.state.mergedPRs??[],r=this.state.closedPRs??[];if(t.length===0&&r.length===0)return;nT(this.state,t,r)&&this.autoSave()}},Sn=null,oo=null});async function Kr(e,t,r){let n=0,s=!1,o=async()=>{for(;n<e.length&&!s;){let a=e[n++];try{await t(a)}catch(c){throw s=!0,c}}},i=Math.min(r,e.length);await Promise.all(Array.from({length:i},()=>o()))}function _m(e){let t=e.filter(n=>n.status==="rejected");if(t.length===0)return;throw(t.find(n=>de(n.reason))??t[0]).reason}var vr,is=A(()=>{"use strict";ee();vr=5});async function je(e,t=100,r=10){let n=[];for(let s=1;s<=r;s++){let{data:o}=await e(s);if(n.push(...o),o.length<t)return{items:n,truncated:!1}}return{items:n,truncated:!0}}async function vm(e,t=100,r=10){let{items:n}=await je(e,t,r);return n}var io=A(()=>{"use strict"});function as(){return f_||(f_=new Su),f_}async function ra(e,t,r){let n=e.getInflight(t);if(n)return O(_n,`Dedup hit for ${t}`),await n;let o=(async()=>{let a={},c=e.get(t);c&&(a["if-none-match"]=c.etag);try{let u=await r(a),d=u.headers?.etag;return d&&e.set(t,d,u.data),u.data}catch(u){if(j1(u)){let d=e.get(t);if(d)return O(_n,`304 cache hit for ${t}`),d.body}throw u}})(),i=e.setInflight(t,o);try{return await o}finally{i()}}function j1(e){return Ue(e)===304}var vt,Ru,T$,_n,G1,U1,Su,f_,_u=A(()=>{"use strict";vt=B(require("node:fs"),1),Ru=B(require("node:path"),1),T$=B(require("node:crypto"),1);Vr();ce();ee();_n="http-cache",G1=1440*60*1e3,U1=2e3,Su=class{cacheDir;maxEntries;inflightRequests=new Map;constructor(t,r=U1){this.cacheDir=t??Xp(),this.maxEntries=r}keyFor(t){return T$.createHash("sha256").update(t).digest("hex")}pathFor(t){return Ru.join(this.cacheDir,`${this.keyFor(t)}.json`)}getIfFresh(t,r){let n=this.get(t);if(!n)return null;let s=Date.now()-new Date(n.cachedAt).getTime();return!Number.isFinite(s)||s<0||s>r?null:n.body}get(t){let r=this.pathFor(t);try{let n=vt.readFileSync(r,"utf8"),s=JSON.parse(n);return s.url!==t?(O(_n,`Cache collision detected for ${t}, ignoring`),null):s}catch(n){if(n&&typeof n=="object"&&n.code!=="ENOENT"){let s=n instanceof Error?n.message:"unknown error";O(_n,`Cache read failed for ${t} (treating as miss): ${s}`)}return null}}set(t,r,n){let s={etag:r,url:t,body:n,cachedAt:new Date().toISOString()};try{vt.writeFileSync(this.pathFor(t),JSON.stringify(s),{encoding:"utf8",mode:384}),O(_n,`Cached response for ${t}`),this.evictIfExceeds(this.maxEntries)}catch(o){O(_n,`Failed to write cache for ${t}`,o)}}evictIfExceeds(t){if(!(t<=0))try{let r=vt.readdirSync(this.cacheDir).filter(i=>i.endsWith(".json"));if(r.length<=t)return;let n=r.map(i=>{let a=Ru.join(this.cacheDir,i);try{return{fullPath:a,mtimeMs:vt.statSync(a).mtimeMs}}catch{return null}}).filter(i=>i!==null).sort((i,a)=>i.mtimeMs-a.mtimeMs),s=n.length-t,o=0;for(let i=0;i<s;i++)try{vt.unlinkSync(n[i].fullPath),o++}catch{}o>0&&O(_n,`Capped cache at ${t} entries: evicted ${o} oldest`)}catch{}}hasInflight(t){return this.inflightRequests.has(t)}getInflight(t){return this.inflightRequests.get(t)}setInflight(t,r){return this.inflightRequests.set(t,r),()=>{this.inflightRequests.delete(t)}}evictStale(t=G1){let r=0;try{let n=vt.readdirSync(this.cacheDir),s=Date.now();for(let o of n){if(!o.endsWith(".json"))continue;let i=Ru.join(this.cacheDir,o);try{let a=vt.readFileSync(i,"utf8"),c=JSON.parse(a);s-new Date(c.cachedAt).getTime()>t&&(vt.unlinkSync(i),r++)}catch{try{vt.unlinkSync(i),r++}catch{}}}}catch{}return r>0&&O(_n,`Evicted ${r} stale cache entries`),r}clear(){try{let t=vt.readdirSync(this.cacheDir);for(let r of t)r.endsWith(".json")&&vt.unlinkSync(Ru.join(this.cacheDir,r));O(_n,"Cache cleared")}catch{}}size(){try{return vt.readdirSync(this.cacheDir).filter(t=>t.endsWith(".json")).length}catch{return 0}}},f_=null});function km(){return{status:"unknown",failingCheckNames:[],failingCheckConclusions:new Map}}function Cm(e,t,r){if(r==="cancelled"||r==="timed_out")return"infrastructure";if(r==="action_required")return"auth_gate";let n=e.toLowerCase();if(O$.some(s=>s.test(n)))return"auth_gate";if($$.some(s=>s.test(n)))return"fork_limitation";if(I$.some(s=>s.test(n)))return"infrastructure";if(t){let s=t.toLowerCase();if(O$.some(o=>o.test(s)))return"auth_gate";if($$.some(o=>o.test(s)))return"fork_limitation";if(I$.some(o=>o.test(s)))return"infrastructure"}return"actionable"}function vu(e,t){return e.map(r=>{let n=t?.get(r);return{name:r,category:Cm(r,void 0,n),conclusion:n}})}function g_(e){let{ciStatus:t,failingCheckNames:r,classifiedChecks:n}=e;if(t==="passing")return{category:"all_passing",summary:"All checks passing",action:"none"};if(t==="pending"){let s=r.length;return{category:"blocked",summary:s>0?`${s} pending check(s); CI run incomplete`:"CI checks pending",action:"request_rerun"}}if(t==="failing"){let s=n.filter(a=>a.category==="actionable");if(s.length>0){let a=s.slice(0,3).map(u=>u.name).join(", "),c=s.length>3?` (+${s.length-3} more)`:"";return{category:"failing",summary:`${s.length} actionable failure(s): ${a}${c}`,action:"investigate"}}return n.length===0?{category:"failing",summary:"CI reported failure but no check details available",action:"investigate"}:n.some(a=>a.category==="infrastructure")?{category:"blocked",summary:`${n.length} non-actionable failure(s) including infrastructure issues; rerun may resolve`,action:"request_rerun"}:{category:"fork_limitation",summary:`${n.length} non-actionable failure(s) (fork limits / auth gates)`,action:"informational"}}return{category:"not_running",summary:"No CI checks reported",action:"check_workflows"}}function z1(e){let t=!1,r=!1,n=!1,s=[],o=new Map;for(let i of e)i.conclusion==="failure"||i.conclusion==="cancelled"||i.conclusion==="timed_out"||i.conclusion==="action_required"?(t=!0,s.push(i.name),o.set(i.name,i.conclusion)):i.conclusion===null&&i.status==="waiting"?(t=!0,s.push(i.name),o.set(i.name,"action_required")):i.conclusion===null&&i.status!=="completed"?r=!0:i.conclusion==="success"&&(n=!0);return{hasFailingChecks:t,hasPendingChecks:r,hasSuccessfulChecks:n,failingCheckNames:s,failingCheckConclusions:o}}function B1(e){let t=e.statuses.filter(c=>{let u=(c.description||"").toLowerCase();return!(c.state==="failure"&&(u.includes("authorization required")||u.includes("authorize")))}),r=t.some(c=>c.state==="failure"||c.state==="error"),n=t.some(c=>c.state==="pending"),s=t.some(c=>c.state==="success"),o;r?o="failure":n?o="pending":s||t.length===0?o="success":o=e.state;let i=e.statuses.length>0,a=[];for(let c of t)(c.state==="failure"||c.state==="error")&&a.push(c.context);return{effectiveCombinedState:o,hasStatuses:i,failingStatusNames:a}}function H1(e,t,r){let{hasFailingChecks:n,hasPendingChecks:s,hasSuccessfulChecks:o,failingCheckNames:i,failingCheckConclusions:a}=e,{effectiveCombinedState:c,hasStatuses:u,failingStatusNames:d}=t,p=[...i,...d];return n||c==="failure"||c==="error"?{status:"failing",failingCheckNames:p,failingCheckConclusions:a}:s||c==="pending"?{status:"pending",failingCheckNames:[],failingCheckConclusions:new Map}:o||c==="success"?{status:"passing",failingCheckNames:[],failingCheckConclusions:new Map}:km()}function h_(e,t){let r=new Map;for(let i of e){let a=r.get(i.name);(!a||new Date(i.started_at??0)>new Date(a.started_at??0))&&r.set(i.name,i)}let n=[...r.values()],s=z1(n),o=B1(t);return H1(s,o,n.length)}async function y_(e,t,r,n){if(!n)return km();try{let[s,o]=await Promise.all([e.repos.getCombinedStatusForRef({owner:t,repo:r,ref:n,per_page:100}),vm(c=>e.checks.listForRef({owner:t,repo:r,ref:n,per_page:100,page:c}).then(u=>({data:u.data.check_runs}))).catch(c=>{let u=Ue(c);if(u===429)throw c;if(u===403){let d=I(c).toLowerCase();if(d.includes("rate limit")||d.includes("abuse detection"))throw c}return u===404?O("pr-monitor",`Check runs 404 for ${t}/${r}@${n.slice(0,7)} (no checks configured)`):v("pr-monitor",`Non-404 error fetching check runs for ${t}/${r}@${n.slice(0,7)}: ${u??c}`),null})]),i=s.data;return h_(o??[],i)}catch(s){let o=Ue(s);if(o===401||o===403||o===429)throw s;return o===404?O("pr-monitor",`CI check 404 for ${t}/${r} (no CI configured)`):v("pr-monitor",`Failed to check CI for ${t}/${r}@${n.slice(0,7)}: ${I(s)}`),km()}}var $$,O$,I$,ku=A(()=>{"use strict";ee();ce();io();$$=[/vercel/i,/netlify/i,/\bpreview\s*deploy/i,/\bdeploy\s*preview/i,/storybook/i,/chromatic/i,/percy/i,/cloudflare pages/i,/\binternal\b(?!\s+(?:api|test|integration|smoke|unit|e2e|regression|functional))/i],O$=[/authoriz/i,/approval/i,/\bcla\b/i,/license\/cla/i,/\b(?:pr|type|require[sd]?|check|missing)[\s-]+(?:\w+[\s-]+)?labels?\b/i,/\blabeler\b/i,/\btriage\b/i],I$=[/\binstall\s*(os\s*)?dep(endenc|s\b)/i,/\bsetup\s+fail(ed|ure)?\b/i,/\bservice\s*unavailable/i,/\binfrastructure/i,/\bblacksmith\b/i,/\breadthedocs\b/i]});function Cu(e){if(e.status==="rejected")throw e.reason;return e.value}function x$(e){let t=q(e);if(!t||t.type!=="pull")throw new j(`Invalid PR URL format: ${e}`);return t}async function q1(e,t){let r={items:[],totalCount:0,pagesRead:0,incomplete:!1};for(let n=1;n<=S_;n++){let s;try{({data:s}=await e.search.issuesAndPullRequests({q:t,page:n,sort:"updated",order:"desc",per_page:w_}))}catch(o){if(de(o))throw o;return r.failure={page:n,error:o},r}if(r.pagesRead=n,r.totalCount=s.total_count,s.incomplete_results&&(r.incomplete=!0),r.items.push(...s.items),s.items.length<w_||r.items.length>=r.totalCount)break}return r}function Z1(e,t){if(t.failure)return`GitHub search for ${e} failed on page ${t.failure.page} (${Xt(t.failure.error)}); only the ${t.items.length} result(s) from the ${t.pagesRead} page(s) before it were read this run.`;if(t.items.length<t.totalCount)return`GitHub Search API reports ${t.totalCount} ${e}, but only the ${t.items.length} most recently updated were read (${t.pagesRead} page(s) of ${w_}). Older reviewed PRs are not checked this run.`}function K1(e,t){let r=`open PRs you ${e} (not authored)`,n=[],s=Z1(r,t);return s!==void 0&&n.push(s),t.incomplete&&n.push(`GitHub Search API returned incomplete results for ${r} (the search timed out server-side); some reviewed PRs may be missing this run.`),n}function J1(e,t){return(Date.parse(t.updatedAt)||0)-(Date.parse(e.updatedAt)||0)}async function D$(e,t){let r=t.githubUsername;if(!r)throw new Te("No GitHub username configured. Run setup first.");let n=new R_(t),s=[],o=new Set,i=[];for(let{qualifier:a,label:c}of V1){let u=await q1(e,`is:pr is:open is:public ${a}:${r} -author:${r}`);for(let d of u.items){if(o.has(d.html_url))continue;o.add(d.html_url);let p=n.toRef(d);p&&s.push(p)}for(let d of K1(c,u))i.push(d),v(b_,d)}return s.sort(J1),O(b_,`Found ${s.length} open PRs reviewed by @${r}`),{prs:s,warnings:i}}async function L$(e,t){let{owner:r,repo:n,number:s}=x$(t),o=await Promise.allSettled([e.pulls.get({owner:r,repo:n,pull_number:s}),je(f=>e.issues.listComments({owner:r,repo:n,page:f,issue_number:s,per_page:100})),je(f=>e.pulls.listReviews({owner:r,repo:n,page:f,pull_number:s,per_page:100})),je(f=>e.pulls.listReviewComments({owner:r,repo:n,page:f,pull_number:s,per_page:100})),je(f=>e.pulls.listCommits({owner:r,repo:n,page:f,pull_number:s,per_page:100}))]);_m(o);let i=Cu(o[0]).data,a=Cu(o[1]),c=Cu(o[2]),u=Cu(o[3]),d=Cu(o[4]),p=[];return a.truncated&&p.push("comments"),c.truncated&&p.push("reviews"),u.truncated&&p.push("review comments"),(d.items.length>=W1||d.items.at(-1)?.sha!==i.head.sha||d.truncated)&&p.push("commits"),{truncatedLists:p,pr:{headSha:i.head.sha,state:i.state,author:i.user?.login,title:i.title},comments:a.items,reviews:c.items,reviewComments:u.items,commits:d.items}}async function M$(e,t,r,n){let{owner:s,repo:o}=x$(t);try{let{data:i}=await e.repos.compareCommitsWithBasehead({owner:s,repo:o,basehead:`${r}...${n}`,per_page:1});return i.status}catch(i){if(Ue(i)===404)return"missing";throw i}}var b_,S_,w_,W1,V1,R_,__=A(()=>{"use strict";is();ee();ce();io();nt();b_="reviewed-prs",S_=3,w_=100,W1=250,V1=[{qualifier:"reviewed-by",label:"reviewed"},{qualifier:"commenter",label:"commented on"}];R_=class{constructor(t){this.config=t;this.usernameLower=t.githubUsername.toLowerCase(),this.excludedRepos=new Set((t.excludeRepos??[]).map(r=>r.toLowerCase())),this.excludedOrgs=new Set((t.excludeOrgs??[]).map(r=>r.toLowerCase()))}config;usernameLower;excludedRepos;excludedOrgs;isRepoExcluded(t,r){let n=t.toLowerCase();return Sr(t,this.config.githubUsername)||Fi(t,this.config.untrackedOrgs)?!0:this.excludedRepos.has(r.toLowerCase())||this.excludedOrgs.has(n)}toRef(t){if(!t.pull_request)return;let r=q(t.html_url);if(!r||r.type!=="pull"){v(b_,`Skipping reviewed PR with unparseable URL: ${t.html_url}`);return}let n=t.user?.login??"",s=`${r.owner}/${r.repo}`;if(!(n.toLowerCase()===this.usernameLower||this.isRepoExcluded(r.owner,s)))return{repo:s,author:n,url:t.html_url,number:r.number,title:t.title,updatedAt:t.updated_at}}}});var F$={};re(F$,{byDateDescending:()=>v_,daysBetween:()=>cs,formatRelativeTime:()=>Pu});function cs(e,t=new Date){return Math.max(0,Math.floor((t.getTime()-e.getTime())/(1e3*60*60*24)))}function Pu(e){let t=new Date(e),r=Date.now()-t.getTime();if(r<0)return"just now";let n=Math.floor(r/6e4),s=Math.floor(r/36e5),o=Math.floor(r/864e5);return n<60?`${n}m ago`:s<24?`${s}h ago`:o<30?`${o}d ago`:t.toLocaleDateString()}function v_(e){return(t,r)=>{let n=new Date(e(t)||0).getTime();return new Date(e(r)||0).getTime()-n}}var na=A(()=>{"use strict"});function X1(e,t){if(!e||!t)return!0;let r=e.toLowerCase();return Y1.has(r)?!0:r===t.toLowerCase()}function sa(e){return e?new Date(e).getTime():Number.NaN}function eB(e,t){let r=sa(e),n=sa(t);return!Number.isFinite(r)||!Number.isFinite(n)?!1:r-n>=Q1}function N$(e){let{latestCommitDate:t,latestCommitAuthor:r,contributorUsername:n}=e;if(t)return X1(r,n)?t:void 0}function G$(e,t,r){if(!e||!t||!eB(e,t))return!1;if(r){let n=sa(e),s=sa(r);if(!Number.isFinite(n)||!Number.isFinite(s)||n<s)return!1}return!0}function U$(e,t){if(!e||!t)return!1;let r=sa(e),n=sa(t);return!Number.isFinite(r)||!Number.isFinite(n)?!1:r>=n}function tB(e){let{ciStatus:t,hasMergeConflict:r,hasUnrespondedComment:n,reviewDecision:s,lastMaintainerCommentDate:o,latestChangesRequestedDate:i,hasActionableCIFailure:a=!0}=e,c=N$(e),u=[];return n&&!(s==="approved"&&(t==="passing"||t==="unknown"))&&!G$(c,o,i)&&u.push("needs_response"),s==="changes_requested"&&i&&!U$(c,i)&&u.push("needs_changes"),t==="failing"&&a&&u.push("failing_ci"),r&&u.push("merge_conflict"),u.length>0?u:void 0}function k_(e){let t=rB(e);t.status==="waiting_on_maintainer"&&e.hasMergeConflict&&(t={status:"needs_addressing",actionReason:"merge_conflict",stalenessTier:t.stalenessTier});let r=tB(e);return r?{...t,actionReasons:r}:t}function rB(e){let{ciStatus:t,hasMergeConflict:r,hasUnrespondedComment:n,reviewDecision:s,daysSinceActivity:o,daysSinceMaintainerActivity:i=o,dormantThreshold:a,approachingThreshold:c,lastMaintainerCommentDate:u,latestChangesRequestedDate:d,hasActionableCIFailure:p=!0}=e,m="active";i>=a?m="dormant":i>=c&&(m="approaching_dormant");let f=N$(e);return n?G$(f,u,d)?t==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:s==="approved"&&(t==="passing"||t==="unknown")?{status:"waiting_on_maintainer",waitReason:"pending_merge",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_response",stalenessTier:m}:s==="changes_requested"&&d?U$(f,d)?t==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_changes",stalenessTier:m}:t==="failing"?p?o>=5?{status:"waiting_on_maintainer",waitReason:"stale_ci_failure",stalenessTier:m}:{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"ci_blocked",stalenessTier:m}:r?{status:"needs_addressing",actionReason:"merge_conflict",stalenessTier:m}:s==="approved"&&(t==="passing"||t==="unknown")?{status:"waiting_on_maintainer",waitReason:"pending_merge",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"pending_review",stalenessTier:m}}var Y1,Q1,C_=A(()=>{"use strict";Y1=new Set(["autofix-ci[bot]","prettier-ci[bot]","pre-commit-ci[bot]"]),Q1=120*1e3});function kt(e,t){if(t==="Bot")return!0;let r=e.toLowerCase();return r.includes("[bot]")||r.endsWith("-bot")||r.endsWith("-robot")||nB.has(r)}function oa(e){if(!e||e.length>100||e.includes("?"))return!1;let t=e.toLowerCase();return["thanks","thank you","lgtm","looks good","will review","we'll review","we'll get to this","noted","got it","will look","will check"].some(n=>t.includes(n))}function B$(e){return e.replaceAll(/:[\w+-]+:/g," ").replaceAll(/[^\p{L}\p{N}+]+/gu," ").trim().toLowerCase()}function ao(e){let t=B$(e);return t===""||sB.has(t)}function Pm(e){return oB.has(B$(e))}function z$(e){return e.replaceAll(/\s+/g," ").trim()}function H$(e){let t=[],r=!1;for(let n of e.split(`
78
+ `);let u=!1,d=()=>{if(u)return;u=!0,Ir.global==null&&T1(n,a),c.global=c.global??Ir.global,c.auth=c.auth??Ir.auth,c.search=c.search??Ir.search,c.write=c.write??Ir.write,c.notifications=c.notifications??Ir.notifications,c.retryLimiter=c.retryLimiter??new n;let p={},m=new n.Events(p);p.on("secondary-limit",c.onSecondaryRateLimit),p.on("rate-limit",c.onRateLimit),p.on("error",f=>e.log.warn("Error in throttling-plugin limit handler",f)),c.retryLimiter.on("failed",async function(f,g){let[h,b,w]=g.args,{pathname:y}=new URL(w.url,"http://github.test");if(!(y.startsWith("/graphql")&&f.status!==401||f.status===403||f.status===429))return;let k=~~b.retryCount;b.retryCount=k,w.request.retryCount=k;let{wantRetry:R,retryAfter:P=0}=await(async function(){if(/\bsecondary rate\b/i.test(f.message)){let C=Number(f.response.headers["retry-after"])||h.fallbackSecondaryRateRetryAfter;return{wantRetry:await m.trigger("secondary-limit",C,w,e,k),retryAfter:C}}if(f.response.headers!=null&&f.response.headers["x-ratelimit-remaining"]==="0"||(f.response.data?.errors??[]).some(C=>C.type==="RATE_LIMITED")){let C=new Date(~~f.response.headers["x-ratelimit-reset"]*1e3).getTime(),E=Math.max(Math.ceil((C-Date.now())/1e3)+1,0);return{wantRetry:await m.trigger("rate-limit",E,w,e,k),retryAfter:E}}return{}})();if(R)return b.retryCount++,P*h.retryAfterBaseValue})};return e.hook.wrap("request",(p,m)=>(d(),k1(c,p,m))),{}}var y$,v1,u_,E1,h$,b$,Ir,T1,l_=A(()=>{y$=B(c_(),1),v1="0.0.0-development",u_=()=>Promise.resolve();E1=["/orgs/{org}/invitations","/orgs/{org}/invitations/{invitation_id}","/orgs/{org}/teams/{team_slug}/discussions","/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments","/repos/{owner}/{repo}/collaborators/{username}","/repos/{owner}/{repo}/commits/{commit_sha}/comments","/repos/{owner}/{repo}/issues","/repos/{owner}/{repo}/issues/{issue_number}/comments","/repos/{owner}/{repo}/issues/{issue_number}/sub_issue","/repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority","/repos/{owner}/{repo}/pulls","/repos/{owner}/{repo}/pulls/{pull_number}/comments","/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies","/repos/{owner}/{repo}/pulls/{pull_number}/merge","/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers","/repos/{owner}/{repo}/pulls/{pull_number}/reviews","/repos/{owner}/{repo}/releases","/teams/{team_id}/discussions","/teams/{team_id}/discussions/{discussion_number}/comments"];h$=A1(E1),b$=h$.test.bind(h$),Ir={},T1=function(e,t){Ir.global=new e.Group({id:"octokit-global",maxConcurrent:10,...t}),Ir.auth=new e.Group({id:"octokit-auth",maxConcurrent:1,...t}),Ir.search=new e.Group({id:"octokit-search",maxConcurrent:1,minTime:2e3,...t}),Ir.write=new e.Group({id:"octokit-write",maxConcurrent:1,minTime:1e3,...t}),Ir.notifications=new e.Group({id:"octokit-notifications",maxConcurrent:1,minTime:3e3,...t})};Xi.VERSION=v1;Xi.triggersNotification=b$});function O1(e){return e.request!==void 0}async function w$(e,t,r,n){if(!O1(r)||!r?.request.request)throw r;if(r.status>=400&&!e.doNotRetry.includes(r.status)){let s=n.request.retries!=null?n.request.retries:e.retries,o=Math.pow((n.request.retryCount||0)+1,2);throw t.retry.retryRequest(r,s,o)}throw r}async function I1(e,t,r,n){let s=new R$.default;return s.on("failed",function(o,i){let a=~~o.request.request?.retries,c=~~o.request.request?.retryAfter;if(n.request.retryCount=i.retryCount+1,a>i.retryCount)return c*e.retryAfterBaseValue}),s.schedule(x1.bind(null,e,t,r),n)}async function x1(e,t,r,n){let s=await r(n);if(s.data&&s.data.errors&&s.data.errors.length>0&&/Something went wrong while executing your query/.test(s.data.errors[0].message)){let o=new Rn(s.data.errors[0].message,500,{request:n,response:s});return w$(e,t,o,n)}return s}function wu(e,t){let r=Object.assign({enabled:!0,retryAfterBaseValue:1e3,doNotRetry:[400,401,403,404,410,422,451],retries:3},t.retry),n={retry:{retryRequest:(s,o,i)=>(s.request.request=Object.assign({},s.request.request,{retries:o,retryAfter:i}),s)}};return r.enabled&&(e.hook.error("request",w$.bind(null,r,n)),e.hook.wrap("request",I1.bind(null,r,n))),n}var R$,$1,d_=A(()=>{R$=B(c_(),1);VS();$1="0.0.0-development";wu.VERSION=$1});var v$={};re(v$,{checkRateLimit:()=>p_,getOctokit:()=>be,getRateLimitCallbacks:()=>_$});function wm(e){return e.toLocaleTimeString("en-US",{hour12:!1})}function _$(){return{onRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return n<2?(v(ym,`Rate limit hit (retry ${n+1}/2, waiting ${e}s, resets at ${wm(o)}) \u2014 ${s.method} ${s.url}`),!0):(v(ym,`Rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${wm(o)})`),!1)},onSecondaryRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return n<3?(v(ym,`Secondary rate limit hit (retry ${n+1}/3, waiting ${e}s, resets at ${wm(o)}) \u2014 ${s.method} ${s.url}`),!0):(v(ym,`Secondary rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${wm(o)})`),!1)}}}function be(e){if(bm&&S$===e)return bm;let t=_$();return bm=new D1({auth:e,throttle:t,retry:{doNotRetry:[400,401,403,404,410,422,429,451]}}),S$=e,bm}async function p_(e){let t=be(e),{data:r}=await t.rateLimit.get(),n=r.resources.search;return{remaining:n.remaining,limit:n.limit,resetAt:new Date(n.reset*1e3).toISOString()}}var ym,D1,bm,S$,so=A(()=>{"use strict";o_();l_();d_();ce();ym="github",D1=hm.plugin(wu,Xi),bm=null,S$=null});function C$(e,t){let r=[],n=0;for(let s of e){if(q(s.url)===null){v(Me,`Dropping ${t} PR with invalid URL: ${s.url}`),n++;continue}r.push(s)}return{valid:r,dropped:n}}function P$(e,t){let r=!1;for(let n of L1)t[n]!==void 0&&e[n]===void 0&&(e[n]=t[n],r=!0);return r}async function we(e,t,r){if(!e.isGistMode())return null;r?.();try{return await E$(e,t)}catch(n){return n instanceof Qt&&r?F1(e,t,r,n):Rm(t,n)}}async function E$(e,t){if(await e.checkpoint())return null;let r="Gist checkpoint push failed after retry; the local mutation is saved but NOT synced yet. A running MCP server or dashboard retries the push before its next Gist refresh; a new CLI run starts from the Gist without it, so re-run the command there";return v(t,r),r}async function F1(e,t,r,n){let s;try{s=await e.runMutation(()=>e.refreshFromGist({force:!0}))}catch(o){return Rm(t,o)}if(!s)return Rm(t,n);try{r()}catch(o){let i=`Gist conflict recovery failed; state was refreshed from the Gist and re-applying the mutation threw, so the mutation was LOST, re-run the command: ${I(o)}`;return v(t,i),i}try{return await E$(e,t)}catch(o){return Rm(t,o)}}function Rm(e,t){let r=`Gist checkpoint failed; the local mutation is saved but NOT synced to the Gist, re-run the command to retry: ${I(t)}`;return v(e,r),r}function L(){return Sn||(Sn=new ea),Sn}async function m_(e){return Sn&&(!e||Sn.isGistMode()&&!Sn.isGistDegraded())?Sn:oo||(e?(oo=ea.createWithGist(e).then(t=>(Sn=t,oo=null,t)).catch(t=>{if(oo=null,t instanceof Te||!im(t))throw t;return v(Me,`Gist initialization failed (transient network error), falling back to local-only mode: ${t}`),L()}),oo):L())}async function ta(e){let t;try{let n=ss.readFileSync(jt(),"utf8");t=JSON.parse(n)?.config?.persistence}catch(n){if(n.code!=="ENOENT")return v(Me,`State file unreadable during gist-persistence check (will retry): ${I(n)}`),"state-unreadable";let s=N1();if(s==="local")return"local-mode";if(s==="unreadable")return"state-unreadable";t="gist"}if(t!=="gist")return"local-mode";if(!e)return"no-token";let r=await m_(e);return r.isGistMode()&&!r.isGistDegraded()?"gist":"degraded"}function N1(){try{let e=ss.readFileSync(es(),"utf8");return JSON.parse(e)?.config?.persistence==="gist"?"gist":"local"}catch(e){if(e.code!=="ENOENT")return v(Me,`State cache unreadable during gist-persistence check (will retry): ${I(e)}`),"unreadable"}try{return ss.existsSync(Qs())?"gist":"local"}catch(e){return v(Me,`Gist ID check failed during gist-persistence check (will retry): ${I(e)}`),"unreadable"}}async function A$(e){let t=null;try{let r=await ta(null);r==="no-token"&&(r=await ta(await e())),r==="no-token"?t="no-token":r==="state-unreadable"?t="state-unreadable":r==="degraded"&&(t="init-fallback")}catch(r){let n=`Gist initialization failed: ${I(r)}`;r instanceof $r?n=`Gist initialization failed (${I(r)}). To fix it, ${om}.`:r instanceof Te&&(n=`Gist initialization failed (${I(r)}) \u2014 fix the Gist setup (check the token's gist scope, or run state-show / setup) before relying on sync`),t={reason:n}}return t===null?null:Ji(t)}function Sm(){Sn=null,oo=null}var ss,k$,Me,L1,M1,ea,Sn,oo,os=A(()=>{"use strict";ss=B(require("node:fs"),1);gn();$S();Ui();pu();LS();ce();ee();NS();jS();zS();Vr();nt();pu();k$="overnight-report.md",Me="state";L1=["openedAt","firstMaintainerResponseAt","issueUrl","pick","lastReviewDecision","lastCiStatus","backfilledAt","responseRule","closeReason","selfCloseReason"];M1=300;ea=class e{state;inMemoryOnly;lastLoadedMtimeMs=0;_batching=!1;_batchDirty=!1;gistStore=null;gistDegraded=!1;staleness=null;lastSuccessfulRefreshAt=null;mutationDepth=0;unpushed=!1;refreshCount=0;loadRecovery=null;constructor(t=!1){if(this.inMemoryOnly=t,t)this.state=bn();else{let r=cm();this.state=r.state,this.lastLoadedMtimeMs=r.mtimeMs,this.loadRecovery=r.recovery??null,this.tryReconcilePRCounts()}}static async createWithGist(t){let{getOctokit:r}=await Promise.resolve().then(()=>(so(),v$)),n=r(t),s=new Zi(n),o=jt(),i,a=null;if(ss.existsSync(o)){let u=cm();a=u.recovery??null;let d=await s.bootstrapWithMigration(u.state);if(i=d,d.migrated)try{let p=o+".pre-gist-migration";ss.renameSync(o,p),O(Me,`Renamed ${o} to ${p} after Gist migration`)}catch(p){v(Me,`Failed to rename state.json after Gist migration: ${p}`)}}else i=await s.bootstrap();let c=new e(!0);return c.state=i.state,i.gistId&&(c.state.gistId=i.gistId),c.gistStore=s,c.gistDegraded=i.degraded??!1,c.inMemoryOnly=!1,c.loadRecovery=a,i.degraded&&(c.staleness={source:"cache",reason:"initial Gist bootstrap fell back to local cache",lastSuccessfulRefresh:null,detectedAt:new Date().toISOString()}),c}tryReconcilePRCounts(){try{this.reconcilePRCounts()}catch(t){v(Me,`PR count reconciliation failed (will retry on next load): ${I(t)}`),O(Me,`Reconciliation error details: ${t instanceof Error?t.stack:String(t)}`)}}batch(t){if(this._batching){t();return}this._batching=!0,this._batchDirty=!1;try{t(),this._batchDirty&&this.save()}finally{this._batching=!1,this._batchDirty=!1}}autoSave(){if(this._batching){this._batchDirty=!0;return}this.save()}isSetupComplete(){return this.state.config.setupComplete===!0}markSetupComplete(){this.state.config.setupComplete=!0,this.state.config.setupCompletedAt=new Date().toISOString(),this.autoSave()}initializeWithDefaults(t){if(this.state.config.setupComplete){O(Me,`Setup already complete, skipping initializeWithDefaults for "${t}"`);return}this.batch(()=>{this.updateConfig({githubUsername:t}),this.markSetupComplete(),O(Me,`Initialized with defaults for user "${t}"`)})}save(t={}){if(this.state.lastRunAt=new Date().toISOString(),this.gistStore&&(this.unpushed=!0),!this.inMemoryOnly){if(this.gistStore){try{Or(es(),Ar(this.state),384)}catch(r){v(Me,`Failed to write Gist local cache: ${I(r)}`)}return}try{this.lastLoadedMtimeMs=VA(this.state,this.lastLoadedMtimeMs)}catch(r){if(r instanceof Tr&&t.allowReloadAndLoseMutation){v(Me,`Concurrent external write detected; reloading and discarding in-memory mutation. ${r.message}`),this.reloadIfChanged();return}throw r}}}async checkpoint(){if(!this.gistStore)return!0;this.gistStore.setState(Ar(this.state));let t;try{t=await this.gistStore.push()}catch(r){throw r instanceof $r&&(this.gistDegraded=!0),r}return this.gistDegraded=!t,t&&(this.unpushed=!1),t}isGistMode(){return this.gistStore!==null}isGistDegraded(){return this.gistDegraded}getGistHealth(){return this.gistStore===null?{mode:"local",degraded:this.state.config.persistence==="gist"?{cause:"configured-but-local",recoverable:!0}:null}:this.gistDegraded?{mode:"gist",degraded:{cause:"bootstrap-degraded",...this.staleness&&{since:this.staleness.detectedAt},recoverable:!0}}:{mode:"gist",degraded:null}}isGuidelinesAvailable(){return this.gistStore!==null}getGuidelines(t){return lT(this.gistStore,t)}setGuidelines(t,r){dT(this.gistStore,t,r),this.autoSave()}deleteGuidelines(t){pT(this.gistStore,t),this.autoSave()}listGuidelinesRepos(){return mT(this.gistStore)}getState(){return this.state}reloadIfChanged(){if(this.inMemoryOnly||this.gistStore)return!1;let t=qA(this.lastLoadedMtimeMs);return t?(this.state=t.state,this.lastLoadedMtimeMs=t.mtimeMs,this.loadRecovery=t.recovery??null,this.tryReconcilePRCounts(),!0):!1}getLoadRecovery(){return this.loadRecovery}async runMutation(t){this.mutationDepth++;try{return await t()}finally{this.mutationDepth--}}get refreshGeneration(){return this.refreshCount}hasUnpushedChanges(){return this.unpushed}forgetUnpushedChanges(){this.unpushed=!1}async refreshFromGist(t={}){if(!this.gistStore||this.mutationDepth>0&&!t.force)return!1;if(t.force&&this.mutationDepth===0&&this.unpushed)return v(Me,"Forced Gist refresh refused: local changes are not pushed yet and nothing would re-apply them"),!1;if(!t.force&&this.unpushed){if(await this.checkpoint().catch(o=>(v(Me,`Push before Gist refresh failed: ${I(o)}`),null))===!1)return this.staleness={source:"cache",reason:"Gist refresh skipped: local changes are not pushed yet (push failed); serving local state",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1;if(this.mutationDepth>0)return!1}let n=(await this.gistStore.refreshFromGist(t)).status==="refreshed";if(n){let s=this.gistStore.cachedFiles.get("state.json");if(!s)return v(Me,"Gist refreshed but state.json missing from cache"),this.staleness={source:"cache",reason:"Gist refresh returned no state.json file",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1;let o=this.unpushed,i;try{i=JSON.parse(s),this.state=Gt.parse(i)}catch(c){return v(Me,`Failed to parse refreshed Gist state: ${I(c)}`),this.staleness={source:"cache",reason:`Gist refresh succeeded but payload was invalid: ${I(c)}`,lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1}Xs(i,this.state,"Gist state"),this.tryReconcilePRCounts(),this.unpushed=!1;let a=new Date;if(this.lastSuccessfulRefreshAt=a.toISOString(),this.staleness=null,this.refreshCount++,o&&!t.force){let c="A Gist refresh replaced local state that still had un-pushed changes; they were NOT synced. Re-run the command that made the change.";v(Me,c),this.staleness={reason:c,source:"cache",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:a.toISOString()}}}else this.gistStore.lastRefreshError&&(this.staleness={source:"cache",reason:I(this.gistStore.lastRefreshError),lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()});return n}getStateStaleness(){return this.staleness}setLastDigest(t){this.state.lastDigest=t,this.state.lastDigestAt=t.generatedAt,this.autoSave()}setLastStrategyAt(t){this.state.lastStrategyAt=t,this.autoSave()}setMonthlyMergedCounts(t){this.state.monthlyMergedCounts=t,this.autoSave()}setMonthlyClosedCounts(t){this.state.monthlyClosedCounts=t,this.autoSave()}setMonthlyOpenedCounts(t){this.state.monthlyOpenedCounts=t,this.autoSave()}setLocalRepoCache(t){this.state.localRepoCache=t,this.autoSave()}getMergedPRs(){return this.state.mergedPRs??[]}addMergedPRs(t){if(t.length===0)return{added:0,dropped:0};let{valid:r,dropped:n}=C$(t,"merged"),s=r.map(c=>this.withPick(c));if(s.length===0)return{added:0,dropped:n};this.state.mergedPRs||(this.state.mergedPRs=[]);let o=new Map(this.state.mergedPRs.map(c=>[c.url,c])),i=[],a=!1;for(let c of s){let u=o.get(c.url);u?a=P$(u,c)||a:(i.push(c),o.set(c.url,c))}return i.length===0&&!a?{added:0,dropped:n}:(this.state.mergedPRs.push(...i),this.state.mergedPRs.sort((c,u)=>u.mergedAt.localeCompare(c.mergedAt)),O(Me,`Added ${i.length} merged PRs (total: ${this.state.mergedPRs.length})`),this.autoSave(),{added:i.length,dropped:n})}withPick(t){if(!t.issueUrl||t.pick)return t;let r=t.issueUrl.toLowerCase(),n=this.getPickSnapshots().find(s=>s.issueUrl.toLowerCase()===r);return n?{...t,pick:n}:t}getMergedPRWatermark(){return this.state.mergedPRs?.[0]?.mergedAt||void 0}getClosedPRs(){return this.state.closedPRs??[]}addClosedPRs(t){if(t.length===0)return{added:0,dropped:0};let{valid:r,dropped:n}=C$(t,"closed"),s=r.map(c=>this.withPick(c));if(s.length===0)return{added:0,dropped:n};this.state.closedPRs||(this.state.closedPRs=[]);let o=new Map(this.state.closedPRs.map(c=>[c.url,c])),i=[],a=!1;for(let c of s){let u=o.get(c.url);u?a=P$(u,c)||a:(i.push(c),o.set(c.url,c))}return i.length===0&&!a?{added:0,dropped:n}:(this.state.closedPRs.push(...i),this.state.closedPRs.sort((c,u)=>u.closedAt.localeCompare(c.closedAt)),O(Me,`Added ${i.length} closed PRs (total: ${this.state.closedPRs.length})`),this.autoSave(),{added:i.length,dropped:n})}getClosedPRWatermark(){return this.state.closedPRs?.[0]?.closedAt||void 0}markPRCommentsFetched(t,r){let n=this.state.mergedPRs?.find(o=>o.url===t);if(n){n.commentsFetchedAt=r,this.autoSave();return}let s=this.state.closedPRs?.find(o=>o.url===t);s&&(s.commentsFetchedAt=r,this.autoSave())}setLedgerResponse(t,r,n){let s=this.state.mergedPRs?.find(o=>o.url===t)??this.state.closedPRs?.find(o=>o.url===t);s&&(r===void 0?delete s.firstMaintainerResponseAt:s.firstMaintainerResponseAt=r,s.responseRule=n,this.autoSave())}markPRLearningsExtracted(t,r){let n=this.state.mergedPRs?.find(o=>o.url===t);if(n){n.learningsExtractedAt=r,this.autoSave();return}let s=this.state.closedPRs?.find(o=>o.url===t);s&&(s.learningsExtractedAt=r,this.autoSave())}updateConfig(t){this.state.config={...this.state.config,...t},this.autoSave()}addIssue(t){let r=We(t.url),n=this.state.activeIssues.find(s=>r?We(s.url)===r:s.url===t.url);if(n){n.status=t.status,n.updatedAt=t.updatedAt,O(Me,`Issue ${t.url} already tracked; refreshed claim stamp to ${t.updatedAt}`),this.autoSave();return}this.state.activeIssues.push(t),O(Me,`Added issue: ${t.repo}#${t.number}`),this.autoSave()}releaseIssue(t,r){let n=We(t),s=this.state.activeIssues.findIndex(i=>n?We(i.url)===n:i.url===t);if(s===-1)return O(Me,`releaseIssue: ${t} is not tracked; nothing to release`),"not_tracked";let o=this.state.activeIssues[s];if(r!==void 0){let i=Date.parse(o.updatedAt),a=Date.parse(r);if(Number.isNaN(i)||Number.isNaN(a)||i>=a)return O(Me,`releaseIssue: keeping ${o.repo}#${o.number}; claim stamp ${o.updatedAt} is not before ${r}`),"newer_claim"}return this.state.activeIssues.splice(s,1),O(Me,`Released issue claim: ${o.repo}#${o.number}`),this.autoSave(),"released"}addTrustedProject(t){this.state.config.trustedProjects.includes(t)||(this.state.config.trustedProjects.push(t),O(Me,`Added trusted project: ${t}`),this.autoSave())}static matchesExclusion(t,r,n){let s=t.toLowerCase();return!!(r.some(o=>o.toLowerCase()===s)||n?.some(o=>o.toLowerCase()===s.split("/",1)[0]))}cleanupExcludedData(t,r){let n=i=>e.matchesExclusion(i,t,r),s=this.state.config.trustedProjects.length;this.state.config.trustedProjects=this.state.config.trustedProjects.filter(i=>!n(i));let o=s-this.state.config.trustedProjects.length;o>0&&(O(Me,`Removed ${o} trusted project(s) for excluded repos/orgs`),this.autoSave())}getStarredRepos(){return this.state.config.starredRepos||[]}setStarredRepos(t){this.state.config.starredRepos=t,this.state.config.starredReposLastFetched=new Date().toISOString(),O(Me,`Updated starred repos: ${t.length} repositories`),this.autoSave()}isStarredReposStale(){let t=this.state.config.starredReposLastFetched;if(!t)return!0;let r=1440*60*1e3,n=new Date(t);return new Date().getTime()-n.getTime()>r}shelvePR(t){return this.state.config.shelvedPRUrls||(this.state.config.shelvedPRUrls=[]),this.state.config.shelvedPRUrls.includes(t)?!1:(this.state.config.shelvedPRUrls.push(t),this.autoSave(),!0)}unshelvePR(t){if(!this.state.config.shelvedPRUrls)return!1;let r=this.state.config.shelvedPRUrls.indexOf(t);return r===-1?!1:(this.state.config.shelvedPRUrls.splice(r,1),this.autoSave(),!0)}isPRShelved(t){return this.state.config.shelvedPRUrls?.includes(t)??!1}dismissIssue(t,r,n={}){return this.state.config.dismissedIssues||(this.state.config.dismissedIssues={}),t in this.state.config.dismissedIssues&&!n.refresh?!1:(this.state.config.dismissedIssues[t]=r,this.setDismissedPRHead(t,n.headSha),this.autoSave(),!0)}undismissIssue(t){return!this.state.config.dismissedIssues||!(t in this.state.config.dismissedIssues)?!1:(delete this.state.config.dismissedIssues[t],this.setDismissedPRHead(t,void 0),this.autoSave(),!0)}getIssueDismissedAt(t){return this.state.config.dismissedIssues?.[t]}getDismissedPRHead(t){return this.state.config.dismissedPRHeads?.[t]}setDismissedPRHead(t,r){this.state.config.dismissedPRHeads||(this.state.config.dismissedPRHeads={}),r===void 0?delete this.state.config.dismissedPRHeads[t]:this.state.config.dismissedPRHeads[t]=r}getPickSnapshots(){return this.state.pickSnapshots??[]}recordPickSnapshots(t){let r=new Set(this.getPickSnapshots().map(s=>s.issueUrl.toLowerCase())),n=t.filter(s=>{let o=s.issueUrl.toLowerCase();return r.has(o)?!1:(r.add(o),!0)});n.length!==0&&(this.state.pickSnapshots=[...this.getPickSnapshots(),...n].slice(-M1),this.autoSave())}getSearchSeen(){return this.state.searchSeen??[]}setSearchSeen(t){this.state.searchSeen=t,this.autoSave()}getOvernightReportDocument(){let t=this.gistStore?.getDocument(k$)??null;return t===""?null:t}setOvernightReportDocument(t){this.gistStore?.setDocument(k$,t)}getLastOvernight(){return this.state.lastOvernight}setLastOvernight(t){this.state.lastOvernight=t,this.autoSave()}getSearchRotation(){return this.state.searchRotation}setSearchRotation(t){this.state.searchRotation=t,this.autoSave()}getWorkClaims(){return this.state.workClaims??[]}getActiveWorkClaims(t=Date.now()){return cr(this.getWorkClaims(),t)}pruneWorkClaims(t){let r=this.getWorkClaims();for(let n of r)Number.isFinite(Date.parse(n.expiresAt))||v(Me,`Pruning work claim on ${n.url} (session ${n.session}): expiresAt "${n.expiresAt}" is not a date`);return cr(r,t)}upsertWorkClaim(t,r=Date.now()){let n=Yt(t.url),s=this.pruneWorkClaims(r),o=s.some(i=>Yt(i.url)===n);return this.state.workClaims=[...s.filter(i=>Yt(i.url)!==n),t],this.autoSave(),o}finishWorkClaim(t,r,n=Date.now()){let s=Yt(t),o=this.pruneWorkClaims(n),i=o.find(c=>Yt(c.url)===s);if(!i)return;let a=Zp(i,r);return this.state.workClaims=o.map(c=>c===i?a:c),this.autoSave(),a}releaseWorkClaims(t,r=Date.now()){let n=t.url===void 0?void 0:Yt(t.url),s=a=>n!==void 0&&Yt(a.url)!==n||t.session!==void 0&&a.session!==t.session?!1:t.kind===void 0||a.kind===t.kind,o=this.pruneWorkClaims(r),i=o.filter(a=>s(a)).map(a=>a.url);return i.length>0&&(this.state.workClaims=o.filter(a=>!s(a)),this.autoSave()),i}setStatusOverride(t,r,n){this.state.config.statusOverrides||(this.state.config.statusOverrides={}),this.state.config.statusOverrides[t]={status:r,setAt:new Date().toISOString(),lastActivityAt:n},this.autoSave()}clearStatusOverride(t){return!this.state.config.statusOverrides||!(t in this.state.config.statusOverrides)?!1:(delete this.state.config.statusOverrides[t],this.autoSave(),!0)}getStatusOverride(t,r){let n=this.state.config.statusOverrides?.[t];if(n){if(r&&r>n.lastActivityAt){this.clearStatusOverride(t);return}return n}}getRepoScore(t){return QA(this.state,t)}updateRepoScore(t,r){DS(this.state,t,r),this.autoSave()}getReposWithMergedPRs(){return XA(this.state)}getReposWithOpenPRs(){return eT(this.state)}getHighScoringRepos(t){return tT(this.state,t)}getLowScoringRepos(t){return rT(this.state,t)}getStats(){return iT(this.state)}renameRepo(t,r){oT(this.state,t,r),this.autoSave()}reconcilePRCounts(){let t=this.state.mergedPRs??[],r=this.state.closedPRs??[];if(t.length===0&&r.length===0)return;nT(this.state,t,r)&&this.autoSave()}},Sn=null,oo=null});async function Kr(e,t,r){let n=0,s=!1,o=async()=>{for(;n<e.length&&!s;){let a=e[n++];try{await t(a)}catch(c){throw s=!0,c}}},i=Math.min(r,e.length);await Promise.all(Array.from({length:i},()=>o()))}function _m(e){let t=e.filter(n=>n.status==="rejected");if(t.length===0)return;throw(t.find(n=>de(n.reason))??t[0]).reason}var vr,is=A(()=>{"use strict";ee();vr=5});async function je(e,t=100,r=10){let n=[];for(let s=1;s<=r;s++){let{data:o}=await e(s);if(n.push(...o),o.length<t)return{items:n,truncated:!1}}return{items:n,truncated:!0}}async function vm(e,t=100,r=10){let{items:n}=await je(e,t,r);return n}var io=A(()=>{"use strict"});function as(){return f_||(f_=new Su),f_}async function ra(e,t,r){let n=e.getInflight(t);if(n)return O(_n,`Dedup hit for ${t}`),await n;let o=(async()=>{let a={},c=e.get(t);c&&(a["if-none-match"]=c.etag);try{let u=await r(a),d=u.headers?.etag;return d&&e.set(t,d,u.data),u.data}catch(u){if(j1(u)){let d=e.get(t);if(d)return O(_n,`304 cache hit for ${t}`),d.body}throw u}})(),i=e.setInflight(t,o);try{return await o}finally{i()}}function j1(e){return Ue(e)===304}var vt,Ru,T$,_n,G1,U1,Su,f_,_u=A(()=>{"use strict";vt=B(require("node:fs"),1),Ru=B(require("node:path"),1),T$=B(require("node:crypto"),1);Vr();ce();ee();_n="http-cache",G1=1440*60*1e3,U1=2e3,Su=class{cacheDir;maxEntries;inflightRequests=new Map;constructor(t,r=U1){this.cacheDir=t??Xp(),this.maxEntries=r}keyFor(t){return T$.createHash("sha256").update(t).digest("hex")}pathFor(t){return Ru.join(this.cacheDir,`${this.keyFor(t)}.json`)}getIfFresh(t,r){let n=this.get(t);if(!n)return null;let s=Date.now()-new Date(n.cachedAt).getTime();return!Number.isFinite(s)||s<0||s>r?null:n.body}get(t){let r=this.pathFor(t);try{let n=vt.readFileSync(r,"utf8"),s=JSON.parse(n);return s.url!==t?(O(_n,`Cache collision detected for ${t}, ignoring`),null):s}catch(n){if(n&&typeof n=="object"&&n.code!=="ENOENT"){let s=n instanceof Error?n.message:"unknown error";O(_n,`Cache read failed for ${t} (treating as miss): ${s}`)}return null}}set(t,r,n){let s={etag:r,url:t,body:n,cachedAt:new Date().toISOString()};try{vt.writeFileSync(this.pathFor(t),JSON.stringify(s),{encoding:"utf8",mode:384}),O(_n,`Cached response for ${t}`),this.evictIfExceeds(this.maxEntries)}catch(o){O(_n,`Failed to write cache for ${t}`,o)}}evictIfExceeds(t){if(!(t<=0))try{let r=vt.readdirSync(this.cacheDir).filter(i=>i.endsWith(".json"));if(r.length<=t)return;let n=r.map(i=>{let a=Ru.join(this.cacheDir,i);try{return{fullPath:a,mtimeMs:vt.statSync(a).mtimeMs}}catch{return null}}).filter(i=>i!==null).sort((i,a)=>i.mtimeMs-a.mtimeMs),s=n.length-t,o=0;for(let i=0;i<s;i++)try{vt.unlinkSync(n[i].fullPath),o++}catch{}o>0&&O(_n,`Capped cache at ${t} entries: evicted ${o} oldest`)}catch{}}hasInflight(t){return this.inflightRequests.has(t)}getInflight(t){return this.inflightRequests.get(t)}setInflight(t,r){return this.inflightRequests.set(t,r),()=>{this.inflightRequests.delete(t)}}evictStale(t=G1){let r=0;try{let n=vt.readdirSync(this.cacheDir),s=Date.now();for(let o of n){if(!o.endsWith(".json"))continue;let i=Ru.join(this.cacheDir,o);try{let a=vt.readFileSync(i,"utf8"),c=JSON.parse(a);s-new Date(c.cachedAt).getTime()>t&&(vt.unlinkSync(i),r++)}catch{try{vt.unlinkSync(i),r++}catch{}}}}catch{}return r>0&&O(_n,`Evicted ${r} stale cache entries`),r}clear(){try{let t=vt.readdirSync(this.cacheDir);for(let r of t)r.endsWith(".json")&&vt.unlinkSync(Ru.join(this.cacheDir,r));O(_n,"Cache cleared")}catch{}}size(){try{return vt.readdirSync(this.cacheDir).filter(t=>t.endsWith(".json")).length}catch{return 0}}},f_=null});function km(){return{status:"unknown",failingCheckNames:[],failingCheckConclusions:new Map}}function Cm(e,t,r){if(r==="cancelled"||r==="timed_out")return"infrastructure";if(r==="action_required")return"auth_gate";let n=e.toLowerCase();if(O$.some(s=>s.test(n)))return"auth_gate";if($$.some(s=>s.test(n)))return"fork_limitation";if(I$.some(s=>s.test(n)))return"infrastructure";if(t){let s=t.toLowerCase();if(O$.some(o=>o.test(s)))return"auth_gate";if($$.some(o=>o.test(s)))return"fork_limitation";if(I$.some(o=>o.test(s)))return"infrastructure"}return"actionable"}function vu(e,t){return e.map(r=>{let n=t?.get(r);return{name:r,category:Cm(r,void 0,n),conclusion:n}})}function g_(e){let{ciStatus:t,failingCheckNames:r,classifiedChecks:n}=e;if(t==="passing")return{category:"all_passing",summary:"All checks passing",action:"none"};if(t==="pending"){let s=r.length;return{category:"blocked",summary:s>0?`${s} pending check(s); CI run incomplete`:"CI checks pending",action:"request_rerun"}}if(t==="failing"){let s=n.filter(a=>a.category==="actionable");if(s.length>0){let a=s.slice(0,3).map(u=>u.name).join(", "),c=s.length>3?` (+${s.length-3} more)`:"";return{category:"failing",summary:`${s.length} actionable failure(s): ${a}${c}`,action:"investigate"}}return n.length===0?{category:"failing",summary:"CI reported failure but no check details available",action:"investigate"}:n.some(a=>a.category==="infrastructure")?{category:"blocked",summary:`${n.length} non-actionable failure(s) including infrastructure issues; rerun may resolve`,action:"request_rerun"}:{category:"fork_limitation",summary:`${n.length} non-actionable failure(s) (fork limits / auth gates)`,action:"informational"}}return{category:"not_running",summary:"No CI checks reported",action:"check_workflows"}}function z1(e){let t=!1,r=!1,n=!1,s=[],o=new Map;for(let i of e)i.conclusion==="failure"||i.conclusion==="cancelled"||i.conclusion==="timed_out"||i.conclusion==="action_required"?(t=!0,s.push(i.name),o.set(i.name,i.conclusion)):i.conclusion===null&&i.status==="waiting"?(t=!0,s.push(i.name),o.set(i.name,"action_required")):i.conclusion===null&&i.status!=="completed"?r=!0:i.conclusion==="success"&&(n=!0);return{hasFailingChecks:t,hasPendingChecks:r,hasSuccessfulChecks:n,failingCheckNames:s,failingCheckConclusions:o}}function B1(e){let t=e.statuses.filter(c=>{let u=(c.description||"").toLowerCase();return!(c.state==="failure"&&(u.includes("authorization required")||u.includes("authorize")))}),r=t.some(c=>c.state==="failure"||c.state==="error"),n=t.some(c=>c.state==="pending"),s=t.some(c=>c.state==="success"),o;r?o="failure":n?o="pending":s||t.length===0?o="success":o=e.state;let i=e.statuses.length>0,a=[];for(let c of t)(c.state==="failure"||c.state==="error")&&a.push(c.context);return{effectiveCombinedState:o,hasStatuses:i,failingStatusNames:a}}function H1(e,t,r){let{hasFailingChecks:n,hasPendingChecks:s,hasSuccessfulChecks:o,failingCheckNames:i,failingCheckConclusions:a}=e,{effectiveCombinedState:c,hasStatuses:u,failingStatusNames:d}=t,p=[...i,...d];return n||c==="failure"||c==="error"?{status:"failing",failingCheckNames:p,failingCheckConclusions:a}:s||c==="pending"?{status:"pending",failingCheckNames:[],failingCheckConclusions:new Map}:o||c==="success"?{status:"passing",failingCheckNames:[],failingCheckConclusions:new Map}:km()}function h_(e,t){let r=new Map;for(let i of e){let a=r.get(i.name);(!a||new Date(i.started_at??0)>new Date(a.started_at??0))&&r.set(i.name,i)}let n=[...r.values()],s=z1(n),o=B1(t);return H1(s,o,n.length)}async function y_(e,t,r,n){if(!n)return km();try{let[s,o]=await Promise.all([e.repos.getCombinedStatusForRef({owner:t,repo:r,ref:n,per_page:100}),vm(c=>e.checks.listForRef({owner:t,repo:r,ref:n,per_page:100,page:c}).then(u=>({data:u.data.check_runs}))).catch(c=>{let u=Ue(c);if(u===429)throw c;if(u===403){let d=I(c).toLowerCase();if(d.includes("rate limit")||d.includes("abuse detection"))throw c}return u===404?O("pr-monitor",`Check runs 404 for ${t}/${r}@${n.slice(0,7)} (no checks configured)`):v("pr-monitor",`Non-404 error fetching check runs for ${t}/${r}@${n.slice(0,7)}: ${u??c}`),null})]),i=s.data;return h_(o??[],i)}catch(s){let o=Ue(s);if(o===401||o===403||o===429)throw s;return o===404?O("pr-monitor",`CI check 404 for ${t}/${r} (no CI configured)`):v("pr-monitor",`Failed to check CI for ${t}/${r}@${n.slice(0,7)}: ${I(s)}`),km()}}var $$,O$,I$,ku=A(()=>{"use strict";ee();ce();io();$$=[/vercel/i,/netlify/i,/\bpreview\s*deploy/i,/\bdeploy\s*preview/i,/storybook/i,/chromatic/i,/percy/i,/cloudflare pages/i,/\binternal\b(?!\s+(?:api|test|integration|smoke|unit|e2e|regression|functional))/i],O$=[/authoriz/i,/approval/i,/\bcla\b/i,/license\/cla/i,/\b(?:pr|type|require[sd]?|check|missing)[\s-]+(?:\w+[\s-]+)?labels?\b/i,/\blabeler\b/i,/\btriage\b/i],I$=[/\binstall\s*(os\s*)?dep(endenc|s\b)/i,/\bsetup\s+fail(ed|ure)?\b/i,/\bservice\s*unavailable/i,/\binfrastructure/i,/\bblacksmith\b/i,/\breadthedocs\b/i]});function Cu(e){if(e.status==="rejected")throw e.reason;return e.value}function x$(e){let t=q(e);if(!t||t.type!=="pull")throw new j(`Invalid PR URL format: ${e}`);return t}async function q1(e,t){let r={items:[],totalCount:0,pagesRead:0,incomplete:!1};for(let n=1;n<=S_;n++){let s;try{({data:s}=await e.search.issuesAndPullRequests({q:t,page:n,sort:"updated",order:"desc",per_page:w_}))}catch(o){if(de(o))throw o;return r.failure={page:n,error:o},r}if(r.pagesRead=n,r.totalCount=s.total_count,s.incomplete_results&&(r.incomplete=!0),r.items.push(...s.items),s.items.length<w_||r.items.length>=r.totalCount)break}return r}function Z1(e,t){if(t.failure)return`GitHub search for ${e} failed on page ${t.failure.page} (${Xt(t.failure.error)}); only the ${t.items.length} result(s) from the ${t.pagesRead} page(s) before it were read this run.`;if(t.items.length<t.totalCount)return`GitHub Search API reports ${t.totalCount} ${e}, but only the ${t.items.length} most recently updated were read (${t.pagesRead} page(s) of ${w_}). Older reviewed PRs are not checked this run.`}function K1(e,t){let r=`open PRs you ${e} (not authored)`,n=[],s=Z1(r,t);return s!==void 0&&n.push(s),t.incomplete&&n.push(`GitHub Search API returned incomplete results for ${r} (the search timed out server-side); some reviewed PRs may be missing this run.`),n}function J1(e,t){return(Date.parse(t.updatedAt)||0)-(Date.parse(e.updatedAt)||0)}async function D$(e,t){let r=t.githubUsername;if(!r)throw new Te("No GitHub username configured. Run setup first.");let n=new R_(t),s=[],o=new Set,i=[];for(let{qualifier:a,label:c}of V1){let u=await q1(e,`is:pr is:open is:public ${a}:${r} -author:${r}`);for(let d of u.items){if(o.has(d.html_url))continue;o.add(d.html_url);let p=n.toRef(d);p&&s.push(p)}for(let d of K1(c,u))i.push(d),v(b_,d)}return s.sort(J1),O(b_,`Found ${s.length} open PRs reviewed by @${r}`),{prs:s,warnings:i}}async function L$(e,t){let{owner:r,repo:n,number:s}=x$(t),o=await Promise.allSettled([e.pulls.get({owner:r,repo:n,pull_number:s}),je(f=>e.issues.listComments({owner:r,repo:n,page:f,issue_number:s,per_page:100})),je(f=>e.pulls.listReviews({owner:r,repo:n,page:f,pull_number:s,per_page:100})),je(f=>e.pulls.listReviewComments({owner:r,repo:n,page:f,pull_number:s,per_page:100})),je(f=>e.pulls.listCommits({owner:r,repo:n,page:f,pull_number:s,per_page:100}))]);_m(o);let i=Cu(o[0]).data,a=Cu(o[1]),c=Cu(o[2]),u=Cu(o[3]),d=Cu(o[4]),p=[];return a.truncated&&p.push("comments"),c.truncated&&p.push("reviews"),u.truncated&&p.push("review comments"),(d.items.length>=W1||d.items.at(-1)?.sha!==i.head.sha||d.truncated)&&p.push("commits"),{truncatedLists:p,pr:{headSha:i.head.sha,state:i.state,author:i.user?.login,title:i.title},comments:a.items,reviews:c.items,reviewComments:u.items,commits:d.items}}async function M$(e,t,r,n){let{owner:s,repo:o}=x$(t);try{let{data:i}=await e.repos.compareCommitsWithBasehead({owner:s,repo:o,basehead:`${r}...${n}`,per_page:1});return i.status}catch(i){if(Ue(i)===404)return"missing";throw i}}var b_,S_,w_,W1,V1,R_,__=A(()=>{"use strict";is();ee();ce();io();nt();b_="reviewed-prs",S_=3,w_=100,W1=250,V1=[{qualifier:"reviewed-by",label:"reviewed"},{qualifier:"commenter",label:"commented on"}];R_=class{constructor(t){this.config=t;this.usernameLower=t.githubUsername.toLowerCase(),this.excludedRepos=new Set((t.excludeRepos??[]).map(r=>r.toLowerCase())),this.excludedOrgs=new Set((t.excludeOrgs??[]).map(r=>r.toLowerCase()))}config;usernameLower;excludedRepos;excludedOrgs;isRepoExcluded(t,r){let n=t.toLowerCase();return Sr(t,this.config.githubUsername)||Fi(t,this.config.untrackedOrgs)?!0:this.excludedRepos.has(r.toLowerCase())||this.excludedOrgs.has(n)}toRef(t){if(!t.pull_request)return;let r=q(t.html_url);if(!r||r.type!=="pull"){v(b_,`Skipping reviewed PR with unparseable URL: ${t.html_url}`);return}let n=t.user?.login??"",s=`${r.owner}/${r.repo}`;if(!(n.toLowerCase()===this.usernameLower||this.isRepoExcluded(r.owner,s)))return{repo:s,author:n,url:t.html_url,number:r.number,title:t.title,updatedAt:t.updated_at}}}});var F$={};re(F$,{byDateDescending:()=>v_,daysBetween:()=>cs,formatRelativeTime:()=>Pu});function cs(e,t=new Date){return Math.max(0,Math.floor((t.getTime()-e.getTime())/(1e3*60*60*24)))}function Pu(e){let t=new Date(e),r=Date.now()-t.getTime();if(r<0)return"just now";let n=Math.floor(r/6e4),s=Math.floor(r/36e5),o=Math.floor(r/864e5);return n<60?`${n}m ago`:s<24?`${s}h ago`:o<30?`${o}d ago`:t.toLocaleDateString()}function v_(e){return(t,r)=>{let n=new Date(e(t)||0).getTime();return new Date(e(r)||0).getTime()-n}}var na=A(()=>{"use strict"});function X1(e,t){if(!e||!t)return!0;let r=e.toLowerCase();return Y1.has(r)?!0:r===t.toLowerCase()}function sa(e){return e?new Date(e).getTime():Number.NaN}function eB(e,t){let r=sa(e),n=sa(t);return!Number.isFinite(r)||!Number.isFinite(n)?!1:r-n>=Q1}function N$(e){let{latestCommitDate:t,latestCommitAuthor:r,contributorUsername:n}=e;if(t)return X1(r,n)?t:void 0}function G$(e,t,r){if(!e||!t||!eB(e,t))return!1;if(r){let n=sa(e),s=sa(r);if(!Number.isFinite(n)||!Number.isFinite(s)||n<s)return!1}return!0}function U$(e,t){if(!e||!t)return!1;let r=sa(e),n=sa(t);return!Number.isFinite(r)||!Number.isFinite(n)?!1:r>=n}function tB(e){let{ciStatus:t,hasMergeConflict:r,hasUnrespondedComment:n,reviewDecision:s,lastMaintainerCommentDate:o,latestChangesRequestedDate:i,hasActionableCIFailure:a=!0}=e,c=N$(e),u=[];return n&&!(s==="approved"&&(t==="passing"||t==="unknown"))&&!G$(c,o,i)&&u.push("needs_response"),s==="changes_requested"&&i&&!U$(c,i)&&u.push("needs_changes"),t==="failing"&&a&&u.push("failing_ci"),r&&u.push("merge_conflict"),u.length>0?u:void 0}function k_(e){let t=rB(e);t.status==="waiting_on_maintainer"&&e.hasMergeConflict&&(t={status:"needs_addressing",actionReason:"merge_conflict",stalenessTier:t.stalenessTier});let r=tB(e);return r?{...t,actionReasons:r}:t}function rB(e){let{ciStatus:t,hasMergeConflict:r,hasUnrespondedComment:n,reviewDecision:s,daysSinceActivity:o,daysSinceMaintainerActivity:i=o,dormantThreshold:a,approachingThreshold:c,lastMaintainerCommentDate:u,latestChangesRequestedDate:d,hasActionableCIFailure:p=!0}=e,m="active";i>=a?m="dormant":i>=c&&(m="approaching_dormant");let f=N$(e);return n?G$(f,u,d)?t==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:s==="approved"&&(t==="passing"||t==="unknown")?{status:"waiting_on_maintainer",waitReason:"pending_merge",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_response",stalenessTier:m}:s==="changes_requested"&&d?U$(f,d)?t==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_changes",stalenessTier:m}:t==="failing"?p?o>=5?{status:"waiting_on_maintainer",waitReason:"stale_ci_failure",stalenessTier:m}:{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"ci_blocked",stalenessTier:m}:r?{status:"needs_addressing",actionReason:"merge_conflict",stalenessTier:m}:s==="approved"&&(t==="passing"||t==="unknown")?{status:"waiting_on_maintainer",waitReason:"pending_merge",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"pending_review",stalenessTier:m}}var Y1,Q1,C_=A(()=>{"use strict";Y1=new Set(["autofix-ci[bot]","prettier-ci[bot]","pre-commit-ci[bot]"]),Q1=120*1e3});function kt(e,t){if(t==="Bot")return!0;let r=e.toLowerCase();return r.includes("[bot]")||r.endsWith("-bot")||r.endsWith("-robot")||nB.has(r)}function oa(e){if(!e||e.length>100||e.includes("?"))return!1;let t=e.toLowerCase();return["thanks","thank you","lgtm","looks good","will review","we'll review","we'll get to this","noted","got it","will look","will check"].some(n=>t.includes(n))}function B$(e){return e.replaceAll(/:[\w+-]+:/g," ").replaceAll(/[^\p{L}\p{N}+]+/gu," ").trim().toLowerCase()}function ao(e){let t=B$(e);return t===""||sB.has(t)}function Pm(e){return oB.has(B$(e))}function z$(e){return e.replaceAll(/\s+/g," ").trim()}function H$(e){let t=[],r=!1;for(let n of e.split(`
79
79
  `)){if(/^\s{0,3}(?:```|~~~)/.test(n)){r=!r;continue}let s=/^\s*>/.test(n)||/^(?: {4}|\t)/.test(n);!r&&!s&&t.push(n)}return t}function W$(e){return H$(e).join(`
80
80
  `).replaceAll(/`[^`\n]*`/g," ")}function ia(e,t){let r=z$(H$(t).join(`
81
81
  `)).toLowerCase();if(r.length<j$)return!1;for(let n of e.split(`
@@ -259,17 +259,17 @@ Capacity: ${t.hasCapacity?"\u2705 Ready for new work":"\u26A0\uFE0F Focus on ex
259
259
  ${t}`;let n=e.indexOf(`
260
260
  ## `,r+xv.length);return e.slice(0,r)+t+(n===-1?"":e.slice(n))}function rl(e,t){if(e.isGistMode())try{e.setOvernightReportDocument(dt.readFileSync(t,"utf8"))}catch(r){v($a,`Could not publish ${t} to the Gist: ${I(r)}`)}}function Mv(e,t){if(dt.existsSync(t))return{source:"local",content:dt.readFileSync(t,"utf8")};let r=e.getOvernightReportDocument();return r?{source:"gist",content:r}:{source:"none",content:null}}function nZ(){let e=L(),t=e.getLastOvernight();if(!t)throw new Error("No overnight run recorded yet; run `overnight` first.");return{runAt:t.runAt,reportPath:t.reportPath,...Mv(e,t.reportPath)}}function Fv(e=new Date){let t=L().getLastOvernight();if(!t)return;let r=e.getTime()-Date.parse(t.runAt),n={runAt:t.runAt,reportPath:t.reportPath,prepareCount:t.prepareCount,judgmentCount:t.judgmentCount,preparedCount:t.prepared.length,reportAvailable:Mv(L(),t.reportPath).source};return Number.isNaN(r)?{...n,runAtInvalid:!0}:{...n,ageHours:Math.max(0,Math.round(r/36e5))}}function Sf(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function n0(){return`${JSON.stringify({enabledPlugins:{"oss-autopilot@oss-autopilot":!0}},null,2)}
261
261
  `}function s0(e,t,r){let n=[e.claudePath,"-p","/oss-overnight","--permission-mode","dontAsk","--setting-sources","","--settings",r,"--allowedTools",r0,"--disallowedTools",t0,"--output-format","text"];return['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>",` <key>Label</key><string>${Nv}</string>`," <key>ProgramArguments</key>"," <array>",...n.map(s=>` <string>${Sf(s)}</string>`)," </array>"," <key>StartCalendarInterval</key>",` <dict><key>Hour</key><integer>${e.hour}</integer><key>Minute</key><integer>0</integer></dict>`,` <key>StandardOutPath</key><string>${Sf(t)}</string>`,` <key>StandardErrorPath</key><string>${Sf(t)}</string>`," <key>EnvironmentVariables</key>"," <dict>",` <key>PATH</key><string>${Sf(`${rr.dirname(process.execPath)}:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin`)}</string>`,` <key>${sm}</key><string>1</string>`," </dict>","</dict>","</plist>",""].join(`
262
- `)}function o0(e,t=process.env.PATH){let r='pass --claude-path "$(command -v claude)"';if(rr.isAbsolute(e)){if(!dt.existsSync(e))throw new Error(`--claude-path ${e} does not exist; ${r}`);return e}for(let n of(t??"").split(rr.delimiter)){if(!n)continue;let s=rr.join(n,e);if(dt.existsSync(s))return s}throw new Error(`Could not find "${e}" on PATH; ${r}`)}function iZ(e){if(!Number.isInteger(e.hour)||e.hour<0||e.hour>23)throw new Error(`--hour must be an integer 0-23, got ${e.hour}`);let t=o0(e.claudePath),r=rr.join(qx.homedir(),"Library","LaunchAgents",`${Nv}.plist`),n=rr.join(ji(),"overnight-launchd.log"),s=rr.join(ji(),"overnight-settings.json"),o=s0({hour:e.hour,claudePath:t},n,s);return e.install&&(dt.mkdirSync(rr.dirname(r),{recursive:!0}),dt.writeFileSync(r,o,{mode:420}),dt.mkdirSync(rr.dirname(s),{recursive:!0}),dt.writeFileSync(s,n0(),{mode:384})),{plist:o,plistPath:r,settingsPath:s,installed:e.install,loadCommand:`launchctl bootout gui/$(id -u) ${r} 2>/dev/null; launchctl bootstrap gui/$(id -u) ${r}`}}var dt,qx,rr,$a,Zq,Zx,Iv,Jq,xv,eZ,Nv,sZ,oZ,t0,r0,bs=A(()=>{"use strict";dt=B(require("node:fs"),1),qx=B(require("node:os"),1),rr=B(require("node:path"),1);le();ee();ce();Vr();Ea();Po();el();Ov();$a="overnight",Zq={ci_failing:{bucket:"prepare",reason:"CI is red: an agent can diagnose and prepare a fix branch"},merge_conflict:{bucket:"prepare",reason:"merge conflict: an agent can rebase in a worktree"},needs_changes:{bucket:"prepare",reason:"changes requested: an agent can prepare the requested edits"},incomplete_checklist:{bucket:"judgment",reason:"checklist incomplete: the gaps are PR-body checkboxes, which only you can edit"},needs_response:{bucket:"judgment",reason:"a maintainer is waiting on your reply"}},Zx=["javascript","typescript"];Iv="Pursue";Jq={claim:"claimed",open_pr:"have an open PR for",closed_pr:"had a PR on",merged_pr:"had a PR on"};xv="## Prepared branches (";eZ=/^(?!-)[\w./@+-]+$/;Nv="com.oss-autopilot.overnight",sZ=["clone","fetch","worktree","checkout","switch","branch","rebase","merge-base","status","diff","log","show","add","commit","rev-parse","remote"],oZ=["pr view","pr checks","pr diff","pr list","run view","run list","issue view","repo view","auth status"],t0=["Bash(git push)","Bash(git push *)","Bash(git * push)","Bash(git * push *)","Bash(gh pr create *)","Bash(gh pr comment *)","Bash(gh pr merge *)","Bash(gh pr close *)","Bash(gh pr edit *)","Bash(gh pr ready *)","Bash(gh issue create *)","Bash(gh issue comment *)","Bash(gh issue close *)","Bash(gh run rerun *)","Bash(gh api *)","Bash(npm publish)","Bash(npm publish *)","Bash(npm unpublish *)","Bash(npm deprecate *)","Bash(pnpm publish)","Bash(pnpm publish *)","Bash(npm exec)","Bash(npm exec *)","Bash(npm x)","Bash(npm x *)","Bash(npm * exec *)","Bash(pnpm dlx *)","Bash(pnpm * dlx *)","Bash(pnpm exec)","Bash(pnpm exec *)","Bash(pnpm * exec *)","Bash(node -e *)","Bash(node --eval *)","Bash(node -p *)","Bash(node -pe *)","Bash(node --print *)","Bash(node * -e *)","Bash(node * --eval *)","Bash(node * -p *)","Bash(node * -pe *)","Bash(node * --print *)","Bash(npm * x *)","Bash(node --eval=*)","Bash(node * --eval=*)","Bash(node --print=*)","Bash(node * --print=*)","AskUserQuestion"].join(","),r0=["Read","Edit","Write","Glob","Grep","Task",...sZ.flatMap(e=>[`Bash(git ${e})`,`Bash(git ${e} *)`,`Bash(git -C * ${e})`,`Bash(git -C * ${e} *)`]),...oZ.map(e=>`Bash(gh ${e} *)`),"Bash(node *)","Bash(pnpm *)","Bash(npm *)"].join(",")});var u0={};re(u0,{countIssueListItems:()=>c0,detectIssueList:()=>Eo,openInBrowser:()=>vf,parseIssueListPathFromConfig:()=>bv,runStartup:()=>lZ});function c0(e){let{availableCount:t,completedCount:r,blockedCount:n}=tn(e);return{availableCount:t,completedCount:r,blockedCount:n}}function Eo(){let e=hs();if(!e)return;let t=e.path,r=e.source,n=0,s=0,o=0,i;try{let c=nl.readFileSync(t,"utf8");({availableCount:n,completedCount:s,blockedCount:o}=c0(c))}catch(c){i=I(c),console.error(`[STARTUP] Failed to read issue list at ${t}:`,i)}let a;try{let u=L().getState().config.skippedIssuesPath;if(u){let d=Tn.isAbsolute(u)?u:Tn.resolve(Tn.dirname(t),u);nl.existsSync(d)&&(a=d,d!==u&&bf("skippedIssuesPath",d))}}catch(c){v("startup",`Could not read skippedIssuesPath from state: ${I(c)}`)}if(!a&&t){let c=Tn.join(Tn.dirname(t),"skipped-issues.md");if(nl.existsSync(c)){a=c;try{let u=L();u.getState().config.skippedIssuesPath||u.updateConfig({skippedIssuesPath:c})}catch(u){v("startup",`Could not persist auto-detected skippedIssuesPath: ${I(u)}`)}}}return{path:t,source:r,availableCount:n,completedCount:s,blockedCount:o,skippedIssuesPath:a,...i!==void 0&&{readError:i}}}function vf(e){let t,r;switch(process.platform){case"darwin":{t="open",r=[e];break}case"win32":{t="cmd",r=["/c","start","",e];break}default:{t="xdg-open",r=[e];break}}(0,a0.execFile)(t,r,n=>{n&&console.error(`[STARTUP] Failed to open dashboard in browser: ${n.message}`)})}function aZ(){let e=process.env.OSS_DASHBOARD_REOPEN_THROTTLE_MS;if(!e)return i0;let t=Number(e);return Number.isFinite(t)&&t>=0?t:i0}function cZ(e,t){if(process.env.OSS_NO_BROWSER==="1")return!1;if(!e.alreadyRunning||t===0)return!0;let r=e.lastBrowserOpenedAt;if(!r)return!0;let n=Date.parse(r);if(!Number.isFinite(n))return!0;let s=Date.now()-n;return s<0?!0:s>=t}async function uZ(e){try{let t=`http://127.0.0.1:${e}`,r=await fetch(`${t}/api/data`,{signal:AbortSignal.timeout(5e3)}),n=r.headers.get("x-csrf-token");if(await r.text().catch(()=>{}),!r.ok||!n)return console.error(`[STARTUP] Dashboard refresh returned ${r.status}: no CSRF token from /api/data`),!1;let s=await fetch(`${t}/api/refresh`,{method:"POST",headers:{Origin:`http://oss.localhost:${e}`,"X-CSRF-Token":n},signal:AbortSignal.timeout(5e3)});if(!s.ok){let o=await s.text().catch(()=>"");return console.error(`[STARTUP] Dashboard refresh returned ${s.status}: ${o}`),!1}return await s.text().catch(()=>{}),!0}catch(t){return console.error(`[STARTUP] Could not trigger dashboard refresh: ${I(t)}`),!1}}async function lZ(){let e=Wr(),t=L(),r=!1;if(!t.isSetupComplete()){let f=await Dm();if(f)try{t.initializeWithDefaults(f),r=!0}catch(g){return console.error(`[STARTUP] Auto-detected username "${f}" but failed to save config:`,I(g)),{version:e,setupComplete:!1}}else return{version:e,setupComplete:!1}}let n=await xr();if(!n)return{version:e,setupComplete:!0,authError:'GitHub authentication required. Install GitHub CLI (https://cli.github.com/) and run "gh auth login", or set GITHUB_TOKEN.'};let s=await Aa(n),o,i,a;try{let f=await Gv();f?(o=f.url,f.alreadyRunning?i=await uZ(f.port)?"refreshed":"running":i="opened",cZ(f,aZ())&&(vf(f.url),qI(f.port))):(a="Dashboard SPA assets not found. Build with: cd packages/dashboard && pnpm run build",console.error(`[STARTUP] ${a}`))}catch(f){a=`SPA dashboard launch failed: ${I(f)}`,console.error(`[STARTUP] ${a}`)}i==="opened"?s.briefSummary+=" | Dashboard opened in browser":i==="refreshed"?s.briefSummary+=" | Dashboard refreshed":i==="running"&&(s.briefSummary+=" | Dashboard running");let c=Eo(),u=process.env.OSS_DASHBOARD_BUILD_STATUS,d=u==="fresh"||u==="rebuilt"||u==="failed"||u==="missing-pnpm"?u:void 0,p=process.env.OSS_DASHBOARD_BUILD_ERROR_TAIL;return{version:e,setupComplete:!0,autoDetected:r,daily:s,dashboardUrl:o,dashboardError:a,dashboardBuildStatus:d,dashboardBuildErrorTail:(d==="failed"||d==="missing-pnpm")&&p?p:void 0,issueList:c,overnight:Fv()}}var nl,Tn,a0,i0,sl=A(()=>{"use strict";nl=B(require("node:fs"),1),Tn=B(require("node:path"),1),a0=require("node:child_process");le();ee();ce();el();Uv();Zu();Po();Ea();bs();Ea();i0=1800*1e3});var Ia,l0=A(()=>{"use strict";Ia=class{maxRequests;windowMs;timestamps=[];constructor(t){this.maxRequests=t.maxRequests,this.windowMs=t.windowMs}check(){let t=Date.now(),r=t-this.windowMs;if(this.timestamps=this.timestamps.filter(n=>n>r),this.timestamps.length>=this.maxRequests){let s=this.timestamps[0]+this.windowMs-t;return{allowed:!1,retryAfterSeconds:Math.ceil(s/1e3)}}return this.timestamps.push(t),{allowed:!0}}}});var dZ,pZ,mZ,kf,d0=A(()=>{"use strict";le();ee();ce();dZ="Gist persistence is configured but this dashboard process is running LOCAL-ONLY; changes made here will NOT sync and may be overwritten by the next successful Gist read. Recovery is retried automatically.",pZ="Gist persistence is active but the last Gist read fell back to the local cache; data shown may be stale. Recovery is retried automatically.",mZ=3e4,kf=class{constructor(t,r){this.token=t;this.module=r;this.manager=L()}token;module;manager;pendingGistSyncWarnings=[];pendingSince=0;lastRecoveryAttemptAt=0;recoveryHaltedReason=null;degradedMutationCount=0;recoveryLossNotices=[];get stateManager(){return this.manager}recordGistSyncOutcome(t){if(t===null){this.manager.refreshGeneration!==this.pendingSince&&this.convertPendingWarningsToLossNotices(),this.pendingGistSyncWarnings=[];return}this.pendingGistSyncWarnings.length===0&&(this.pendingSince=this.manager.refreshGeneration),this.pendingGistSyncWarnings.includes(t)||this.pendingGistSyncWarnings.push(t)}withPendingGistWarnings(t){let r=[...this.pendingGistSyncWarnings,...this.recoveryLossNotices];if(this.gistConfiguredButLocal()?r.push(this.recoveryHaltedReason===null?dZ:`Gist persistence is configured but recovery FAILED permanently: ${this.recoveryHaltedReason} \u2014 fix the Gist setup (check the token gist scope, or run state-show), then restart the dashboard.`):this.gistBootstrapDegraded()&&r.push(this.recoveryHaltedReason===null?pZ:`Gist persistence is degraded and recovery FAILED permanently: ${this.recoveryHaltedReason} \u2014 fix the Gist setup (check the token gist scope, or run state-show), then restart the dashboard.`),r.length===0)return t;let n=t??[];return[...n,...r.filter(s=>!n.includes(s))]}async flushPendingGistSync(){if(this.pendingGistSyncWarnings.length>0){this.recordGistSyncOutcome(await we(this.manager,this.module));return}if(!this.manager.hasUnpushedChanges())return;let t=await we(this.manager,this.module);t!==null&&(O(this.module,`Dropping un-pushed refresh data before the Gist pull: ${t}`),this.manager.forgetUnpushedChanges())}probeGistHealth(){try{return this.manager.getGistHealth()}catch(t){return v(this.module,`Degraded-gist probe failed (treating as not degraded): ${I(t)}`),null}}gistConfiguredButLocal(){let t=this.probeGistHealth();return t!==null&&t.mode==="local"&&t.degraded!==null}gistBootstrapDegraded(){let t=this.probeGistHealth();return t!==null&&t.mode==="gist"&&t.degraded!==null}convertPendingWarningsToLossNotices(){this.pendingGistSyncWarnings.length!==0&&(this.recoveryLossNotices.push(`A Gist read replaced local state while ${this.pendingGistSyncWarnings.length} change(s) were still un-pushed \u2014 they were NOT synced to the Gist and may have been reverted in this view. Re-apply anything missing.`),this.pendingGistSyncWarnings=[])}async pullFromGist(t={}){let r=await this.manager.refreshFromGist(t);return r&&this.convertPendingWarningsToLossNotices(),r}async maybeRecoverGist(){if(this.probeGistHealth()?.degraded==null||this.recoveryHaltedReason!==null)return;let t=Date.now();if(t-this.lastRecoveryAttemptAt<mZ)return;let r=this.token||Pn();if(r){this.lastRecoveryAttemptAt=t;try{await ta(r);let n=this.manager;this.manager=L(),this.manager!==n&&this.pendingGistSyncWarnings.length>0&&(this.pendingSince=this.manager.refreshGeneration);let s=this.manager.getGistHealth(),o=s.mode==="gist"&&s.degraded===null;o&&this.convertPendingWarningsToLossNotices(),o&&this.degradedMutationCount>0&&(this.recoveryLossNotices.push(`Gist persistence recovered, but ${this.degradedMutationCount} change(s) made while degraded were saved locally only and were NOT merged into the Gist \u2014 they may have been reverted in this view. Re-apply anything missing.`),this.degradedMutationCount=0)}catch(n){n instanceof Te&&(this.recoveryHaltedReason=I(n)),v(this.module,`Gist recovery attempt failed: ${I(n)}`)}}}unhaltRecovery(){this.recoveryHaltedReason=null}recordMutationWhileDegraded(){this.gistConfiguredButLocal()&&this.degradedMutationCount++}clearRecoveryLossNotices(){this.recoveryLossNotices=[]}}});function gZ(e){try{let t=Eo();if(!t)return null;let r=Ef.readFileSync(t.path,"utf8");return tn(r)}catch(t){return v(fZ,`Failed to read vetted issue list: ${I(t)}`),e?.push("read vetted issue list"),null}}function Cf(){try{let e=Eo();return e?Ef.statSync(e.path).mtimeMs:null}catch{return null}}function jv(e,t,r,n,s,o){let i=[...o??[]],a={...e,openPRs:Yr(e.openPRs||[],t,i),summary:{...e.summary}};XI(a,t);let c=tx(a,t),u=rx(c),{monthlyMerged:d,monthlyOpened:p,monthlyClosed:m}=nx(t),f=n??mv(L().getMergedPRs()),g=s??fv(L().getClosedPRs()),h=t.config.minStars??50,b=t.repoScores||{},w=T=>!qr(b[T.repo]?.stargazersCount,h),y=f.filter(w),S=g.filter(w),k=QI(a,t,y.length,S.length),R=t.config.dismissedIssues||{},P=r.filter(T=>{if(T.status!=="new_response")return!1;let M=R[T.url];return!M||!ya(M,T.lastResponseAt)}),C={};for(let[T,M]of Object.entries(b))(M.stargazersCount!==void 0||M.language!==void 0)&&(C[T]={stars:M.stargazersCount,language:M.language});let E=gZ(i);return E&&(k.availableIssues=E.availableCount),{stats:k,prsByRepo:c,topRepos:u.map(([T,M])=>({repo:T,...M})),monthlyMerged:d,monthlyOpened:p,monthlyClosed:m,activePRs:(a.openPRs||[]).map(T=>({...T,attentionBucket:Uu(T)})),shelvedPRUrls:(a.shelvedPRs||[]).map(T=>T.url),recentlyMergedPRs:a.recentlyMergedPRs||[],recentlyClosedPRs:a.recentlyClosedPRs||[],autoUnshelvedPRs:a.autoUnshelvedPRs||[],commentedIssues:r,issueResponses:P,allMergedPRs:y,allClosedPRs:S,repoMetadata:C,vettedIssues:E,partialFailures:i.length>0?[...new Set(i)]:void 0}}var Ef,fZ,Pf,zv=A(()=>{"use strict";Ef=B(require("node:fs"),1);le();ee();ce();ff();sl();Po();ts();fZ="dashboard-server";Pf=class{constructor(t,r){this.mergeWarnings=r;this.cachedDigest=t,this.cachedIssueListMtimeMs=Cf()}mergeWarnings;cachedDigest;cachedCommentedIssues=[];cachedPartialFailures=void 0;cachedJsonData;cachedIssueListMtimeMs;lastBackgroundRefreshError=null;get digest(){return this.cachedDigest}get jsonData(){return this.cachedJsonData}get issueListMtimeMs(){return this.cachedIssueListMtimeMs}adoptFetchResult(t){this.cachedDigest=t.digest,this.cachedCommentedIssues=t.commentedIssues,this.cachedPartialFailures=t.partialFailures.length>0?t.partialFailures:void 0}adoptNewerPulledDigest(t){t&&Date.parse(t.generatedAt)>Date.parse(this.cachedDigest.generatedAt)&&(this.cachedDigest=t)}rebuild(t,r,n,s){this.cachedJsonData=jv(this.cachedDigest,t,this.cachedCommentedIssues,r,n,this.mergeWarnings(this.cachedPartialFailures)),this.cachedIssueListMtimeMs=s===void 0?Cf():s}}});var Vv={};re(Vv,{VALID_TARGETS:()=>Wv,runMove:()=>hZ});function Hv(e,t){return t?{...e,gistSyncWarning:t}:e}async function hZ(e){Ze(e.prUrl),Qe(e.prUrl,tr,"PR");let t=e.target;if(!Wv.includes(t))throw new j(`Invalid target "${e.target}". Must be one of: ${Wv.join(", ")}`);let r=L();switch(t){case"attention":case"waiting":{let n=t==="attention"?"needs_addressing":"waiting_on_maintainer",s=t==="attention"?"Need Attention":"Waiting on Maintainer",o=new Date().toISOString(),i=()=>r.batch(()=>{r.setStatusOverride(e.prUrl,n,o),r.unshelvePR(e.prUrl)});i();let a=await we(r,Bv,i);return Hv({url:e.prUrl,target:t,description:`Moved to ${s}`},a)}case"shelved":{let n=()=>r.batch(()=>{r.shelvePR(e.prUrl),r.clearStatusOverride(e.prUrl)});n();let s=await we(r,Bv,n);return Hv({url:e.prUrl,target:t,description:"Shelved \u2014 excluded from capacity and actionable items"},s)}case"auto":{let n=()=>r.batch(()=>{r.clearStatusOverride(e.prUrl),r.unshelvePR(e.prUrl)});n();let s=await we(r,Bv,n);return Hv({url:e.prUrl,target:t,description:"Reset to computed status"},s)}default:{let n=t;throw new Error(`Unhandled move target: ${n}`)}}}var Bv,Wv,qv=A(()=>{"use strict";le();ee();Ot();Bv="move",Wv=["attention","waiting","shelved","auto"]});var Af={};re(Af,{runDismiss:()=>yZ,runUndismiss:()=>bZ});async function yZ(e){Ze(e.url),Qe(e.url,Ku,"issue or PR");let t=tr.test(e.url);if(!t&&e.head!==void 0)throw new j("--head applies to PR URLs only: a dismissed issue has no head commit");let r=L(),n=new Date().toISOString(),s={refresh:t,...e.head!==void 0&&{headSha:YI(e.head)}},o=r.dismissIssue(e.url,n,s),i=await we(r,p0,()=>r.dismissIssue(e.url,n,s));return{dismissed:o,url:e.url,...i&&{gistSyncWarning:i}}}async function bZ(e){Ze(e.url),Qe(e.url,Ku,"issue or PR");let t=L(),r=t.undismissIssue(e.url),n=await we(t,p0,()=>t.undismissIssue(e.url));return{undismissed:r,url:e.url,...n&&{gistSyncWarning:n}}}var p0,Tf=A(()=>{"use strict";le();ee();Ot();p0="dismiss"});var S0={};re(S0,{buildDashboardJson:()=>jv,findRunningDashboardServer:()=>pf,getDashboardPidPath:()=>Wu,isDashboardServerRunning:()=>qu,readDashboardServerInfo:()=>Ro,removeDashboardServerInfo:()=>fs,startDashboardServer:()=>kZ,writeDashboardServerInfo:()=>Vu});function _Z(e,t=wZ){return new Promise((r,n)=>{let s=[],o=0,i=!1;e.on("data",a=>{if(!i){if(o+=a.length,o>t){i=!0,e.destroy(),n(new Error("Body too large"));return}s.push(a)}}),e.on("end",()=>{i||r(Buffer.concat(s).toString("utf8"))}),e.on("error",a=>{i||n(a)})})}function w0(e){e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("X-Frame-Options","DENY"),e.setHeader("Content-Security-Policy","default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'; worker-src 'self' blob:"),e.setHeader("Referrer-Policy","strict-origin-when-cross-origin")}function R0(e){return[`localhost:${e}`,`127.0.0.1:${e}`,`oss.localhost:${e}`]}function f0(e,t){let r=e.headers.origin;return typeof r!="string"?!1:R0(t).map(s=>`http://${s}`).includes(r)}function vZ(e,t){let r=e.headers.host;return typeof r!="string"?!1:R0(t).includes(r)}function g0(e,t){let r=e.headers["x-csrf-token"];if(typeof r!="string"||r.length!==t.length)return!1;try{return Of.timingSafeEqual(Buffer.from(r),Buffer.from(t))}catch{return!1}}function ol(e,t,r){w0(e),e.setHeader("Cache-Control","no-store");let n=JSON.stringify(r);e.writeHead(t,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(n)}),e.end(n)}function Ge(e,t,r){ol(e,t,{error:r})}function h0(e){return e.replaceAll(/[\r\n]+/g," ").trim()}function Zv(e){return e instanceof Tr||e instanceof Qt}function y0(e){ol(e,409,{error:"Another process wrote state concurrently \u2014 retry the request",code:"CONCURRENCY_ERROR",retryable:!0})}async function kZ(e){let{port:t,assetsDir:r,token:n,open:s}=e,o=new kf(n,wt),i=$n.resolve(r),a=Of.randomBytes(32).toString("hex"),c=o.stateManager.getState().lastDigest;if(!c)throw new Error("No dashboard data available. Run the daily check first: oss-autopilot daily (or /oss in Claude Code)");let u=new Pf(c,C=>o.withPendingGistWarnings(C));try{u.rebuild(o.stateManager.getState())}catch(C){throw new Error(`Failed to build dashboard data: ${I(C)}. State data may be corrupted \u2014 try running: daily --json`,{cause:C})}let d=new Ia({maxRequests:30,windowMs:6e4}),p=new Ia({maxRequests:10,windowMs:6e4}),m=new Ia({maxRequests:6,windowMs:6e4}),f=b0.createServer(async(C,E)=>{let T=C.method||"GET",M=C.url||"/";try{if(M.startsWith("/api/")&&!vZ(C,k)){Ge(E,403,"Invalid host");return}if(M==="/api/data"&&T==="GET"){let G=d.check();if(!G.allowed){E.setHeader("Retry-After",String(G.retryAfterSeconds)),Ge(E,429,"Too many requests");return}E.setHeader("X-CSRF-Token",a);let X=await g(),ve=Cf(),he=ve!==u.issueListMtimeMs;if(X||he)try{u.rebuild(o.stateManager.getState(),void 0,void 0,ve)}catch(oe){v(wt,`Failed to rebuild dashboard data after state reload: ${I(oe)}`),E.setHeader("X-Dashboard-Stale","1")}h(E),ol(E,200,u.jsonData);return}if(M==="/api/action"&&T==="POST"){let G=p.check();if(!G.allowed){E.setHeader("Retry-After",String(G.retryAfterSeconds)),Ge(E,429,"Too many requests");return}if(!f0(C,k)){Ge(E,403,"Invalid origin");return}if(!g0(C,a)){Ge(E,403,"Missing or invalid CSRF token");return}await b(C,E);return}if(M==="/api/refresh"&&T==="POST"){let G=m.check();if(!G.allowed){E.setHeader("Retry-After",String(G.retryAfterSeconds)),Ge(E,429,"Too many requests");return}if(!f0(C,k)){Ge(E,403,"Invalid origin");return}if(!g0(C,a)){Ge(E,403,"Missing or invalid CSRF token");return}await w(C,E);return}if(T==="GET"){y(M,E);return}Ge(E,405,"Method not allowed")}catch(G){v(wt,`Unhandled request error: ${T} ${M} ${I(G)}`),E.headersSent||Ge(E,500,"Internal server error")}});f.requestTimeout=RZ;async function g(C={}){if(o.stateManager.isGistMode()){await o.flushPendingGistSync();let T=await o.pullFromGist(C);return T&&u.adoptNewerPulledDigest(o.stateManager.getState().lastDigest),o.gistBootstrapDegraded()&&(await o.maybeRecoverGist(),!o.gistBootstrapDegraded())?!0:T}let E=o.stateManager.reloadIfChanged();return E&&o.unhaltRecovery(),await o.maybeRecoverGist(),o.stateManager.isGistMode()&&(E=!0),E}function h(C){let E=o.stateManager.getStateStaleness();E!==null&&(C.setHeader("X-Dashboard-Stale","1"),C.setHeader("X-Dashboard-Stale-Reason",h0(`state-stale: ${E.reason}`))),u.lastBackgroundRefreshError!==null&&(C.setHeader("X-Dashboard-Stale","1"),C.setHeader("X-Dashboard-Stale-Reason",h0(`background-refresh-failed: ${u.lastBackgroundRefreshError}`)))}async function b(C,E){let T;try{let he=await _Z(C);T=JSON.parse(he)}catch(he){let oe=he instanceof Error&&he.message==="Body too large";Ge(E,oe?413:400,oe?"Request body too large":"Invalid JSON body");return}if(!T.action||!m0.has(T.action)){Ge(E,400,`Invalid action. Must be one of: ${[...m0].join(", ")}`);return}if(!T.url||typeof T.url!="string"){Ge(E,400,'Missing or invalid "url" field');return}let M=T.action==="dismiss_issue_response";try{Ze(T.url),Qe(T.url,M?dr:tr,M?"issue":"PR")}catch(he){he instanceof j?Ge(E,400,he.message):(v(wt,`Unexpected error during URL validation: ${I(he)}`),Ge(E,400,"Invalid URL"));return}let G=null,X;if(T.action==="move"){let{VALID_TARGETS:he,runMove:oe}=await Promise.resolve().then(()=>(qv(),Vv));if(!T.target||!he.includes(T.target)){Ge(E,400,`move requires a valid "target" field (${he.join(", ")})`);return}let Z=T.target;X=async()=>{G=(await oe({prUrl:T.url,target:Z})).gistSyncWarning??null}}else{let{runDismiss:he}=await Promise.resolve().then(()=>(Tf(),Af));X=async()=>{G=(await he({url:T.url})).gistSyncWarning??null}}await g();let ve=o.stateManager;try{await ve.runMutation(async()=>X())}catch(he){if(!Zv(he)){v(wt,`Action failed: ${T.action} ${T.url} ${I(he)}`),Ge(E,500,"Action failed");return}try{await g({force:!0}),await ve.runMutation(async()=>X())}catch(oe){if(Zv(oe)){v(wt,`Action conflicted twice: ${T.action} ${T.url} ${I(oe)}`),y0(E);return}v(wt,`Action failed on conflict retry: ${T.action} ${T.url} ${I(oe)}`),Ge(E,500,"Action failed");return}}o.recordGistSyncOutcome(G),o.recordMutationWhileDegraded(),u.rebuild(o.stateManager.getState()),h(E),ol(E,200,u.jsonData)}async function w(C,E){let T=n||Pn();if(!T){Ge(E,401,"No GitHub token available. Cannot refresh data.");return}try{o.clearRecoveryLossNotices(),await g(),v(wt,"Refreshing dashboard data from GitHub...");let M=await pv(T);u.adoptFetchResult(M),u.rebuild(o.stateManager.getState(),M.allMergedPRs,M.allClosedPRs),u.lastBackgroundRefreshError=null,h(E),ol(E,200,u.jsonData)}catch(M){if(Zv(M)){v(wt,`Dashboard refresh hit a concurrent state write: ${I(M)}`),y0(E);return}v(wt,`Dashboard refresh failed: ${I(M)}`),Ge(E,500,"Refresh failed")}}function y(C,E){let T;try{T=decodeURIComponent(C.split("?",1)[0])}catch{v(wt,`Malformed URL received: ${C}`),Ge(E,400,"Malformed URL");return}if(T.includes("..")){Ge(E,403,"Forbidden");return}let M=T==="/"?"index.html":T.replace(/^\/+/,""),G=$n.join(i,M);if(!G.startsWith(i+$n.sep)&&G!==i){Ge(E,403,"Forbidden");return}let X=T.startsWith("/assets/"),ve=$n.join(i,"index.html");try{$f.statSync(G).isDirectory()&&(G=ve)}catch($e){if($e.code==="ENOENT"){if(X){Ge(E,404,"Not found");return}G=ve}else{v(wt,`Failed to stat file: ${G}`),Ge(E,500,"Internal server error");return}}let he=$n.extname(G).toLowerCase(),oe=SZ[he]||"application/octet-stream",Z=X&&G!==ve?"public, max-age=3600":"no-cache";try{let $e=$f.readFileSync(G);w0(E),E.writeHead(200,{"Content-Type":oe,"Content-Length":$e.length,"Cache-Control":Z}),E.end($e)}catch($e){$e.code==="ENOENT"?Ge(E,404,"Not found"):(v(wt,`Failed to serve static file: ${G}`),Ge(E,500,"Failed to read file"))}}let S=10,k=t;for(let C=0;C<S;C++)try{await new Promise((E,T)=>{f.once("error",T),f.listen(k,"127.0.0.1",()=>E())});break}catch(E){let T=E;if(T.code==="EADDRINUSE"&&C<S-1){v(wt,`Port ${k} is in use, trying ${k+1}...`),k++;continue}throw new Error(`Failed to start server: ${T.message}`,{cause:E})}Vu({pid:process.pid,port:k,startedAt:new Date().toISOString(),version:Wr()});let R=`http://oss.localhost:${k}`;v(wt,`Dashboard server running at ${R} (also: http://localhost:${k})`),n&&pv(n).then(async C=>{o.clearRecoveryLossNotices(),o.stateManager.isGistMode()?(await o.flushPendingGistSync(),await o.pullFromGist(),o.gistBootstrapDegraded()&&await o.maybeRecoverGist()):(o.stateManager.reloadIfChanged(),await o.maybeRecoverGist()),u.adoptFetchResult(C),u.rebuild(o.stateManager.getState(),C.allMergedPRs,C.allClosedPRs),u.lastBackgroundRefreshError=null,v(wt,"Background data refresh complete")}).catch(C=>{u.lastBackgroundRefreshError=I(C),v(wt,`Background data refresh failed (serving cached data): ${u.lastBackgroundRefreshError}`)}),s&&vf(R);let P=()=>{v(wt,"Shutting down dashboard server..."),fs(),f.close(()=>{process.exit(0)}),setTimeout(()=>process.exit(0),3e3).unref()};process.on("SIGINT",P),process.on("SIGTERM",P)}var b0,$f,$n,Of,m0,wt,wZ,RZ,SZ,_0=A(()=>{"use strict";b0=B(require("node:http"),1),$f=B(require("node:fs"),1),$n=B(require("node:path"),1),Of=B(require("node:crypto"),1);le();ee();ce();Ot();ff();sl();Zu();l0();d0();zv();zv();Zu();m0=new Set(["move","dismiss_issue_response"]),wt="dashboard-server",wZ=10240,RZ=3e4,SZ={".html":"text/html",".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".json":"application/json",".png":"image/png",".ico":"image/x-icon"}});var v0={};re(v0,{resolveAssetsDir:()=>If,serveDashboard:()=>CZ});function If(){let e=pr.resolve(__dirname,"../../dashboard/dist");if(il.existsSync(pr.join(e,"index.html")))return e;let t=pr.resolve(pr.dirname(process.argv[1]),"../../dashboard/dist");if(il.existsSync(pr.join(t,"index.html")))return t;let r=pr.resolve(__dirname,"dashboard");if(il.existsSync(pr.join(r,"index.html")))return r;try{let n=require.resolve("@oss-autopilot/dashboard/package.json"),s=pr.join(pr.dirname(n),"dist");if(il.existsSync(pr.join(s,"index.html")))return s}catch(n){n.code!=="MODULE_NOT_FOUND"&&console.error("Error resolving dashboard package:",n)}return null}async function CZ(e){let t=If();t||(console.error("Could not find dashboard SPA assets."),console.error("From a git checkout, build them: cd packages/dashboard && pnpm run build"),console.error("From npm, update to the latest @oss-autopilot/core; older releases did not include them."),process.exit(1));let r=Pn(),{startDashboardServer:n}=await Promise.resolve().then(()=>(_0(),S0));await n({port:e.port,assetsDir:t,token:r,open:e.open})}var il,pr,Kv=A(()=>{"use strict";il=B(require("node:fs"),1),pr=B(require("node:path"),1);le()});var E0={};re(E0,{launchDashboardServer:()=>Gv,resolveCliEntry:()=>P0,stopStaleDashboardServer:()=>Jv});function P0(e,t){if(/^cli\.(?:bundle\.cjs|ts|js)$/.test(xf.basename(e)))return e;let r=xf.resolve(t,"../../core/dist/cli.bundle.cjs");return C0.existsSync(r)?r:e}function TZ(e){return new Promise(t=>setTimeout(t,e))}async function Jv(){let e=await pf();if(!e)return null;let t=Ro();if(!t)return null;let r={url:e.url,port:e.port,alreadyRunning:!0,lastBrowserOpenedAt:t.lastBrowserOpenedAt},n=Wr();if(!t.version||n==="0.0.0"||t.version===n)return r;console.error(`[DASHBOARD] Dashboard server version mismatch (running: ${t.version}, current: ${n}). Stopping it...`);try{process.kill(t.pid,"SIGTERM")}catch(s){if(s.code!=="ESRCH")return console.error(`[DASHBOARD] Could not kill outdated dashboard (PID ${t.pid}): ${s.message}`),r}return fs(),null}async function Gv(e){let t=If();if(!t)return await Jv(),null;let r=await Jv();if(r)return r;let n=e?.port??PZ,s=P0(process.argv[1],t),o=(0,k0.spawn)("node",[s,"dashboard","serve","--port",String(n),"--no-open"],{detached:!0,stdio:"ignore"}),i=!1,a=!1;o.on("error",c=>{i=!0,console.error(`[STARTUP] Failed to spawn dashboard server: ${c.message}`)}),o.on("exit",c=>{a=!0,c!==0&&c!==null&&console.error(`[STARTUP] Dashboard server exited prematurely (code ${c})`)}),o.unref();for(let c=0;c<AZ;c++){if(await TZ(EZ),i||a)return null;let u=Ro();if(u&&await qu(u.port))return{url:`http://oss.localhost:${u.port}`,port:u.port,alreadyRunning:!1}}if(console.error("[STARTUP] Dashboard server failed to start within 5 seconds"),o.pid)try{process.kill(o.pid,"SIGTERM")}catch(c){c.code!=="ESRCH"&&console.error(`[STARTUP] Failed to kill orphan dashboard process (PID ${o.pid}): ${c.message}`)}return null}var k0,C0,xf,PZ,EZ,AZ,Uv=A(()=>{"use strict";k0=require("node:child_process"),C0=B(require("node:fs"),1),xf=B(require("node:path"),1);Zu();Kv();le();PZ=3e3,EZ=200,AZ=25});var A0={};re(A0,{runStatus:()=>$Z});async function $Z(e){let t=L(),r=t.getStats(),n=t.getState(),s=n.lastDigestAt||n.lastRunAt,{totalTracked:o,...i}=r,a={stats:i,lastRunAt:n.lastRunAt};e.offline&&(a.offline=!0,a.lastUpdated=s);let c=t.getStateStaleness();return c&&(a.warnings=[An(c)]),a}var T0=A(()=>{"use strict";le();me()});var $0={};re($0,{runStrategy:()=>IZ});async function IZ(){let t=L().getState(),r=gs(t);if(r===null){let n=t.mergedPRs?.length??0;return{strategy:null,message:`Strategy snapshot needs at least ${10} merged PRs in local state; currently tracking ${n}. Keep contributing and the snapshot becomes available automatically.`}}return{strategy:r}}var O0=A(()=>{"use strict";le();Ju()});var Lf={};re(Lf,{runStateShow:()=>DZ,runStateSync:()=>MZ,runStateUnlink:()=>FZ});async function DZ(e={}){let t=L(),r=t.getState(),n={persistence:r.config.persistence??"local",gistId:r.gistId??null,gistDegraded:t.isGistDegraded(),lastRunAt:r.lastRunAt};return e.validate&&(n.invalidEntries=LZ(t)),n}function LZ(e){let t=[];for(let r of e.getMergedPRs())q(r.url)===null&&t.push({kind:"merged",url:r.url,title:r.title});for(let r of e.getClosedPRs())q(r.url)===null&&t.push({kind:"closed",url:r.url,title:r.title});return t}async function MZ(){let e=L();if(!e.isGistMode())return{pushed:!1,gistId:null};if(!await e.checkpoint())throw new Error("Failed to push state to Gist after retry. Check network connectivity and token permissions.");return{pushed:!0,gistId:e.getState().gistId??null}}async function FZ(){let e=L(),r=e.getState().gistId??null,n=jt();e.isGistMode()&&await e.refreshFromGist();let s=JSON.parse(JSON.stringify(e.getState()));delete s.gistId,s.config.persistence="local",Or(n,JSON.stringify(s,null,2),384);let o=Qs();try{Df.existsSync(o)&&Df.unlinkSync(o)}catch(i){v(xZ,`Failed to remove gist-id file: ${i}`)}return Sm(),{unlinked:!0,localStatePath:n,previousGistId:r}}var Df,xZ,Mf=A(()=>{"use strict";Df=B(require("node:fs"),1);os();pu();Vr();nt();ce();xZ="state-cmd"});function NZ(e){let t=new Map,r=e.lastDigest?.openPRs;if(!r)return t;for(let n of r){let s=n.repo.toLowerCase();t.set(s,(t.get(s)??0)+1)}return t}function GZ(e,t){let r=t.toLowerCase(),s=Object.entries(e.repoScores??{}).find(([o])=>o.toLowerCase()===r)?.[1]?.mergedPRCount??0;return s>0?s:(e.mergedPRs??[]).filter(o=>{let i=q(o.url);return i!==null&&`${i.owner}/${i.repo}`.toLowerCase()===r}).length}function UZ(e,t){let{maxOpenPRsPerRepo:r=0,maxOpenPRsColdRepo:n=0}=e,s=[r,t?n:0].filter(o=>o>0);return s.length>0?Math.min(...s):0}function jZ(e){let t=[];if(e.excluded&&t.push(`${e.repo} is in excludeRepos`),e.atCap){let r=e.cold?" for a repo where none of your PRs have merged yet":"";t.push(`${e.repo} has ${e.openPRCount} open PR(s), at the cap of ${e.cap}${r}`)}return t.length>0?t.join("; "):void 0}function Ff(e,t,r){let n=e.config??{},s=r?.openPRCount??NZ(e).get(t.toLowerCase())??0,o=GZ(e,t),i=o===0,a=UZ(n,i),c={repo:t,openPRCount:s,countSource:r?"github":"digest",mergedPRCount:o,cold:i,cap:a,atCap:a>0&&s>=a,excluded:(n.excludeRepos??[]).some(d=>d.toLowerCase()===t.toLowerCase())},u=jZ(c);return u?{...c,reason:u}:c}function Nf(e){let t=e.lastDigest?.openPRs;if(!t)return[];let r=new Set,n=[];for(let s of t){let o=s.repo.toLowerCase();r.has(o)||(r.add(o),Ff(e,s.repo).atCap&&n.push(s.repo))}return n}function Gf(e,t){let r=Ff(e,t);return r.reason?{repoCap:r}:{}}var xa=A(()=>{"use strict";nt()});function jf(e){Uf=e}function x0(){return Uf}function D0(){Uf="debug"}function Yv(e){return I0[Uf]>=I0[e]}function se(e,t,...r){if(!Yv("debug"))return;let n=new Date().toISOString();console.error(`[${n}] [DEBUG] [${e}] ${t}`,...r)}function ze(e,t,...r){if(!Yv("info"))return;let n=new Date().toISOString();console.error(`[${n}] [INFO] [${e}] ${t}`,...r)}function H(e,t,...r){if(!Yv("warn"))return;let n=new Date().toISOString();console.error(`[${n}] [WARN] [${e}] ${t}`,...r)}var I0,Uf,pt=A(()=>{I0={silent:0,warn:1,info:2,debug:3},Uf="info"});function Y(e){return e instanceof Error?e.message:String(e)}function Me(e){if(e&&typeof e=="object"&&"status"in e){let t=e.status;return typeof t=="number"&&Number.isFinite(t)?t:void 0}}function L0(e){let t=Me(e);return t===401?!0:t===403&&!mt(e)}function mt(e){let t=e?.errors;if(Array.isArray(t)&&t.some(n=>n?.type==="RATE_LIMITED"))return!0;let r=Me(e);if(r===429)return!0;if(r===403){let n=Y(e).toLowerCase();return n.includes("rate limit")||n.includes("abuse detection")}return!1}function Be(e){if(Me(e)===401||mt(e))throw e}var zf,Da,ot,ft=A(()=>{zf=class extends Error{code;constructor(t,r){super(t),this.code=r,this.name="OssScoutError"}},Da=class extends zf{constructor(t){super(t,"CONFIGURATION_ERROR"),this.name="ConfigurationError"}},ot=class extends zf{strategiesUsed;constructor(t,r){super(t,"VALIDATION_ERROR"),this.strategiesUsed=r,this.name="ValidationError"}}});function mr(e){return new Promise(t=>setTimeout(t,e))}function Rs(){let e=Bf.join(N0.homedir(),".oss-scout");return ws.existsSync(e)||ws.mkdirSync(e,{recursive:!0,mode:448}),e}function U0(){let e=Bf.join(Rs(),"cache");return ws.existsSync(e)||ws.mkdirSync(e,{recursive:!0,mode:448}),e}function it(e){let t;try{t=new URL(e)}catch{return null}let r=t.hostname.toLowerCase().replace(/^www\./,""),n=t.pathname.split("/").filter(Boolean);return r==="api.github.com"?n[0]==="repos"&&n.length>=3?`${n[1]}/${n[2]}`:null:r==="github.com"&&n.length>=2?`${n[0]}/${n[1]}`:null}function HZ(e,t){return zZ.test(e)&&BZ.test(t)}function Ao(e){let t=/^(?:www\.)?github\.com\//i.test(e)?`https://${e}`:e,r;try{r=new URL(t)}catch{return null}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.hostname.toLowerCase().replace(/^www\./,"")!=="github.com")return null;let s=r.pathname.split("/").filter(Boolean);if(s.length!==4)return null;let[o,i,a,c]=s;return a!=="pull"&&a!=="issues"||!HZ(o,i)||!/^\d+$/.test(c)?null:{owner:o,repo:i,number:parseInt(c,10),type:a}}function Ma(e,t=new Date){return Math.max(0,Math.floor((t.getTime()-e.getTime())/(1e3*60*60*24)))}function Qv(){if(La)return La;if(F0)return null;F0=!0;let e=process.env.GITHUB_TOKEN?.trim();if(e)return La=e,La;try{let t=(0,G0.execFileSync)("gh",["auth","token"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:2e3}).trim();if(t&&t.length>0)return La=t,se(M0,"Using GitHub token from gh CLI"),La}catch(t){se(M0,`gh auth token failed: ${Y(t)}`)}return null}function j0(){let e=Qv();if(!e)throw new Da(`GitHub authentication required.
262
+ `)}function o0(e,t=process.env.PATH){let r='pass --claude-path "$(command -v claude)"';if(rr.isAbsolute(e)){if(!dt.existsSync(e))throw new Error(`--claude-path ${e} does not exist; ${r}`);return e}for(let n of(t??"").split(rr.delimiter)){if(!n)continue;let s=rr.join(n,e);if(dt.existsSync(s))return s}throw new Error(`Could not find "${e}" on PATH; ${r}`)}function iZ(e){if(!Number.isInteger(e.hour)||e.hour<0||e.hour>23)throw new Error(`--hour must be an integer 0-23, got ${e.hour}`);let t=o0(e.claudePath),r=rr.join(qx.homedir(),"Library","LaunchAgents",`${Nv}.plist`),n=rr.join(ji(),"overnight-launchd.log"),s=rr.join(ji(),"overnight-settings.json"),o=s0({hour:e.hour,claudePath:t},n,s);return e.install&&(dt.mkdirSync(rr.dirname(r),{recursive:!0}),dt.writeFileSync(r,o,{mode:420}),dt.mkdirSync(rr.dirname(s),{recursive:!0}),dt.writeFileSync(s,n0(),{mode:384})),{plist:o,plistPath:r,settingsPath:s,installed:e.install,loadCommand:`launchctl bootout gui/$(id -u) ${r} 2>/dev/null; launchctl bootstrap gui/$(id -u) ${r}`}}var dt,qx,rr,$a,Zq,Zx,Iv,Jq,xv,eZ,Nv,sZ,oZ,t0,r0,bs=A(()=>{"use strict";dt=B(require("node:fs"),1),qx=B(require("node:os"),1),rr=B(require("node:path"),1);le();ee();ce();Vr();Ea();Po();el();Ov();$a="overnight",Zq={ci_failing:{bucket:"prepare",reason:"CI is red: an agent can diagnose and prepare a fix branch"},merge_conflict:{bucket:"prepare",reason:"merge conflict: an agent can rebase in a worktree"},needs_changes:{bucket:"prepare",reason:"changes requested: an agent can prepare the requested edits"},incomplete_checklist:{bucket:"judgment",reason:"checklist incomplete: the gaps are PR-body checkboxes, which only you can edit"},needs_response:{bucket:"judgment",reason:"a maintainer is waiting on your reply"}},Zx=["javascript","typescript"];Iv="Pursue";Jq={claim:"claimed",open_pr:"have an open PR for",closed_pr:"had a PR on",merged_pr:"had a PR on"};xv="## Prepared branches (";eZ=/^(?!-)[\w./@+-]+$/;Nv="com.oss-autopilot.overnight",sZ=["clone","fetch","worktree","checkout","switch","branch","rebase","merge-base","status","diff","log","show","add","commit","rev-parse","remote"],oZ=["pr view","pr checks","pr diff","pr list","run view","run list","issue view","repo view","auth status"],t0=["Bash(git push)","Bash(git push *)","Bash(git * push)","Bash(git * push *)","Bash(gh pr create *)","Bash(gh pr comment *)","Bash(gh pr merge *)","Bash(gh pr close *)","Bash(gh pr edit *)","Bash(gh pr ready *)","Bash(gh issue create *)","Bash(gh issue comment *)","Bash(gh issue close *)","Bash(gh run rerun *)","Bash(gh api *)","Bash(npm publish)","Bash(npm publish *)","Bash(npm unpublish *)","Bash(npm deprecate *)","Bash(pnpm publish)","Bash(pnpm publish *)","Bash(npm exec)","Bash(npm exec *)","Bash(npm x)","Bash(npm x *)","Bash(npm * exec *)","Bash(pnpm dlx *)","Bash(pnpm * dlx *)","Bash(pnpm exec)","Bash(pnpm exec *)","Bash(pnpm * exec *)","Bash(node -e *)","Bash(node --eval *)","Bash(node -p *)","Bash(node -pe *)","Bash(node --print *)","Bash(node * -e *)","Bash(node * --eval *)","Bash(node * -p *)","Bash(node * -pe *)","Bash(node * --print *)","Bash(npm * x *)","Bash(node --eval=*)","Bash(node * --eval=*)","Bash(node --print=*)","Bash(node * --print=*)","AskUserQuestion"].join(","),r0=["Read","Edit","Write","Glob","Grep","Task",...sZ.flatMap(e=>[`Bash(git ${e})`,`Bash(git ${e} *)`,`Bash(git -C * ${e})`,`Bash(git -C * ${e} *)`]),...oZ.map(e=>`Bash(gh ${e} *)`),"Bash(node *)","Bash(pnpm *)","Bash(npm *)"].join(",")});var u0={};re(u0,{countIssueListItems:()=>c0,detectIssueList:()=>Eo,openInBrowser:()=>vf,parseIssueListPathFromConfig:()=>bv,runStartup:()=>lZ});function c0(e){let{availableCount:t,completedCount:r,blockedCount:n}=tn(e);return{availableCount:t,completedCount:r,blockedCount:n}}function Eo(){let e=hs();if(!e)return;let t=e.path,r=e.source,n=0,s=0,o=0,i;try{let c=nl.readFileSync(t,"utf8");({availableCount:n,completedCount:s,blockedCount:o}=c0(c))}catch(c){i=I(c),console.error(`[STARTUP] Failed to read issue list at ${t}:`,i)}let a;try{let u=L().getState().config.skippedIssuesPath;if(u){let d=Tn.isAbsolute(u)?u:Tn.resolve(Tn.dirname(t),u);nl.existsSync(d)&&(a=d,d!==u&&bf("skippedIssuesPath",d))}}catch(c){v("startup",`Could not read skippedIssuesPath from state: ${I(c)}`)}if(!a&&t){let c=Tn.join(Tn.dirname(t),"skipped-issues.md");if(nl.existsSync(c)){a=c;try{let u=L();u.getState().config.skippedIssuesPath||u.updateConfig({skippedIssuesPath:c})}catch(u){v("startup",`Could not persist auto-detected skippedIssuesPath: ${I(u)}`)}}}return{path:t,source:r,availableCount:n,completedCount:s,blockedCount:o,skippedIssuesPath:a,...i!==void 0&&{readError:i}}}function vf(e){let t,r;switch(process.platform){case"darwin":{t="open",r=[e];break}case"win32":{t="cmd",r=["/c","start","",e];break}default:{t="xdg-open",r=[e];break}}(0,a0.execFile)(t,r,n=>{n&&console.error(`[STARTUP] Failed to open dashboard in browser: ${n.message}`)})}function aZ(){let e=process.env.OSS_DASHBOARD_REOPEN_THROTTLE_MS;if(!e)return i0;let t=Number(e);return Number.isFinite(t)&&t>=0?t:i0}function cZ(e,t){if(process.env.OSS_NO_BROWSER==="1")return!1;if(!e.alreadyRunning||t===0)return!0;let r=e.lastBrowserOpenedAt;if(!r)return!0;let n=Date.parse(r);if(!Number.isFinite(n))return!0;let s=Date.now()-n;return s<0?!0:s>=t}async function uZ(e){try{let t=`http://127.0.0.1:${e}`,r=await fetch(`${t}/api/data`,{signal:AbortSignal.timeout(5e3)}),n=r.headers.get("x-csrf-token");if(await r.text().catch(()=>{}),!r.ok||!n)return console.error(`[STARTUP] Dashboard refresh returned ${r.status}: no CSRF token from /api/data`),!1;let s=await fetch(`${t}/api/refresh`,{method:"POST",headers:{Origin:`http://oss.localhost:${e}`,"X-CSRF-Token":n},signal:AbortSignal.timeout(5e3)});if(!s.ok){let o=await s.text().catch(()=>"");return console.error(`[STARTUP] Dashboard refresh returned ${s.status}: ${o}`),!1}return await s.text().catch(()=>{}),!0}catch(t){return console.error(`[STARTUP] Could not trigger dashboard refresh: ${I(t)}`),!1}}async function lZ(){let e=Wr(),t=L(),r=!1;if(!t.isSetupComplete()){let f=await Dm();if(f)try{t.initializeWithDefaults(f),r=!0}catch(g){return console.error(`[STARTUP] Auto-detected username "${f}" but failed to save config:`,I(g)),{version:e,setupComplete:!1}}else return{version:e,setupComplete:!1}}let n=await xr();if(!n)return{version:e,setupComplete:!0,authError:'GitHub authentication required. Install GitHub CLI (https://cli.github.com/) and run "gh auth login", or set GITHUB_TOKEN.'};let s=await Aa(n),o,i,a;try{let f=await Gv();f?(o=f.url,f.alreadyRunning?i=await uZ(f.port)?"refreshed":"running":i="opened",cZ(f,aZ())&&(vf(f.url),qI(f.port))):(a="Dashboard SPA assets not found. Build with: cd packages/dashboard && pnpm run build",console.error(`[STARTUP] ${a}`))}catch(f){a=`SPA dashboard launch failed: ${I(f)}`,console.error(`[STARTUP] ${a}`)}i==="opened"?s.briefSummary+=" | Dashboard opened in browser":i==="refreshed"?s.briefSummary+=" | Dashboard refreshed":i==="running"&&(s.briefSummary+=" | Dashboard running");let c=Eo(),u=process.env.OSS_DASHBOARD_BUILD_STATUS,d=u==="fresh"||u==="rebuilt"||u==="failed"||u==="missing-pnpm"?u:void 0,p=process.env.OSS_DASHBOARD_BUILD_ERROR_TAIL;return{version:e,setupComplete:!0,autoDetected:r,daily:s,dashboardUrl:o,dashboardError:a,dashboardBuildStatus:d,dashboardBuildErrorTail:(d==="failed"||d==="missing-pnpm")&&p?p:void 0,issueList:c,overnight:Fv()}}var nl,Tn,a0,i0,sl=A(()=>{"use strict";nl=B(require("node:fs"),1),Tn=B(require("node:path"),1),a0=require("node:child_process");le();ee();ce();el();Uv();Zu();Po();Ea();bs();Ea();i0=1800*1e3});var Ia,l0=A(()=>{"use strict";Ia=class{maxRequests;windowMs;timestamps=[];constructor(t){this.maxRequests=t.maxRequests,this.windowMs=t.windowMs}check(){let t=Date.now(),r=t-this.windowMs;if(this.timestamps=this.timestamps.filter(n=>n>r),this.timestamps.length>=this.maxRequests){let s=this.timestamps[0]+this.windowMs-t;return{allowed:!1,retryAfterSeconds:Math.ceil(s/1e3)}}return this.timestamps.push(t),{allowed:!0}}}});var dZ,pZ,mZ,kf,d0=A(()=>{"use strict";le();ee();ce();dZ="Gist persistence is configured but this dashboard process is running LOCAL-ONLY; changes made here will NOT sync and may be overwritten by the next successful Gist read. Recovery is retried automatically.",pZ="Gist persistence is active but the last Gist read fell back to the local cache; data shown may be stale. Recovery is retried automatically.",mZ=3e4,kf=class{constructor(t,r){this.token=t;this.module=r;this.manager=L()}token;module;manager;pendingGistSyncWarnings=[];pendingSince=0;lastRecoveryAttemptAt=0;recoveryHaltedReason=null;degradedMutationCount=0;recoveryLossNotices=[];get stateManager(){return this.manager}recordGistSyncOutcome(t){if(t===null){this.manager.refreshGeneration!==this.pendingSince&&this.convertPendingWarningsToLossNotices(),this.pendingGistSyncWarnings=[];return}this.pendingGistSyncWarnings.length===0&&(this.pendingSince=this.manager.refreshGeneration),this.pendingGistSyncWarnings.includes(t)||this.pendingGistSyncWarnings.push(t)}withPendingGistWarnings(t){let r=[...this.pendingGistSyncWarnings,...this.recoveryLossNotices];if(this.gistConfiguredButLocal()?r.push(this.recoveryHaltedReason===null?dZ:`Gist persistence is configured but recovery FAILED permanently: ${this.recoveryHaltedReason} \u2014 fix the Gist setup (check the token gist scope, or run state-show), then restart the dashboard.`):this.gistBootstrapDegraded()&&r.push(this.recoveryHaltedReason===null?pZ:`Gist persistence is degraded and recovery FAILED permanently: ${this.recoveryHaltedReason} \u2014 fix the Gist setup (check the token gist scope, or run state-show), then restart the dashboard.`),r.length===0)return t;let n=t??[];return[...n,...r.filter(s=>!n.includes(s))]}async flushPendingGistSync(){if(this.pendingGistSyncWarnings.length>0){this.recordGistSyncOutcome(await we(this.manager,this.module));return}if(!this.manager.hasUnpushedChanges())return;let t=await we(this.manager,this.module);t!==null&&(O(this.module,`Dropping un-pushed refresh data before the Gist pull: ${t}`),this.manager.forgetUnpushedChanges())}probeGistHealth(){try{return this.manager.getGistHealth()}catch(t){return v(this.module,`Degraded-gist probe failed (treating as not degraded): ${I(t)}`),null}}gistConfiguredButLocal(){let t=this.probeGistHealth();return t!==null&&t.mode==="local"&&t.degraded!==null}gistBootstrapDegraded(){let t=this.probeGistHealth();return t!==null&&t.mode==="gist"&&t.degraded!==null}convertPendingWarningsToLossNotices(){this.pendingGistSyncWarnings.length!==0&&(this.recoveryLossNotices.push(`A Gist read replaced local state while ${this.pendingGistSyncWarnings.length} change(s) were still un-pushed \u2014 they were NOT synced to the Gist and may have been reverted in this view. Re-apply anything missing.`),this.pendingGistSyncWarnings=[])}async pullFromGist(t={}){let r=await this.manager.refreshFromGist(t);return r&&this.convertPendingWarningsToLossNotices(),r}async maybeRecoverGist(){if(this.probeGistHealth()?.degraded==null||this.recoveryHaltedReason!==null)return;let t=Date.now();if(t-this.lastRecoveryAttemptAt<mZ)return;let r=this.token||Pn();if(r){this.lastRecoveryAttemptAt=t;try{await ta(r);let n=this.manager;this.manager=L(),this.manager!==n&&this.pendingGistSyncWarnings.length>0&&(this.pendingSince=this.manager.refreshGeneration);let s=this.manager.getGistHealth(),o=s.mode==="gist"&&s.degraded===null;o&&this.convertPendingWarningsToLossNotices(),o&&this.degradedMutationCount>0&&(this.recoveryLossNotices.push(`Gist persistence recovered, but ${this.degradedMutationCount} change(s) made while degraded were saved locally only and were NOT merged into the Gist \u2014 they may have been reverted in this view. Re-apply anything missing.`),this.degradedMutationCount=0)}catch(n){n instanceof Te&&(this.recoveryHaltedReason=I(n)),v(this.module,`Gist recovery attempt failed: ${I(n)}`)}}}unhaltRecovery(){this.recoveryHaltedReason=null}recordMutationWhileDegraded(){this.gistConfiguredButLocal()&&this.degradedMutationCount++}clearRecoveryLossNotices(){this.recoveryLossNotices=[]}}});function gZ(e){try{let t=Eo();if(!t)return null;let r=Ef.readFileSync(t.path,"utf8");return tn(r)}catch(t){return v(fZ,`Failed to read vetted issue list: ${I(t)}`),e?.push("read vetted issue list"),null}}function Cf(){try{let e=Eo();return e?Ef.statSync(e.path).mtimeMs:null}catch{return null}}function jv(e,t,r,n,s,o){let i=[...o??[]],a={...e,openPRs:Yr(e.openPRs||[],t,i),summary:{...e.summary}};XI(a,t);let c=tx(a,t),u=rx(c),{monthlyMerged:d,monthlyOpened:p,monthlyClosed:m}=nx(t),f=n??mv(L().getMergedPRs()),g=s??fv(L().getClosedPRs()),h=t.config.minStars??50,b=t.repoScores||{},w=T=>!qr(b[T.repo]?.stargazersCount,h),y=f.filter(w),S=g.filter(w),k=QI(a,t,y.length,S.length),R=t.config.dismissedIssues||{},P=r.filter(T=>{if(T.status!=="new_response")return!1;let M=R[T.url];return!M||!ya(M,T.lastResponseAt)}),C={};for(let[T,M]of Object.entries(b))(M.stargazersCount!==void 0||M.language!==void 0)&&(C[T]={stars:M.stargazersCount,language:M.language});let E=gZ(i);return E&&(k.availableIssues=E.availableCount),{stats:k,prsByRepo:c,topRepos:u.map(([T,M])=>({repo:T,...M})),monthlyMerged:d,monthlyOpened:p,monthlyClosed:m,activePRs:(a.openPRs||[]).map(T=>({...T,attentionBucket:Uu(T)})),shelvedPRUrls:(a.shelvedPRs||[]).map(T=>T.url),recentlyMergedPRs:a.recentlyMergedPRs||[],recentlyClosedPRs:a.recentlyClosedPRs||[],autoUnshelvedPRs:a.autoUnshelvedPRs||[],commentedIssues:r,issueResponses:P,allMergedPRs:y,allClosedPRs:S,repoMetadata:C,vettedIssues:E,partialFailures:i.length>0?[...new Set(i)]:void 0}}var Ef,fZ,Pf,zv=A(()=>{"use strict";Ef=B(require("node:fs"),1);le();ee();ce();ff();sl();Po();ts();fZ="dashboard-server";Pf=class{constructor(t,r){this.mergeWarnings=r;this.cachedDigest=t,this.cachedIssueListMtimeMs=Cf()}mergeWarnings;cachedDigest;cachedCommentedIssues=[];cachedPartialFailures=void 0;cachedJsonData;cachedIssueListMtimeMs;lastBackgroundRefreshError=null;get digest(){return this.cachedDigest}get jsonData(){return this.cachedJsonData}get issueListMtimeMs(){return this.cachedIssueListMtimeMs}adoptFetchResult(t){this.cachedDigest=t.digest,this.cachedCommentedIssues=t.commentedIssues,this.cachedPartialFailures=t.partialFailures.length>0?t.partialFailures:void 0}adoptNewerPulledDigest(t){t&&Date.parse(t.generatedAt)>Date.parse(this.cachedDigest.generatedAt)&&(this.cachedDigest=t)}rebuild(t,r,n,s){this.cachedJsonData=jv(this.cachedDigest,t,this.cachedCommentedIssues,r,n,this.mergeWarnings(this.cachedPartialFailures)),this.cachedIssueListMtimeMs=s===void 0?Cf():s}}});var Vv={};re(Vv,{VALID_TARGETS:()=>Wv,runMove:()=>hZ});function Hv(e,t){return t?{...e,gistSyncWarning:t}:e}async function hZ(e){Ze(e.prUrl),Qe(e.prUrl,tr,"PR");let t=e.target;if(!Wv.includes(t))throw new j(`Invalid target "${e.target}". Must be one of: ${Wv.join(", ")}`);let r=L();switch(t){case"attention":case"waiting":{let n=t==="attention"?"needs_addressing":"waiting_on_maintainer",s=t==="attention"?"Need Attention":"Waiting on Maintainer",o=new Date().toISOString(),i=()=>r.batch(()=>{r.setStatusOverride(e.prUrl,n,o),r.unshelvePR(e.prUrl)});i();let a=await we(r,Bv,i);return Hv({url:e.prUrl,target:t,description:`Moved to ${s}`},a)}case"shelved":{let n=()=>r.batch(()=>{r.shelvePR(e.prUrl),r.clearStatusOverride(e.prUrl)});n();let s=await we(r,Bv,n);return Hv({url:e.prUrl,target:t,description:"Shelved \u2014 excluded from capacity and actionable items"},s)}case"auto":{let n=()=>r.batch(()=>{r.clearStatusOverride(e.prUrl),r.unshelvePR(e.prUrl)});n();let s=await we(r,Bv,n);return Hv({url:e.prUrl,target:t,description:"Reset to computed status"},s)}default:{let n=t;throw new Error(`Unhandled move target: ${n}`)}}}var Bv,Wv,qv=A(()=>{"use strict";le();ee();Ot();Bv="move",Wv=["attention","waiting","shelved","auto"]});var Af={};re(Af,{runDismiss:()=>bZ,runUndismiss:()=>wZ});function yZ(e,t){let r=e.getState().lastDigest?.openPRs??[],n=t.toLowerCase(),s=r.find(o=>o.url.toLowerCase()===n);if(!(!s||e.isPRShelved(s.url)))return`${s.url} is one of your open PRs. dismiss records it but does not clear the PR from Needs Attention; run \`move ${s.url} waiting\` for that.`}async function bZ(e){Ze(e.url),Qe(e.url,Ku,"issue or PR");let t=tr.test(e.url);if(!t&&e.head!==void 0)throw new j("--head applies to PR URLs only: a dismissed issue has no head commit");let r=L(),n=new Date().toISOString(),s={refresh:t,...e.head!==void 0&&{headSha:YI(e.head)}},o=r.dismissIssue(e.url,n,s),i=await we(r,p0,()=>r.dismissIssue(e.url,n,s)),a=t?yZ(r,e.url):void 0;return{dismissed:o,url:e.url,...a&&{warning:a},...i&&{gistSyncWarning:i}}}async function wZ(e){Ze(e.url),Qe(e.url,Ku,"issue or PR");let t=L(),r=t.undismissIssue(e.url),n=await we(t,p0,()=>t.undismissIssue(e.url));return{undismissed:r,url:e.url,...n&&{gistSyncWarning:n}}}var p0,Tf=A(()=>{"use strict";le();ee();Ot();p0="dismiss"});var S0={};re(S0,{buildDashboardJson:()=>jv,findRunningDashboardServer:()=>pf,getDashboardPidPath:()=>Wu,isDashboardServerRunning:()=>qu,readDashboardServerInfo:()=>Ro,removeDashboardServerInfo:()=>fs,startDashboardServer:()=>CZ,writeDashboardServerInfo:()=>Vu});function vZ(e,t=RZ){return new Promise((r,n)=>{let s=[],o=0,i=!1;e.on("data",a=>{if(!i){if(o+=a.length,o>t){i=!0,e.destroy(),n(new Error("Body too large"));return}s.push(a)}}),e.on("end",()=>{i||r(Buffer.concat(s).toString("utf8"))}),e.on("error",a=>{i||n(a)})})}function w0(e){e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("X-Frame-Options","DENY"),e.setHeader("Content-Security-Policy","default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'; worker-src 'self' blob:"),e.setHeader("Referrer-Policy","strict-origin-when-cross-origin")}function R0(e){return[`localhost:${e}`,`127.0.0.1:${e}`,`oss.localhost:${e}`]}function f0(e,t){let r=e.headers.origin;return typeof r!="string"?!1:R0(t).map(s=>`http://${s}`).includes(r)}function kZ(e,t){let r=e.headers.host;return typeof r!="string"?!1:R0(t).includes(r)}function g0(e,t){let r=e.headers["x-csrf-token"];if(typeof r!="string"||r.length!==t.length)return!1;try{return Of.timingSafeEqual(Buffer.from(r),Buffer.from(t))}catch{return!1}}function ol(e,t,r){w0(e),e.setHeader("Cache-Control","no-store");let n=JSON.stringify(r);e.writeHead(t,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(n)}),e.end(n)}function Ge(e,t,r){ol(e,t,{error:r})}function h0(e){return e.replaceAll(/[\r\n]+/g," ").trim()}function Zv(e){return e instanceof Tr||e instanceof Qt}function y0(e){ol(e,409,{error:"Another process wrote state concurrently \u2014 retry the request",code:"CONCURRENCY_ERROR",retryable:!0})}async function CZ(e){let{port:t,assetsDir:r,token:n,open:s}=e,o=new kf(n,wt),i=$n.resolve(r),a=Of.randomBytes(32).toString("hex"),c=o.stateManager.getState().lastDigest;if(!c)throw new Error("No dashboard data available. Run the daily check first: oss-autopilot daily (or /oss in Claude Code)");let u=new Pf(c,C=>o.withPendingGistWarnings(C));try{u.rebuild(o.stateManager.getState())}catch(C){throw new Error(`Failed to build dashboard data: ${I(C)}. State data may be corrupted \u2014 try running: daily --json`,{cause:C})}let d=new Ia({maxRequests:30,windowMs:6e4}),p=new Ia({maxRequests:10,windowMs:6e4}),m=new Ia({maxRequests:6,windowMs:6e4}),f=b0.createServer(async(C,E)=>{let T=C.method||"GET",M=C.url||"/";try{if(M.startsWith("/api/")&&!kZ(C,k)){Ge(E,403,"Invalid host");return}if(M==="/api/data"&&T==="GET"){let G=d.check();if(!G.allowed){E.setHeader("Retry-After",String(G.retryAfterSeconds)),Ge(E,429,"Too many requests");return}E.setHeader("X-CSRF-Token",a);let X=await g(),ve=Cf(),he=ve!==u.issueListMtimeMs;if(X||he)try{u.rebuild(o.stateManager.getState(),void 0,void 0,ve)}catch(oe){v(wt,`Failed to rebuild dashboard data after state reload: ${I(oe)}`),E.setHeader("X-Dashboard-Stale","1")}h(E),ol(E,200,u.jsonData);return}if(M==="/api/action"&&T==="POST"){let G=p.check();if(!G.allowed){E.setHeader("Retry-After",String(G.retryAfterSeconds)),Ge(E,429,"Too many requests");return}if(!f0(C,k)){Ge(E,403,"Invalid origin");return}if(!g0(C,a)){Ge(E,403,"Missing or invalid CSRF token");return}await b(C,E);return}if(M==="/api/refresh"&&T==="POST"){let G=m.check();if(!G.allowed){E.setHeader("Retry-After",String(G.retryAfterSeconds)),Ge(E,429,"Too many requests");return}if(!f0(C,k)){Ge(E,403,"Invalid origin");return}if(!g0(C,a)){Ge(E,403,"Missing or invalid CSRF token");return}await w(C,E);return}if(T==="GET"){y(M,E);return}Ge(E,405,"Method not allowed")}catch(G){v(wt,`Unhandled request error: ${T} ${M} ${I(G)}`),E.headersSent||Ge(E,500,"Internal server error")}});f.requestTimeout=SZ;async function g(C={}){if(o.stateManager.isGistMode()){await o.flushPendingGistSync();let T=await o.pullFromGist(C);return T&&u.adoptNewerPulledDigest(o.stateManager.getState().lastDigest),o.gistBootstrapDegraded()&&(await o.maybeRecoverGist(),!o.gistBootstrapDegraded())?!0:T}let E=o.stateManager.reloadIfChanged();return E&&o.unhaltRecovery(),await o.maybeRecoverGist(),o.stateManager.isGistMode()&&(E=!0),E}function h(C){let E=o.stateManager.getStateStaleness();E!==null&&(C.setHeader("X-Dashboard-Stale","1"),C.setHeader("X-Dashboard-Stale-Reason",h0(`state-stale: ${E.reason}`))),u.lastBackgroundRefreshError!==null&&(C.setHeader("X-Dashboard-Stale","1"),C.setHeader("X-Dashboard-Stale-Reason",h0(`background-refresh-failed: ${u.lastBackgroundRefreshError}`)))}async function b(C,E){let T;try{let he=await vZ(C);T=JSON.parse(he)}catch(he){let oe=he instanceof Error&&he.message==="Body too large";Ge(E,oe?413:400,oe?"Request body too large":"Invalid JSON body");return}if(!T.action||!m0.has(T.action)){Ge(E,400,`Invalid action. Must be one of: ${[...m0].join(", ")}`);return}if(!T.url||typeof T.url!="string"){Ge(E,400,'Missing or invalid "url" field');return}let M=T.action==="dismiss_issue_response";try{Ze(T.url),Qe(T.url,M?dr:tr,M?"issue":"PR")}catch(he){he instanceof j?Ge(E,400,he.message):(v(wt,`Unexpected error during URL validation: ${I(he)}`),Ge(E,400,"Invalid URL"));return}let G=null,X;if(T.action==="move"){let{VALID_TARGETS:he,runMove:oe}=await Promise.resolve().then(()=>(qv(),Vv));if(!T.target||!he.includes(T.target)){Ge(E,400,`move requires a valid "target" field (${he.join(", ")})`);return}let Z=T.target;X=async()=>{G=(await oe({prUrl:T.url,target:Z})).gistSyncWarning??null}}else{let{runDismiss:he}=await Promise.resolve().then(()=>(Tf(),Af));X=async()=>{G=(await he({url:T.url})).gistSyncWarning??null}}await g();let ve=o.stateManager;try{await ve.runMutation(async()=>X())}catch(he){if(!Zv(he)){v(wt,`Action failed: ${T.action} ${T.url} ${I(he)}`),Ge(E,500,"Action failed");return}try{await g({force:!0}),await ve.runMutation(async()=>X())}catch(oe){if(Zv(oe)){v(wt,`Action conflicted twice: ${T.action} ${T.url} ${I(oe)}`),y0(E);return}v(wt,`Action failed on conflict retry: ${T.action} ${T.url} ${I(oe)}`),Ge(E,500,"Action failed");return}}o.recordGistSyncOutcome(G),o.recordMutationWhileDegraded(),u.rebuild(o.stateManager.getState()),h(E),ol(E,200,u.jsonData)}async function w(C,E){let T=n||Pn();if(!T){Ge(E,401,"No GitHub token available. Cannot refresh data.");return}try{o.clearRecoveryLossNotices(),await g(),v(wt,"Refreshing dashboard data from GitHub...");let M=await pv(T);u.adoptFetchResult(M),u.rebuild(o.stateManager.getState(),M.allMergedPRs,M.allClosedPRs),u.lastBackgroundRefreshError=null,h(E),ol(E,200,u.jsonData)}catch(M){if(Zv(M)){v(wt,`Dashboard refresh hit a concurrent state write: ${I(M)}`),y0(E);return}v(wt,`Dashboard refresh failed: ${I(M)}`),Ge(E,500,"Refresh failed")}}function y(C,E){let T;try{T=decodeURIComponent(C.split("?",1)[0])}catch{v(wt,`Malformed URL received: ${C}`),Ge(E,400,"Malformed URL");return}if(T.includes("..")){Ge(E,403,"Forbidden");return}let M=T==="/"?"index.html":T.replace(/^\/+/,""),G=$n.join(i,M);if(!G.startsWith(i+$n.sep)&&G!==i){Ge(E,403,"Forbidden");return}let X=T.startsWith("/assets/"),ve=$n.join(i,"index.html");try{$f.statSync(G).isDirectory()&&(G=ve)}catch($e){if($e.code==="ENOENT"){if(X){Ge(E,404,"Not found");return}G=ve}else{v(wt,`Failed to stat file: ${G}`),Ge(E,500,"Internal server error");return}}let he=$n.extname(G).toLowerCase(),oe=_Z[he]||"application/octet-stream",Z=X&&G!==ve?"public, max-age=3600":"no-cache";try{let $e=$f.readFileSync(G);w0(E),E.writeHead(200,{"Content-Type":oe,"Content-Length":$e.length,"Cache-Control":Z}),E.end($e)}catch($e){$e.code==="ENOENT"?Ge(E,404,"Not found"):(v(wt,`Failed to serve static file: ${G}`),Ge(E,500,"Failed to read file"))}}let S=10,k=t;for(let C=0;C<S;C++)try{await new Promise((E,T)=>{f.once("error",T),f.listen(k,"127.0.0.1",()=>E())});break}catch(E){let T=E;if(T.code==="EADDRINUSE"&&C<S-1){v(wt,`Port ${k} is in use, trying ${k+1}...`),k++;continue}throw new Error(`Failed to start server: ${T.message}`,{cause:E})}Vu({pid:process.pid,port:k,startedAt:new Date().toISOString(),version:Wr()});let R=`http://oss.localhost:${k}`;v(wt,`Dashboard server running at ${R} (also: http://localhost:${k})`),n&&pv(n).then(async C=>{o.clearRecoveryLossNotices(),o.stateManager.isGistMode()?(await o.flushPendingGistSync(),await o.pullFromGist(),o.gistBootstrapDegraded()&&await o.maybeRecoverGist()):(o.stateManager.reloadIfChanged(),await o.maybeRecoverGist()),u.adoptFetchResult(C),u.rebuild(o.stateManager.getState(),C.allMergedPRs,C.allClosedPRs),u.lastBackgroundRefreshError=null,v(wt,"Background data refresh complete")}).catch(C=>{u.lastBackgroundRefreshError=I(C),v(wt,`Background data refresh failed (serving cached data): ${u.lastBackgroundRefreshError}`)}),s&&vf(R);let P=()=>{v(wt,"Shutting down dashboard server..."),fs(),f.close(()=>{process.exit(0)}),setTimeout(()=>process.exit(0),3e3).unref()};process.on("SIGINT",P),process.on("SIGTERM",P)}var b0,$f,$n,Of,m0,wt,RZ,SZ,_Z,_0=A(()=>{"use strict";b0=B(require("node:http"),1),$f=B(require("node:fs"),1),$n=B(require("node:path"),1),Of=B(require("node:crypto"),1);le();ee();ce();Ot();ff();sl();Zu();l0();d0();zv();zv();Zu();m0=new Set(["move","dismiss_issue_response"]),wt="dashboard-server",RZ=10240,SZ=3e4,_Z={".html":"text/html",".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".json":"application/json",".png":"image/png",".ico":"image/x-icon"}});var v0={};re(v0,{resolveAssetsDir:()=>If,serveDashboard:()=>PZ});function If(){let e=pr.resolve(__dirname,"../../dashboard/dist");if(il.existsSync(pr.join(e,"index.html")))return e;let t=pr.resolve(pr.dirname(process.argv[1]),"../../dashboard/dist");if(il.existsSync(pr.join(t,"index.html")))return t;let r=pr.resolve(__dirname,"dashboard");if(il.existsSync(pr.join(r,"index.html")))return r;try{let n=require.resolve("@oss-autopilot/dashboard/package.json"),s=pr.join(pr.dirname(n),"dist");if(il.existsSync(pr.join(s,"index.html")))return s}catch(n){n.code!=="MODULE_NOT_FOUND"&&console.error("Error resolving dashboard package:",n)}return null}async function PZ(e){let t=If();t||(console.error("Could not find dashboard SPA assets."),console.error("From a git checkout, build them: cd packages/dashboard && pnpm run build"),console.error("From npm, update to the latest @oss-autopilot/core; older releases did not include them."),process.exit(1));let r=Pn(),{startDashboardServer:n}=await Promise.resolve().then(()=>(_0(),S0));await n({port:e.port,assetsDir:t,token:r,open:e.open})}var il,pr,Kv=A(()=>{"use strict";il=B(require("node:fs"),1),pr=B(require("node:path"),1);le()});var E0={};re(E0,{launchDashboardServer:()=>Gv,resolveCliEntry:()=>P0,stopStaleDashboardServer:()=>Jv});function P0(e,t){if(/^cli\.(?:bundle\.cjs|ts|js)$/.test(xf.basename(e)))return e;let r=xf.resolve(t,"../../core/dist/cli.bundle.cjs");return C0.existsSync(r)?r:e}function $Z(e){return new Promise(t=>setTimeout(t,e))}async function Jv(){let e=await pf();if(!e)return null;let t=Ro();if(!t)return null;let r={url:e.url,port:e.port,alreadyRunning:!0,lastBrowserOpenedAt:t.lastBrowserOpenedAt},n=Wr();if(!t.version||n==="0.0.0"||t.version===n)return r;console.error(`[DASHBOARD] Dashboard server version mismatch (running: ${t.version}, current: ${n}). Stopping it...`);try{process.kill(t.pid,"SIGTERM")}catch(s){if(s.code!=="ESRCH")return console.error(`[DASHBOARD] Could not kill outdated dashboard (PID ${t.pid}): ${s.message}`),r}return fs(),null}async function Gv(e){let t=If();if(!t)return await Jv(),null;let r=await Jv();if(r)return r;let n=e?.port??EZ,s=P0(process.argv[1],t),o=(0,k0.spawn)("node",[s,"dashboard","serve","--port",String(n),"--no-open"],{detached:!0,stdio:"ignore"}),i=!1,a=!1;o.on("error",c=>{i=!0,console.error(`[STARTUP] Failed to spawn dashboard server: ${c.message}`)}),o.on("exit",c=>{a=!0,c!==0&&c!==null&&console.error(`[STARTUP] Dashboard server exited prematurely (code ${c})`)}),o.unref();for(let c=0;c<TZ;c++){if(await $Z(AZ),i||a)return null;let u=Ro();if(u&&await qu(u.port))return{url:`http://oss.localhost:${u.port}`,port:u.port,alreadyRunning:!1}}if(console.error("[STARTUP] Dashboard server failed to start within 5 seconds"),o.pid)try{process.kill(o.pid,"SIGTERM")}catch(c){c.code!=="ESRCH"&&console.error(`[STARTUP] Failed to kill orphan dashboard process (PID ${o.pid}): ${c.message}`)}return null}var k0,C0,xf,EZ,AZ,TZ,Uv=A(()=>{"use strict";k0=require("node:child_process"),C0=B(require("node:fs"),1),xf=B(require("node:path"),1);Zu();Kv();le();EZ=3e3,AZ=200,TZ=25});var A0={};re(A0,{runStatus:()=>OZ});async function OZ(e){let t=L(),r=t.getStats(),n=t.getState(),s=n.lastDigestAt||n.lastRunAt,{totalTracked:o,...i}=r,a={stats:i,lastRunAt:n.lastRunAt};e.offline&&(a.offline=!0,a.lastUpdated=s);let c=t.getStateStaleness();return c&&(a.warnings=[An(c)]),a}var T0=A(()=>{"use strict";le();me()});var $0={};re($0,{runStrategy:()=>xZ});async function xZ(){let t=L().getState(),r=gs(t);if(r===null){let n=t.mergedPRs?.length??0;return{strategy:null,message:`Strategy snapshot needs at least ${10} merged PRs in local state; currently tracking ${n}. Keep contributing and the snapshot becomes available automatically.`}}return{strategy:r}}var O0=A(()=>{"use strict";le();Ju()});var Lf={};re(Lf,{runStateShow:()=>LZ,runStateSync:()=>FZ,runStateUnlink:()=>NZ});async function LZ(e={}){let t=L(),r=t.getState(),n={persistence:r.config.persistence??"local",gistId:r.gistId??null,gistDegraded:t.isGistDegraded(),lastRunAt:r.lastRunAt};return e.validate&&(n.invalidEntries=MZ(t)),n}function MZ(e){let t=[];for(let r of e.getMergedPRs())q(r.url)===null&&t.push({kind:"merged",url:r.url,title:r.title});for(let r of e.getClosedPRs())q(r.url)===null&&t.push({kind:"closed",url:r.url,title:r.title});return t}async function FZ(){let e=L();if(!e.isGistMode())return{pushed:!1,gistId:null};if(!await e.checkpoint())throw new Error("Failed to push state to Gist after retry. Check network connectivity and token permissions.");return{pushed:!0,gistId:e.getState().gistId??null}}async function NZ(){let e=L(),r=e.getState().gistId??null,n=jt();e.isGistMode()&&await e.refreshFromGist();let s=JSON.parse(JSON.stringify(e.getState()));delete s.gistId,s.config.persistence="local",Or(n,JSON.stringify(s,null,2),384);let o=Qs();try{Df.existsSync(o)&&Df.unlinkSync(o)}catch(i){v(DZ,`Failed to remove gist-id file: ${i}`)}return Sm(),{unlinked:!0,localStatePath:n,previousGistId:r}}var Df,DZ,Mf=A(()=>{"use strict";Df=B(require("node:fs"),1);os();pu();Vr();nt();ce();DZ="state-cmd"});function GZ(e){let t=new Map,r=e.lastDigest?.openPRs;if(!r)return t;for(let n of r){let s=n.repo.toLowerCase();t.set(s,(t.get(s)??0)+1)}return t}function UZ(e,t){let r=t.toLowerCase(),s=Object.entries(e.repoScores??{}).find(([o])=>o.toLowerCase()===r)?.[1]?.mergedPRCount??0;return s>0?s:(e.mergedPRs??[]).filter(o=>{let i=q(o.url);return i!==null&&`${i.owner}/${i.repo}`.toLowerCase()===r}).length}function jZ(e,t){let{maxOpenPRsPerRepo:r=0,maxOpenPRsColdRepo:n=0}=e,s=[r,t?n:0].filter(o=>o>0);return s.length>0?Math.min(...s):0}function zZ(e){let t=[];if(e.excluded&&t.push(`${e.repo} is in excludeRepos`),e.atCap){let r=e.cold?" for a repo where none of your PRs have merged yet":"";t.push(`${e.repo} has ${e.openPRCount} open PR(s), at the cap of ${e.cap}${r}`)}return t.length>0?t.join("; "):void 0}function Ff(e,t,r){let n=e.config??{},s=r?.openPRCount??GZ(e).get(t.toLowerCase())??0,o=UZ(e,t),i=o===0,a=jZ(n,i),c={repo:t,openPRCount:s,countSource:r?"github":"digest",mergedPRCount:o,cold:i,cap:a,atCap:a>0&&s>=a,excluded:(n.excludeRepos??[]).some(d=>d.toLowerCase()===t.toLowerCase())},u=zZ(c);return u?{...c,reason:u}:c}function Nf(e){let t=e.lastDigest?.openPRs;if(!t)return[];let r=new Set,n=[];for(let s of t){let o=s.repo.toLowerCase();r.has(o)||(r.add(o),Ff(e,s.repo).atCap&&n.push(s.repo))}return n}function Gf(e,t){let r=Ff(e,t);return r.reason?{repoCap:r}:{}}var xa=A(()=>{"use strict";nt()});function jf(e){Uf=e}function x0(){return Uf}function D0(){Uf="debug"}function Yv(e){return I0[Uf]>=I0[e]}function se(e,t,...r){if(!Yv("debug"))return;let n=new Date().toISOString();console.error(`[${n}] [DEBUG] [${e}] ${t}`,...r)}function ze(e,t,...r){if(!Yv("info"))return;let n=new Date().toISOString();console.error(`[${n}] [INFO] [${e}] ${t}`,...r)}function H(e,t,...r){if(!Yv("warn"))return;let n=new Date().toISOString();console.error(`[${n}] [WARN] [${e}] ${t}`,...r)}var I0,Uf,pt=A(()=>{I0={silent:0,warn:1,info:2,debug:3},Uf="info"});function Y(e){return e instanceof Error?e.message:String(e)}function Fe(e){if(e&&typeof e=="object"&&"status"in e){let t=e.status;return typeof t=="number"&&Number.isFinite(t)?t:void 0}}function L0(e){let t=Fe(e);return t===401?!0:t===403&&!mt(e)}function mt(e){let t=e?.errors;if(Array.isArray(t)&&t.some(n=>n?.type==="RATE_LIMITED"))return!0;let r=Fe(e);if(r===429)return!0;if(r===403){let n=Y(e).toLowerCase();return n.includes("rate limit")||n.includes("abuse detection")}return!1}function Be(e){if(Fe(e)===401||mt(e))throw e}var zf,Da,ot,ft=A(()=>{zf=class extends Error{code;constructor(t,r){super(t),this.code=r,this.name="OssScoutError"}},Da=class extends zf{constructor(t){super(t,"CONFIGURATION_ERROR"),this.name="ConfigurationError"}},ot=class extends zf{strategiesUsed;constructor(t,r){super(t,"VALIDATION_ERROR"),this.strategiesUsed=r,this.name="ValidationError"}}});function mr(e){return new Promise(t=>setTimeout(t,e))}function Rs(){let e=Bf.join(N0.homedir(),".oss-scout");return ws.existsSync(e)||ws.mkdirSync(e,{recursive:!0,mode:448}),e}function U0(){let e=Bf.join(Rs(),"cache");return ws.existsSync(e)||ws.mkdirSync(e,{recursive:!0,mode:448}),e}function it(e){let t;try{t=new URL(e)}catch{return null}let r=t.hostname.toLowerCase().replace(/^www\./,""),n=t.pathname.split("/").filter(Boolean);return r==="api.github.com"?n[0]==="repos"&&n.length>=3?`${n[1]}/${n[2]}`:null:r==="github.com"&&n.length>=2?`${n[0]}/${n[1]}`:null}function WZ(e,t){return BZ.test(e)&&HZ.test(t)}function Ao(e){let t=/^(?:www\.)?github\.com\//i.test(e)?`https://${e}`:e,r;try{r=new URL(t)}catch{return null}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.hostname.toLowerCase().replace(/^www\./,"")!=="github.com")return null;let s=r.pathname.split("/").filter(Boolean);if(s.length!==4)return null;let[o,i,a,c]=s;return a!=="pull"&&a!=="issues"||!WZ(o,i)||!/^\d+$/.test(c)?null:{owner:o,repo:i,number:parseInt(c,10),type:a}}function Ma(e,t=new Date){return Math.max(0,Math.floor((t.getTime()-e.getTime())/(1e3*60*60*24)))}function Qv(){if(La)return La;if(F0)return null;F0=!0;let e=process.env.GITHUB_TOKEN?.trim();if(e)return La=e,La;try{let t=(0,G0.execFileSync)("gh",["auth","token"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:2e3}).trim();if(t&&t.length>0)return La=t,se(M0,"Using GitHub token from gh CLI"),La}catch(t){se(M0,`gh auth token failed: ${Y(t)}`)}return null}function j0(){let e=Qv();if(!e)throw new Da(`GitHub authentication required.
263
263
 
264
264
  Options:
265
265
  1. Use gh CLI: gh auth login
266
266
  2. Set GITHUB_TOKEN environment variable
267
267
 
268
- The gh CLI is recommended - install from https://cli.github.com`);return e}var ws,Bf,N0,G0,M0,La,F0,zZ,BZ,It=A(()=>{ws=B(require("fs"),1),Bf=B(require("path"),1),N0=B(require("os"),1),G0=require("child_process");ft();pt();M0="utils",La=null,F0=!1;zZ=/^[a-zA-Z0-9_-]+$/,BZ=/^[a-zA-Z0-9_.-]+$/});function z0(e){let t=String(e?.["x-ratelimit-resource"]??"unknown");On.calls[t]=(On.calls[t]??0)+1;let r=Number(e?.["x-ratelimit-remaining"]);Number.isFinite(r)&&(On.minRemaining[t]=Math.min(On.minRemaining[t]??1/0,r))}function WZ(){let{start:e,...t}=On;return{...t,durationMs:Date.now()-e}}function VZ(){if(!process.env.VITEST)try{let e=JSON.stringify({ts:new Date().toISOString(),host:Vf.basename(process.argv[1]??""),args:process.argv.slice(2).map(t=>/gh[pousr]_|github_pat_/.test(t)?"[redacted]":t),exitCode:process.exitCode??0,...WZ()});B0.appendFileSync(Vf.join(Rs(),"runs.jsonl"),e+`
269
- `)}catch{}}function Wf(e){return e.toLocaleTimeString("en-US",{hour12:!1})}function ZZ(){return{onRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return On.rateLimited++,n<2?(H(Hf,`Rate limit hit (retry ${n+1}/2, waiting ${e}s, resets at ${Wf(o)}) \u2014 ${s.method} ${s.url}`),!0):(H(Hf,`Rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${Wf(o)})`),!1)},onSecondaryRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return On.secondaryRateLimited++,n<3?(H(Hf,`Secondary rate limit hit (retry ${n+1}/3, waiting ${e}s, resets at ${Wf(o)}) \u2014 ${s.method} ${s.url}`),!0):(H(Hf,`Secondary rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${Wf(o)})`),!1)}}}function In(e){if(al&&Xv===e)return al;let t=ZZ();return al=new qZ({auth:e,throttle:t}),al.hook?.wrap("request",async(r,n)=>{try{let s=await r(n);return z0(s.headers),s}catch(s){let o=s;z0(o.response?.headers);let i=String(o.status??"network");throw On.errorsByStatus[i]=(On.errorsByStatus[i]??0)+1,s}}),Xv||process.once("exit",VZ),Xv=e,al}async function qf(e){let t=In(e),{data:r}=await t.rateLimit.get(),n=r.resources.search;return{remaining:n.remaining,limit:n.limit,resetAt:new Date(n.reset*1e3).toISOString()}}var B0,Vf,Hf,On,qZ,al,Xv,Zf=A(()=>{o_();l_();d_();B0=B(require("fs"),1),Vf=B(require("path"),1);pt();It();Hf="github",On={start:Date.now(),calls:{},minRemaining:{},errorsByStatus:{},rateLimited:0,secondaryRateLimited:0};qZ=hm.plugin(Xi,wu),al=null,Xv=null});function fr(){return tk||(tk=new nk),tk}var Kf,rk,ek,KZ,H0,nk,tk,Fa=A(()=>{pt();It();Kf="search-budget",rk=30,ek=60*1e3,KZ=4,H0=rk-KZ,nk=class{callTimestamps=[];knownRemaining=rk;resetAt=0;totalCalls=0;callsSinceReset=0;reservedCalls=0;init(t,r){this.knownRemaining=t,this.resetAt=new Date(r).getTime(),this.callTimestamps=[],this.totalCalls=0,this.callsSinceReset=0,this.reservedCalls=0,se(Kf,`Initialized: ${t} remaining, resets at ${new Date(this.resetAt).toLocaleTimeString()}`)}recordCall(){this.reservedCalls>0&&this.reservedCalls--,this.callTimestamps.push(Date.now()),this.totalCalls++,this.callsSinceReset++,this.pruneOldTimestamps()}refreshExternalBudget(){if(this.resetAt<=0)return;let t=Date.now();if(!(t<this.resetAt)){for(this.knownRemaining=rk,this.callsSinceReset=0;this.resetAt<=t;)this.resetAt+=ek;se(Kf,"Quota window reset; external search budget replenished")}}pruneOldTimestamps(){let t=Date.now()-ek;for(;this.callTimestamps.length>0&&this.callTimestamps[0]<t;)this.callTimestamps.shift()}getCallsInWindow(){return this.pruneOldTimestamps(),this.callTimestamps.length}getEffectiveBudget(){this.refreshExternalBudget();let t=H0-this.callTimestamps.length-this.reservedCalls,r=this.knownRemaining-this.callsSinceReset-this.reservedCalls;return Math.max(0,Math.min(t,r))}canAfford(t){return this.pruneOldTimestamps(),this.getEffectiveBudget()>=t}async waitForBudget(){for(;;){if(this.pruneOldTimestamps(),this.getEffectiveBudget()>0){this.reservedCalls++;return}let t=this.callTimestamps[0];if(!t){if(this.reservedCalls>0){await mr(250);continue}let s=this.resetAt-Date.now();if(this.resetAt>0&&s>0){se(Kf,`External quota exhausted, waiting ${s}ms for reset`),await mr(s+100);continue}this.reservedCalls++;return}let n=t+ek-Date.now();n>0&&(se(Kf,`Budget full (${this.callTimestamps.length}/${H0} in window), waiting ${n}ms`),await mr(n+100))}}getTotalCalls(){return this.totalCalls}},tk=null});var cl,sk=A(()=>{cl={beginner:["good first issue","help wanted","easy","up-for-grabs","first-timers-only","beginner"],intermediate:["enhancement","feature","feature-request","contributions welcome"],advanced:["proposal","RFC","accepted","design"]}});function dl(e){return xn.parse(i2(e))}function i2(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e,r=typeof t.stateRevision=="number"?t.stateRevision:0;if(r>=ok)return e;let n=t;return r<1&&(n=a2(n)),{...n,stateRevision:ok}}function a2(e){let t=e.preferences;if(typeof t!="object"||t===null||Array.isArray(t))return e;let r=t;return r.interPhaseDelayMs!==o2?e:{...e,preferences:{...r,interPhaseDelayMs:0}}}var JZ,ul,ll,$o,Oo,YZ,ik,QZ,XZ,e2,t2,r2,n2,sre,ak,ck,s2,uk,To,ok,xn,o2,Io=A(()=>{ou();JZ=l.enum(["candidate"]),ul=l.enum(["nonprofit","devtools","infrastructure","web-frameworks","data-ml","education"]),ll=l.enum(["beginner","intermediate","advanced"]),$o=l.enum(["merged","orgs","starred","broad","maintained","all"]),Oo=["merged","orgs","starred","broad","maintained"],YZ=l.looseObject({hasActiveMaintainers:l.boolean(),isResponsive:l.boolean(),hasHostileComments:l.boolean()}),ik=l.looseObject({repo:l.string(),score:l.number(),mergedPRCount:l.number(),closedWithoutMergeCount:l.number(),avgResponseDays:l.number().nullable(),lastMergedAt:l.string().optional(),lastEvaluatedAt:l.string(),signals:YZ,stargazersCount:l.number().optional(),language:l.string().nullable().optional()}),QZ=l.looseObject({url:l.string(),title:l.string(),mergedAt:l.string()}),XZ=l.looseObject({url:l.string(),title:l.string(),closedAt:l.string()}),e2=l.looseObject({url:l.string(),title:l.string(),openedAt:l.string()}),t2=l.object({branchNamingConvention:l.string().optional(),commitMessageFormat:l.string().optional(),prTitleFormat:l.string().optional(),requiredChecks:l.array(l.string()).optional(),testFramework:l.string().optional(),testCoverageRequired:l.boolean().optional(),testFileNaming:l.string().optional(),linter:l.string().optional(),formatter:l.string().optional(),styleGuideUrl:l.string().optional(),issueClaimProcess:l.string().optional(),reviewProcess:l.string().optional(),claRequired:l.boolean().optional(),rawContent:l.string().optional()}),r2=l.object({number:l.number(),author:l.string(),state:l.enum(["open","closed"]),merged:l.boolean(),url:l.string(),updatedAt:l.string().optional()}),n2=l.object({passedAllChecks:l.boolean(),checks:l.object({noExistingPR:l.boolean(),notClaimed:l.boolean(),projectActive:l.boolean(),clearRequirements:l.boolean(),contributionGuidelinesFound:l.boolean()}),contributionGuidelines:t2.optional(),linkedPR:r2.nullable().optional(),notes:l.array(l.string())}),sre=l.object({id:l.number(),url:l.string(),repo:l.string(),number:l.number(),title:l.string(),status:JZ,labels:l.array(l.string()),createdAt:l.string(),updatedAt:l.string(),vetted:l.boolean(),vettingResult:n2.optional()}),ak=l.looseObject({url:l.string(),repo:l.string(),number:l.number(),title:l.string(),skippedAt:l.string(),reason:l.string().optional(),permanent:l.boolean().default(!0)}),ck=l.enum(["quick-win","bigger-bet"]),s2=l.looseObject({issueUrl:l.string(),repo:l.string(),number:l.number(),title:l.string(),labels:l.array(l.string()),recommendation:l.enum(["approve","skip","needs_review"]),viabilityScore:l.number(),searchPriority:l.enum(["merged_pr","starred","normal"]).catch("normal"),firstSeenAt:l.string(),lastSeenAt:l.string(),lastScore:l.number(),horizon:ck.optional(),lastStatus:l.enum(["still_available","claimed","closed","has_pr"]).optional()}),uk=l.enum(["local","gist"]),To=l.looseObject({githubUsername:l.string().default(""),languages:l.array(l.string()).default(["any"]),labels:l.array(l.string()).default(["good first issue","help wanted"]),scope:l.array(ll).optional(),excludeRepos:l.array(l.string()).default([]),excludeOrgs:l.array(l.string()).default([]),preferredOrgs:l.array(l.string()).default([]),aiPolicyBlocklist:l.array(l.string()).default(["matplotlib/matplotlib"]),projectCategories:l.array(ul).default([]),minStars:l.number().default(50),maxIssueAgeDays:l.number().default(90),includeDocIssues:l.boolean().default(!0),minRepoScoreThreshold:l.number().default(4),interPhaseDelayMs:l.number().min(0).max(12e4).default(0),persistence:uk.default("local"),defaultStrategy:l.array($o).optional(),preferLanguages:l.array(l.string()).default([]),preferRepos:l.array(l.string()).default([]),diversityRatio:l.number().min(0).max(1).default(0),avoidRepos:l.array(l.string()).default([]),boostIssueTypes:l.array(l.string()).default([]),broadPhaseDelayMs:l.number().min(0).max(3e5).default(0),skipBroadWhenSufficientResults:l.number().int().min(0).max(100).default(8),slmTriageModel:l.string().default(""),slmTriageHost:l.string().default(""),featuresAnchorThreshold:l.number().int().min(1).max(50).default(3),featuresSplitRatio:l.number().min(0).max(1).default(.6)}),ok=1,xn=l.looseObject({version:l.literal(1),stateRevision:l.number().int().min(0).default(ok),preferences:To.default(()=>To.parse({})),repoScores:l.record(l.string(),ik).default({}),starredRepos:l.array(l.string()).default([]),starredReposLastFetched:l.string().optional(),mergedPRs:l.array(QZ).default([]),closedPRs:l.array(XZ).default([]),openPRs:l.array(e2).default([]),savedResults:l.array(s2).default([]),skippedIssues:l.array(ak).default([]),tombstones:l.array(l.looseObject({url:l.string(),removedAt:l.string()})).default([]),preferencesUpdatedAt:l.string().optional(),lastSearchAt:l.string().optional(),lastRunAt:l.string().default(()=>new Date().toISOString()),gistId:l.string().optional(),searchRotation:l.looseObject({languageOffset:l.number().int().min(0).default(0),phase0Offset:l.number().int().min(0).default(0),starredOffset:l.number().int().min(0).default(0),maintainedOffset:l.number().int().min(0).default(0),strategyOffset:l.number().int().min(0).default(0),lastRotatedAt:l.string().optional()}).default(()=>({languageOffset:0,phase0Offset:0,starredOffset:0,maintainedOffset:0,strategyOffset:0}))});o2=3e4});function W0(e){if(!e.labels||!Array.isArray(e.labels)||e.labels.length===0)return!1;let r=e.labels.map(n=>(typeof n=="string"?n:n.name||"").toLowerCase()).filter(n=>n.length>0);return r.length===0?!1:r.every(n=>c2.has(n))}function V0(e){if((e.labels??[]).map(n=>(typeof n=="string"?n:n.name||"").toLowerCase()).some(n=>u2.has(n)))return!0;let r=(e.title??"").trim();return r.endsWith("?")||/^(how|why|what|when|where|which|who|is|are|does|do|can|could|should|would|will|has|have)\b/i.test(r)?!0:r.split(/\s+/).filter(Boolean).length<3}function d2(e){return!e.labels||!Array.isArray(e.labels)?!1:e.labels.map(n=>(typeof n=="string"?n:n.name||"").toLowerCase()).filter(n=>l2.has(n)).length>=5}function p2(e){return e?/^.+\s+(question|fact|point|item|task|entry|post|challenge|exercise|example|problem|tip|recipe|snippet)\s+#?\d+$/i.test(e):!1}function q0(e){let t=new Set,r=new Map;for(let n of e){let s=it(n.repository_url);if(s){if(d2(n)){t.add(s);continue}n.title&&p2(n.title)&&r.set(s,(r.get(s)||0)+1)}}for(let[n,s]of r)s>=3&&t.add(n);return t}function Z0(e,t){let r=new Map,n=[];for(let s of e){let o=r.get(s.issue.repo)||0;o<t&&(n.push(s),r.set(s.issue.repo,o+1))}return n}var c2,u2,l2,lk=A(()=>{It();c2=new Set(["documentation","docs","typo","spelling"]);u2=new Set(["question","discussion","support"]);l2=new Set(["good first issue","hacktoberfest","easy","up-for-grabs","first-timers-only","beginner-friendly","beginner","starter","newbie","low-hanging-fruit","community"])});function K0(e,t){let r=0;return e>=5e3?r+=8:e>=500?r+=5:e>=50&&(r+=3),t>=500?r+=4:t>=50&&(r+=2),r}function J0(e){let t=50;e.repoScore!==null&&(t+=e.repoScore*2),t+=e.repoQualityBonus??0,e.mergedPRCount>0&&(t+=15),e.clearRequirements&&(t+=15);let r=new Date(e.issueUpdatedAt),n=Ma(r);if(n<=14?t+=15:n<=30&&(t+=Math.round(15*(1-(n-14)/16))),e.hasContributionGuidelines&&(t+=10),e.orgHasMergedPRs&&(t+=5),e.matchesPreferredCategory&&(t+=5),e.hasExistingPR&&(t-=30),e.isClaimed&&(t-=20),e.closedWithoutMergeCount>0&&e.mergedPRCount===0&&(t-=15),e.featureSignals){let s=e.featureSignals;t+=Math.min(Math.floor(s.reactions/2),10),s.comments>=5&&(t+=5),s.hasMilestone&&(t+=5),s.wontfixNoContributor&&(t+=10)}return Math.max(0,Math.min(100,t))}var Y0=A(()=>{It()});function Q0(e,t){if(t.length===0)return!1;let r=e.split("/")[0]?.toLowerCase();if(!r)return!1;for(let n of t){let s=f2[n];if(s&&s.some(o=>o.toLowerCase()===r))return!0}return!1}function X0(e){let t=new Set;for(let r of e){let n=m2[r];if(n)for(let s of n)t.add(s)}return[...t]}var m2,f2,dk=A(()=>{m2={nonprofit:["nonprofit","social-good","humanitarian","charity","social-impact","civic-tech"],devtools:["developer-tools","devtools","cli","sdk","linter","formatter","build-tool"],infrastructure:["infrastructure","cloud","kubernetes","docker","devops","monitoring","observability"],"web-frameworks":["web-framework","frontend","backend","fullstack","nextjs","react","vue"],"data-ml":["machine-learning","data-science","deep-learning","nlp","data-pipeline","analytics"],education:["education","learning","tutorial","courseware","edtech","teaching"]},f2={nonprofit:["code-for-america","opengovfoundation","ushahidi","hotosm","openfn","democracyearth"],devtools:["eslint","prettier","vitejs","biomejs","oxc-project","ast-grep","turbot"],infrastructure:["kubernetes","hashicorp","grafana","prometheus","open-telemetry","envoyproxy","cncf"],"web-frameworks":["vercel","remix-run","sveltejs","nuxt","astro","redwoodjs","blitz-js"],"data-ml":["huggingface","mlflow","apache","dbt-labs","dagster-io","prefecthq","langchain-ai"],education:["freeCodeCamp","TheOdinProject","exercism","codecademy","oppia","Khan"]}});async function eD(e,t=100,r=10){let n=[];for(let s=1;s<=r;s++){let{data:o}=await e(s);if(n.push(...o),o.length<t)break}return n}var tD=A(()=>{});function Lr(e){return`${g2}:${e}`}function gt(){return pk||(pk=new mk),pk}async function Yf(e,t,r){let n=e.getInflight(t);if(n)return se(Pt,`Dedup hit for ${t}`),await n;let s=r(),o=e.setInflight(t,s);try{return await s}finally{o()}}async function pl(e,t,r){return Yf(e,t,async()=>{let s={},o=e.get(t);o&&(s["if-none-match"]=o.etag);try{let i=await r(s),a=i.headers?.etag;return a&&e.set(t,a,i.data),i.data}catch(i){if(y2(i)){let a=e.get(t);if(a)return se(Pt,`304 cache hit for ${t}`),a.body;se(Pt,`304 but cache entry vanished for ${t}, refetching`);let c=await r({}),u=c.headers?.etag;return u&&e.set(t,u,c.data),c.data}throw i}})}async function nD(e,t,r,n){let s=e.getEntryIfFresh(t,r);return s?(se(Pt,`Time-based cache hit for ${t}`),s.body):Yf(e,t,async()=>{let o=e.getEntryIfFresh(t,r);if(o)return o.body;let i=await n();return e.set(t,"",i),i})}function y2(e){return Me(e)===304}var nr,Jf,rD,Pt,g2,h2,mk,pk,Dn=A(()=>{nr=B(require("fs"),1),Jf=B(require("path"),1),rD=B(require("crypto"),1);It();pt();ft();Pt="http-cache",g2="v1";h2=1440*60*1e3,mk=class{cacheDir;inflightRequests=new Map;constructor(t){this.cacheDir=t??U0()}keyFor(t){return rD.createHash("sha256").update(t).digest("hex")}pathFor(t){return Jf.join(this.cacheDir,`${this.keyFor(t)}.json`)}getIfFresh(t,r){return this.getEntryIfFresh(t,r)?.body??null}getEntryIfFresh(t,r){let n=this.get(t);if(!n)return null;let s=Date.now()-new Date(n.cachedAt).getTime();return!Number.isFinite(s)||s<0||s>r?null:n}get(t){let r=this.pathFor(t);try{let n=nr.readFileSync(r,"utf-8"),s=JSON.parse(n);return s.url!==t?(se(Pt,`Cache collision detected for ${t}, ignoring`),null):s}catch(n){if(n?.code==="ENOENT")return null;if(n instanceof SyntaxError){se(Pt,`Corrupt cache entry, deleting: ${t}`);try{nr.unlinkSync(r)}catch(o){se(Pt,`Failed to delete corrupt cache entry: ${Y(o)}`)}return null}return H(Pt,`Cache read failed for ${t}: ${Y(n)}`),null}}set(t,r,n){let s={etag:r,url:t,body:n,cachedAt:new Date().toISOString()};try{nr.writeFileSync(this.pathFor(t),JSON.stringify(s),{encoding:"utf-8",mode:384}),se(Pt,`Cached response for ${t}`)}catch(o){H(Pt,`Failed to write cache for ${t}: ${Y(o)}`)}}getInflight(t){return this.inflightRequests.get(t)}setInflight(t,r){return this.inflightRequests.set(t,r),()=>{this.inflightRequests.delete(t)}}evictStale(t=h2){let r=0;try{let n=nr.readdirSync(this.cacheDir),s=Date.now();for(let o of n){if(!o.endsWith(".json"))continue;let i=Jf.join(this.cacheDir,o);try{let a=nr.readFileSync(i,"utf-8"),c=JSON.parse(a);s-new Date(c.cachedAt).getTime()>t&&(nr.unlinkSync(i),r++)}catch{se(Pt,`Removing unreadable cache entry ${o}`);try{nr.unlinkSync(i),r++}catch(a){se(Pt,`Failed to remove stale cache entry ${o}: ${Y(a)}`)}}}}catch(n){n?.code!=="ENOENT"&&H(Pt,`Failed to evict stale cache entries: ${Y(n)}`)}return r>0&&se(Pt,`Evicted ${r} stale cache entries`),r}clear(){try{let t=nr.readdirSync(this.cacheDir);for(let r of t)r.endsWith(".json")&&nr.unlinkSync(Jf.join(this.cacheDir,r));se(Pt,"Cache cleared")}catch(t){t?.code!=="ENOENT"&&H(Pt,`Failed to clear cache: ${Y(t)}`)}}size(){try{return nr.readdirSync(this.cacheDir).filter(t=>t.endsWith(".json")).length}catch(t){return t?.code!=="ENOENT"&&se(Pt,`Failed to read cache size: ${Y(t)}`),0}}},pk=null});function b2(e){return e.event==="cross-referenced"&&!!e.source?.issue?.pull_request}function w2(e,t){let r=e.source?.issue,n=`${t.owner}/${t.repo}#${t.issueNumber}`;if(!r||typeof r.number!="number")return H(Na,`Cross-referenced timeline event for ${n} missing source.issue.number \u2014 possible API shape drift`),null;let s=r.user?.login;if(!s)return H(Na,`Cross-referenced PR #${r.number} for ${n} has no user.login (deleted user?) \u2014 skipping linkedPR metadata`),null;let o=r.html_url;return o?{number:r.number,author:s,state:r.state==="closed"?"closed":"open",merged:!!r.pull_request?.merged_at,url:o,updatedAt:r.updated_at}:(H(Na,`Cross-referenced PR #${r.number} for ${n} missing html_url \u2014 skipping linkedPR metadata`),null)}function v2(e){return e.replace(/<!--[\s\S]*?-->/g," ").replace(/```[\s\S]*?```/g," ").replace(/^\s*[-*] \[ \].*$/gm," ").replace(/^\s*>.*$/gm," ")}function fk(e){let t=v2(e).toLowerCase().split(/(?<=[.!?])|\n+/);for(let r of t){if(C2.test(r))return!0;if(!r.trimEnd().endsWith("?")){if(R2.some(n=>n.test(r))||!_2.test(r)&&S2.some(n=>n.test(r)))return!0;if(!P2.test(r)&&k2.some(n=>n.test(r)))return!0}}return!1}async function oD(e,t,r,n){try{let s=await eD(a=>e.issues.listEventsForTimeline({owner:t,repo:r,issue_number:n,per_page:100,page:a})),o=0,i=null;for(let a of s){let c=a;b2(c)&&(o++,i??=w2(c,{owner:t,repo:r,issueNumber:n}))}return{passed:o===0,linkedPR:i}}catch(s){Be(s);let o=Y(s);return H(Na,`Failed to check for existing PRs on ${t}/${r}#${n}: ${o}. Assuming no existing PR.`),{passed:!0,inconclusive:!0,reason:o,linkedPR:null}}}function gk(e,t){return Lr(`merged-prs:${e}/${t}`)}async function iD(e,t,r,n=fr()){let s=gt(),o=gk(t,r);return Yf(s,o,async()=>{let i=s.getIfFresh(o,E2);if(i!=null&&typeof i=="number")return i;try{await n.waitForBudget();try{let{data:a}=await e.search.issuesAndPullRequests({q:`repo:${t}/${r} is:pr is:merged author:@me`,per_page:1});return s.set(o,"",a.total_count),a.total_count}finally{n.recordCall()}}catch(a){Be(a);let c=Y(a);return H(Na,`Could not check merged PRs in ${t}/${r}: ${c}. Treating as unknown.`),null}})}async function aD(e,t,r,n,s){if(s===0)return{passed:!0};try{let i=Math.max(1,Math.ceil(s/100)),a=i>1?[i-1,i]:[1],c=[];for(let d of a){let p=await e.issues.listComments({owner:t,repo:r,issue_number:n,per_page:100,page:d});c.push(...p.data)}let u=c.length%100;if(c.length>0&&u===0){let d=await e.issues.listComments({owner:t,repo:r,issue_number:n,per_page:100,page:i+1});c.push(...d.data)}for(let d of c)if(fk(d.body||""))return{passed:!1};return{passed:!0}}catch(o){Be(o);let i=Y(o);return H(Na,`Failed to check claim status on ${t}/${r}#${n}: ${i}. Assuming not claimed.`),{passed:!0,inconclusive:!0,reason:i}}}function cD(e){if(!e||e.length<50)return!1;let t=/(^|\n)\s*\d+[.)]\s/.test(e)||/steps?\s+to\s+reproduce|\brepro(duction)?\b/i.test(e),r=/\b(expected|should)\b/i.test(e)&&/\b(actual(ly)?|instead|but|currently|observed|got)\b/i.test(e);return/```|`[^`\n]+`/.test(e)||/\b[\w/.-]+\.(ts|tsx|js|jsx|mjs|cjs|py|rb|go|rs|java|kt|swift|c|cc|cpp|h|hpp|cs|php|sh|vue|svelte)\b/.test(e)||/^\s+at\s+\S+\s+\(/m.test(e)||t&&r}var Na,Qf,R2,sD,S2,_2,k2,C2,P2,E2,hk=A(()=>{tD();ft();pt();Dn();Fa();Na="issue-eligibility",Qf=String.raw`(?:this\b|it\b|that\b|the\b|#\d+|issue\b)`,R2=[new RegExp(String.raw`\bi\s*(?:'ll|will) take ${Qf}`),new RegExp(String.raw`\bi\s*(?:'d|would) (?:like|love) to work on ${Qf}`),new RegExp(String.raw`\bi\s*(?:'d|would) (?:like|love) to (?:\w+ and )?(?:fix|tackle|take on|pick up|implement) ${Qf}`),/\bi\s*(?:'m|am) on it\b/,/\bi\s*(?:'ll|will) submit a pr\b/,/\bassigned to me\b/],sD=String.raw`(?:^\s*|\b(?:i\s*(?:'m|am|'d be|would be|'ll be|will be)|we\s*(?:'re|are|'d be|would be|'ll be|will be))\s+(?:(?:really|very|more than|absolutely|also)\s+)?)`,S2=[new RegExp(String.raw`${sD}(?:happy|glad|willing|keen) to (?:open|send|submit|make|put up|raise|contribute|write) (?:a |the |an )?(?:[\w-]+ ){0,2}(?:pr|pull request|patch|fix)\b`),new RegExp(String.raw`${sD}(?:happy|glad|willing|keen) to (?:have a go|take a stab)\b`),/\bi can (?:send|open|submit|put up) (?:this |it )?(?:as )?(?:a |the )?(?:pr|pull request|patch|fix)\b/,/\bi\s*(?:'ll|will) (?:open|send|put up|raise) a (?:pr|pull request)\b/,/\bi\s*(?:'d|would) love to contribute (?:this|it|a fix|the fix)\b/,/\bi plan to (?:make|send|submit|open) (?:a |the )?(?:[\w-]+ ){0,2}(?:pr|pull request|fix|change)\b/],_2=/\bnot\b|n't\b|\bbut\b|\bunless\b/;k2=[/\bworking on (?:this|it)\b/,/\bworking on a (?:fix|pr)\b/],C2=new RegExp(String.raw`\b(?:can|may|could) i (?:work on|take) ${Qf}`),P2=/\b(?:anyone|anybody|someone|somebody|who|whoever|nobody|no[- ]?one|not)\b/;E2=900*1e3});async function Ga(e,t,r,n){let s=`/repos/${t}/${r}/contents/${n}`,o=`missing:${s}`;if(gt().getIfFresh(o,T2)!==null)return{text:null,transient:!1};try{let i=await pl(gt(),s,a=>e.repos.getContent({owner:t,repo:r,path:n,headers:a}));return i&&typeof i=="object"&&"content"in i&&typeof i.content=="string"?{text:Buffer.from(i.content,"base64").toString("utf-8"),transient:!1}:{text:null,transient:!1}}catch(i){return Me(i)===404?(gt().set(o,"",!0),{text:null,transient:!1}):(Be(i),H(A2,`Unexpected error fetching ${n} from ${t}/${r}: ${Y(i)}`),{text:null,transient:!0})}}var A2,T2,Xf=A(()=>{ft();pt();Dn();A2="probe-repo-file",T2=14400*1e3});async function I2(e,t,r){let n=new Date(Date.now()-O2*24*60*60*1e3).toISOString().slice(0,10),s=`repo:${t}/${r} is:pr closed:>=${n}`,o=await e.graphql(`query repoMergeStats($merged: String!, $closedUnmerged: String!) {
268
+ The gh CLI is recommended - install from https://cli.github.com`);return e}var ws,Bf,N0,G0,M0,La,F0,BZ,HZ,It=A(()=>{ws=B(require("fs"),1),Bf=B(require("path"),1),N0=B(require("os"),1),G0=require("child_process");ft();pt();M0="utils",La=null,F0=!1;BZ=/^[a-zA-Z0-9_-]+$/,HZ=/^[a-zA-Z0-9_.-]+$/});function z0(e){let t=String(e?.["x-ratelimit-resource"]??"unknown");On.calls[t]=(On.calls[t]??0)+1;let r=Number(e?.["x-ratelimit-remaining"]);Number.isFinite(r)&&(On.minRemaining[t]=Math.min(On.minRemaining[t]??1/0,r))}function VZ(){let{start:e,...t}=On;return{...t,durationMs:Date.now()-e}}function qZ(){if(!process.env.VITEST)try{let e=JSON.stringify({ts:new Date().toISOString(),host:Vf.basename(process.argv[1]??""),args:process.argv.slice(2).map(t=>/gh[pousr]_|github_pat_/.test(t)?"[redacted]":t),exitCode:process.exitCode??0,...VZ()});B0.appendFileSync(Vf.join(Rs(),"runs.jsonl"),e+`
269
+ `)}catch{}}function Wf(e){return e.toLocaleTimeString("en-US",{hour12:!1})}function KZ(){return{onRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return On.rateLimited++,n<2?(H(Hf,`Rate limit hit (retry ${n+1}/2, waiting ${e}s, resets at ${Wf(o)}) \u2014 ${s.method} ${s.url}`),!0):(H(Hf,`Rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${Wf(o)})`),!1)},onSecondaryRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return On.secondaryRateLimited++,n<3?(H(Hf,`Secondary rate limit hit (retry ${n+1}/3, waiting ${e}s, resets at ${Wf(o)}) \u2014 ${s.method} ${s.url}`),!0):(H(Hf,`Secondary rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${Wf(o)})`),!1)}}}function In(e){if(al&&Xv===e)return al;let t=KZ();return al=new ZZ({auth:e,throttle:t}),al.hook?.wrap("request",async(r,n)=>{try{let s=await r(n);return z0(s.headers),s}catch(s){let o=s;z0(o.response?.headers);let i=String(o.status??"network");throw On.errorsByStatus[i]=(On.errorsByStatus[i]??0)+1,s}}),Xv||process.once("exit",qZ),Xv=e,al}async function qf(e){let t=In(e),{data:r}=await t.rateLimit.get(),n=r.resources.search;return{remaining:n.remaining,limit:n.limit,resetAt:new Date(n.reset*1e3).toISOString()}}var B0,Vf,Hf,On,ZZ,al,Xv,Zf=A(()=>{o_();l_();d_();B0=B(require("fs"),1),Vf=B(require("path"),1);pt();It();Hf="github",On={start:Date.now(),calls:{},minRemaining:{},errorsByStatus:{},rateLimited:0,secondaryRateLimited:0};ZZ=hm.plugin(Xi,wu),al=null,Xv=null});function fr(){return tk||(tk=new nk),tk}var Kf,rk,ek,JZ,H0,nk,tk,Fa=A(()=>{pt();It();Kf="search-budget",rk=30,ek=60*1e3,JZ=4,H0=rk-JZ,nk=class{callTimestamps=[];knownRemaining=rk;resetAt=0;totalCalls=0;callsSinceReset=0;reservedCalls=0;init(t,r){this.knownRemaining=t,this.resetAt=new Date(r).getTime(),this.callTimestamps=[],this.totalCalls=0,this.callsSinceReset=0,this.reservedCalls=0,se(Kf,`Initialized: ${t} remaining, resets at ${new Date(this.resetAt).toLocaleTimeString()}`)}recordCall(){this.reservedCalls>0&&this.reservedCalls--,this.callTimestamps.push(Date.now()),this.totalCalls++,this.callsSinceReset++,this.pruneOldTimestamps()}refreshExternalBudget(){if(this.resetAt<=0)return;let t=Date.now();if(!(t<this.resetAt)){for(this.knownRemaining=rk,this.callsSinceReset=0;this.resetAt<=t;)this.resetAt+=ek;se(Kf,"Quota window reset; external search budget replenished")}}pruneOldTimestamps(){let t=Date.now()-ek;for(;this.callTimestamps.length>0&&this.callTimestamps[0]<t;)this.callTimestamps.shift()}getCallsInWindow(){return this.pruneOldTimestamps(),this.callTimestamps.length}getEffectiveBudget(){this.refreshExternalBudget();let t=H0-this.callTimestamps.length-this.reservedCalls,r=this.knownRemaining-this.callsSinceReset-this.reservedCalls;return Math.max(0,Math.min(t,r))}canAfford(t){return this.pruneOldTimestamps(),this.getEffectiveBudget()>=t}async waitForBudget(){for(;;){if(this.pruneOldTimestamps(),this.getEffectiveBudget()>0){this.reservedCalls++;return}let t=this.callTimestamps[0];if(!t){if(this.reservedCalls>0){await mr(250);continue}let s=this.resetAt-Date.now();if(this.resetAt>0&&s>0){se(Kf,`External quota exhausted, waiting ${s}ms for reset`),await mr(s+100);continue}this.reservedCalls++;return}let n=t+ek-Date.now();n>0&&(se(Kf,`Budget full (${this.callTimestamps.length}/${H0} in window), waiting ${n}ms`),await mr(n+100))}}getTotalCalls(){return this.totalCalls}},tk=null});var cl,sk=A(()=>{cl={beginner:["good first issue","help wanted","easy","up-for-grabs","first-timers-only","beginner"],intermediate:["enhancement","feature","feature-request","contributions welcome"],advanced:["proposal","RFC","accepted","design"]}});function dl(e){return xn.parse(a2(e))}function a2(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e,r=typeof t.stateRevision=="number"?t.stateRevision:0;if(r>=ok)return e;let n=t;return r<1&&(n=c2(n)),{...n,stateRevision:ok}}function c2(e){let t=e.preferences;if(typeof t!="object"||t===null||Array.isArray(t))return e;let r=t;return r.interPhaseDelayMs!==i2?e:{...e,preferences:{...r,interPhaseDelayMs:0}}}var YZ,ul,ll,$o,Oo,QZ,ik,XZ,e2,t2,r2,n2,s2,ore,ak,ck,o2,uk,To,ok,xn,i2,Io=A(()=>{ou();YZ=l.enum(["candidate"]),ul=l.enum(["nonprofit","devtools","infrastructure","web-frameworks","data-ml","education"]),ll=l.enum(["beginner","intermediate","advanced"]),$o=l.enum(["merged","orgs","starred","broad","maintained","all"]),Oo=["merged","orgs","starred","broad","maintained"],QZ=l.looseObject({hasActiveMaintainers:l.boolean(),isResponsive:l.boolean(),hasHostileComments:l.boolean()}),ik=l.looseObject({repo:l.string(),score:l.number(),mergedPRCount:l.number(),closedWithoutMergeCount:l.number(),avgResponseDays:l.number().nullable(),lastMergedAt:l.string().optional(),lastEvaluatedAt:l.string(),signals:QZ,stargazersCount:l.number().optional(),language:l.string().nullable().optional()}),XZ=l.looseObject({url:l.string(),title:l.string(),mergedAt:l.string()}),e2=l.looseObject({url:l.string(),title:l.string(),closedAt:l.string()}),t2=l.looseObject({url:l.string(),title:l.string(),openedAt:l.string()}),r2=l.object({branchNamingConvention:l.string().optional(),commitMessageFormat:l.string().optional(),prTitleFormat:l.string().optional(),requiredChecks:l.array(l.string()).optional(),testFramework:l.string().optional(),testCoverageRequired:l.boolean().optional(),testFileNaming:l.string().optional(),linter:l.string().optional(),formatter:l.string().optional(),styleGuideUrl:l.string().optional(),issueClaimProcess:l.string().optional(),reviewProcess:l.string().optional(),claRequired:l.boolean().optional(),rawContent:l.string().optional()}),n2=l.object({number:l.number(),author:l.string(),state:l.enum(["open","closed"]),merged:l.boolean(),url:l.string(),updatedAt:l.string().optional()}),s2=l.object({passedAllChecks:l.boolean(),checks:l.object({noExistingPR:l.boolean(),notClaimed:l.boolean(),projectActive:l.boolean(),clearRequirements:l.boolean(),contributionGuidelinesFound:l.boolean()}),contributionGuidelines:r2.optional(),linkedPR:n2.nullable().optional(),notes:l.array(l.string())}),ore=l.object({id:l.number(),url:l.string(),repo:l.string(),number:l.number(),title:l.string(),status:YZ,labels:l.array(l.string()),createdAt:l.string(),updatedAt:l.string(),vetted:l.boolean(),vettingResult:s2.optional()}),ak=l.looseObject({url:l.string(),repo:l.string(),number:l.number(),title:l.string(),skippedAt:l.string(),reason:l.string().optional(),permanent:l.boolean().default(!0)}),ck=l.enum(["quick-win","bigger-bet"]),o2=l.looseObject({issueUrl:l.string(),repo:l.string(),number:l.number(),title:l.string(),labels:l.array(l.string()),recommendation:l.enum(["approve","skip","needs_review"]),viabilityScore:l.number(),searchPriority:l.enum(["merged_pr","starred","normal"]).catch("normal"),firstSeenAt:l.string(),lastSeenAt:l.string(),lastScore:l.number(),horizon:ck.optional(),lastStatus:l.enum(["still_available","claimed","closed","has_pr"]).optional()}),uk=l.enum(["local","gist"]),To=l.looseObject({githubUsername:l.string().default(""),languages:l.array(l.string()).default(["any"]),labels:l.array(l.string()).default(["good first issue","help wanted"]),scope:l.array(ll).optional(),excludeRepos:l.array(l.string()).default([]),excludeOrgs:l.array(l.string()).default([]),preferredOrgs:l.array(l.string()).default([]),aiPolicyBlocklist:l.array(l.string()).default(["matplotlib/matplotlib"]),projectCategories:l.array(ul).default([]),minStars:l.number().default(50),maxIssueAgeDays:l.number().default(90),includeDocIssues:l.boolean().default(!0),minRepoScoreThreshold:l.number().default(4),interPhaseDelayMs:l.number().min(0).max(12e4).default(0),persistence:uk.default("local"),defaultStrategy:l.array($o).optional(),preferLanguages:l.array(l.string()).default([]),preferRepos:l.array(l.string()).default([]),diversityRatio:l.number().min(0).max(1).default(0),avoidRepos:l.array(l.string()).default([]),boostIssueTypes:l.array(l.string()).default([]),broadPhaseDelayMs:l.number().min(0).max(3e5).default(0),skipBroadWhenSufficientResults:l.number().int().min(0).max(100).default(8),slmTriageModel:l.string().default(""),slmTriageHost:l.string().default(""),featuresAnchorThreshold:l.number().int().min(1).max(50).default(3),featuresSplitRatio:l.number().min(0).max(1).default(.6)}),ok=1,xn=l.looseObject({version:l.literal(1),stateRevision:l.number().int().min(0).default(ok),preferences:To.default(()=>To.parse({})),repoScores:l.record(l.string(),ik).default({}),starredRepos:l.array(l.string()).default([]),starredReposLastFetched:l.string().optional(),mergedPRs:l.array(XZ).default([]),closedPRs:l.array(e2).default([]),openPRs:l.array(t2).default([]),savedResults:l.array(o2).default([]),skippedIssues:l.array(ak).default([]),tombstones:l.array(l.looseObject({url:l.string(),removedAt:l.string()})).default([]),preferencesUpdatedAt:l.string().optional(),lastSearchAt:l.string().optional(),lastRunAt:l.string().default(()=>new Date().toISOString()),gistId:l.string().optional(),searchRotation:l.looseObject({languageOffset:l.number().int().min(0).default(0),phase0Offset:l.number().int().min(0).default(0),starredOffset:l.number().int().min(0).default(0),maintainedOffset:l.number().int().min(0).default(0),strategyOffset:l.number().int().min(0).default(0),lastRotatedAt:l.string().optional()}).default(()=>({languageOffset:0,phase0Offset:0,starredOffset:0,maintainedOffset:0,strategyOffset:0}))});i2=3e4});function W0(e){if(!e.labels||!Array.isArray(e.labels)||e.labels.length===0)return!1;let r=e.labels.map(n=>(typeof n=="string"?n:n.name||"").toLowerCase()).filter(n=>n.length>0);return r.length===0?!1:r.every(n=>u2.has(n))}function V0(e){if((e.labels??[]).map(n=>(typeof n=="string"?n:n.name||"").toLowerCase()).some(n=>l2.has(n)))return!0;let r=(e.title??"").trim();return r.endsWith("?")||/^(how|why|what|when|where|which|who|is|are|does|do|can|could|should|would|will|has|have)\b/i.test(r)?!0:r.split(/\s+/).filter(Boolean).length<3}function p2(e){return!e.labels||!Array.isArray(e.labels)?!1:e.labels.map(n=>(typeof n=="string"?n:n.name||"").toLowerCase()).filter(n=>d2.has(n)).length>=5}function m2(e){return e?/^.+\s+(question|fact|point|item|task|entry|post|challenge|exercise|example|problem|tip|recipe|snippet)\s+#?\d+$/i.test(e):!1}function q0(e){let t=new Set,r=new Map;for(let n of e){let s=it(n.repository_url);if(s){if(p2(n)){t.add(s);continue}n.title&&m2(n.title)&&r.set(s,(r.get(s)||0)+1)}}for(let[n,s]of r)s>=3&&t.add(n);return t}function Z0(e,t){let r=new Map,n=[];for(let s of e){let o=r.get(s.issue.repo)||0;o<t&&(n.push(s),r.set(s.issue.repo,o+1))}return n}var u2,l2,d2,lk=A(()=>{It();u2=new Set(["documentation","docs","typo","spelling"]);l2=new Set(["question","discussion","support"]);d2=new Set(["good first issue","hacktoberfest","easy","up-for-grabs","first-timers-only","beginner-friendly","beginner","starter","newbie","low-hanging-fruit","community"])});function K0(e,t){let r=0;return e>=5e3?r+=8:e>=500?r+=5:e>=50&&(r+=3),t>=500?r+=4:t>=50&&(r+=2),r}function J0(e){let t=50;e.repoScore!==null&&(t+=e.repoScore*2),t+=e.repoQualityBonus??0,e.mergedPRCount>0&&(t+=15),e.clearRequirements&&(t+=15);let r=new Date(e.issueUpdatedAt),n=Ma(r);if(n<=14?t+=15:n<=30&&(t+=Math.round(15*(1-(n-14)/16))),e.hasContributionGuidelines&&(t+=10),e.orgHasMergedPRs&&(t+=5),e.matchesPreferredCategory&&(t+=5),e.hasExistingPR&&(t-=30),e.isClaimed&&(t-=20),e.closedWithoutMergeCount>0&&e.mergedPRCount===0&&(t-=15),e.featureSignals){let s=e.featureSignals;t+=Math.min(Math.floor(s.reactions/2),10),s.comments>=5&&(t+=5),s.hasMilestone&&(t+=5),s.wontfixNoContributor&&(t+=10)}return Math.max(0,Math.min(100,t))}var Y0=A(()=>{It()});function Q0(e,t){if(t.length===0)return!1;let r=e.split("/")[0]?.toLowerCase();if(!r)return!1;for(let n of t){let s=g2[n];if(s&&s.some(o=>o.toLowerCase()===r))return!0}return!1}function X0(e){let t=new Set;for(let r of e){let n=f2[r];if(n)for(let s of n)t.add(s)}return[...t]}var f2,g2,dk=A(()=>{f2={nonprofit:["nonprofit","social-good","humanitarian","charity","social-impact","civic-tech"],devtools:["developer-tools","devtools","cli","sdk","linter","formatter","build-tool"],infrastructure:["infrastructure","cloud","kubernetes","docker","devops","monitoring","observability"],"web-frameworks":["web-framework","frontend","backend","fullstack","nextjs","react","vue"],"data-ml":["machine-learning","data-science","deep-learning","nlp","data-pipeline","analytics"],education:["education","learning","tutorial","courseware","edtech","teaching"]},g2={nonprofit:["code-for-america","opengovfoundation","ushahidi","hotosm","openfn","democracyearth"],devtools:["eslint","prettier","vitejs","biomejs","oxc-project","ast-grep","turbot"],infrastructure:["kubernetes","hashicorp","grafana","prometheus","open-telemetry","envoyproxy","cncf"],"web-frameworks":["vercel","remix-run","sveltejs","nuxt","astro","redwoodjs","blitz-js"],"data-ml":["huggingface","mlflow","apache","dbt-labs","dagster-io","prefecthq","langchain-ai"],education:["freeCodeCamp","TheOdinProject","exercism","codecademy","oppia","Khan"]}});async function eD(e,t=100,r=10){let n=[];for(let s=1;s<=r;s++){let{data:o}=await e(s);if(n.push(...o),o.length<t)break}return n}var tD=A(()=>{});function Lr(e){return`${h2}:${e}`}function gt(){return pk||(pk=new mk),pk}async function Yf(e,t,r){let n=e.getInflight(t);if(n)return se(Pt,`Dedup hit for ${t}`),await n;let s=r(),o=e.setInflight(t,s);try{return await s}finally{o()}}async function pl(e,t,r){return Yf(e,t,async()=>{let s={},o=e.get(t);o&&(s["if-none-match"]=o.etag);try{let i=await r(s),a=i.headers?.etag;return a&&e.set(t,a,i.data),i.data}catch(i){if(b2(i)){let a=e.get(t);if(a)return se(Pt,`304 cache hit for ${t}`),a.body;se(Pt,`304 but cache entry vanished for ${t}, refetching`);let c=await r({}),u=c.headers?.etag;return u&&e.set(t,u,c.data),c.data}throw i}})}async function nD(e,t,r,n){let s=e.getEntryIfFresh(t,r);return s?(se(Pt,`Time-based cache hit for ${t}`),s.body):Yf(e,t,async()=>{let o=e.getEntryIfFresh(t,r);if(o)return o.body;let i=await n();return e.set(t,"",i),i})}function b2(e){return Fe(e)===304}var nr,Jf,rD,Pt,h2,y2,mk,pk,Dn=A(()=>{nr=B(require("fs"),1),Jf=B(require("path"),1),rD=B(require("crypto"),1);It();pt();ft();Pt="http-cache",h2="v1";y2=1440*60*1e3,mk=class{cacheDir;inflightRequests=new Map;constructor(t){this.cacheDir=t??U0()}keyFor(t){return rD.createHash("sha256").update(t).digest("hex")}pathFor(t){return Jf.join(this.cacheDir,`${this.keyFor(t)}.json`)}getIfFresh(t,r){return this.getEntryIfFresh(t,r)?.body??null}getEntryIfFresh(t,r){let n=this.get(t);if(!n)return null;let s=Date.now()-new Date(n.cachedAt).getTime();return!Number.isFinite(s)||s<0||s>r?null:n}get(t){let r=this.pathFor(t);try{let n=nr.readFileSync(r,"utf-8"),s=JSON.parse(n);return s.url!==t?(se(Pt,`Cache collision detected for ${t}, ignoring`),null):s}catch(n){if(n?.code==="ENOENT")return null;if(n instanceof SyntaxError){se(Pt,`Corrupt cache entry, deleting: ${t}`);try{nr.unlinkSync(r)}catch(o){se(Pt,`Failed to delete corrupt cache entry: ${Y(o)}`)}return null}return H(Pt,`Cache read failed for ${t}: ${Y(n)}`),null}}set(t,r,n){let s={etag:r,url:t,body:n,cachedAt:new Date().toISOString()};try{nr.writeFileSync(this.pathFor(t),JSON.stringify(s),{encoding:"utf-8",mode:384}),se(Pt,`Cached response for ${t}`)}catch(o){H(Pt,`Failed to write cache for ${t}: ${Y(o)}`)}}getInflight(t){return this.inflightRequests.get(t)}setInflight(t,r){return this.inflightRequests.set(t,r),()=>{this.inflightRequests.delete(t)}}evictStale(t=y2){let r=0;try{let n=nr.readdirSync(this.cacheDir),s=Date.now();for(let o of n){if(!o.endsWith(".json"))continue;let i=Jf.join(this.cacheDir,o);try{let a=nr.readFileSync(i,"utf-8"),c=JSON.parse(a);s-new Date(c.cachedAt).getTime()>t&&(nr.unlinkSync(i),r++)}catch{se(Pt,`Removing unreadable cache entry ${o}`);try{nr.unlinkSync(i),r++}catch(a){se(Pt,`Failed to remove stale cache entry ${o}: ${Y(a)}`)}}}}catch(n){n?.code!=="ENOENT"&&H(Pt,`Failed to evict stale cache entries: ${Y(n)}`)}return r>0&&se(Pt,`Evicted ${r} stale cache entries`),r}clear(){try{let t=nr.readdirSync(this.cacheDir);for(let r of t)r.endsWith(".json")&&nr.unlinkSync(Jf.join(this.cacheDir,r));se(Pt,"Cache cleared")}catch(t){t?.code!=="ENOENT"&&H(Pt,`Failed to clear cache: ${Y(t)}`)}}size(){try{return nr.readdirSync(this.cacheDir).filter(t=>t.endsWith(".json")).length}catch(t){return t?.code!=="ENOENT"&&se(Pt,`Failed to read cache size: ${Y(t)}`),0}}},pk=null});function w2(e){return e.event==="cross-referenced"&&!!e.source?.issue?.pull_request}function R2(e,t){let r=e.source?.issue,n=`${t.owner}/${t.repo}#${t.issueNumber}`;if(!r||typeof r.number!="number")return H(Na,`Cross-referenced timeline event for ${n} missing source.issue.number \u2014 possible API shape drift`),null;let s=r.user?.login;if(!s)return H(Na,`Cross-referenced PR #${r.number} for ${n} has no user.login (deleted user?) \u2014 skipping linkedPR metadata`),null;let o=r.html_url;return o?{number:r.number,author:s,state:r.state==="closed"?"closed":"open",merged:!!r.pull_request?.merged_at,url:o,updatedAt:r.updated_at}:(H(Na,`Cross-referenced PR #${r.number} for ${n} missing html_url \u2014 skipping linkedPR metadata`),null)}function k2(e){return e.replace(/<!--[\s\S]*?-->/g," ").replace(/```[\s\S]*?```/g," ").replace(/^\s*[-*] \[ \].*$/gm," ").replace(/^\s*>.*$/gm," ")}function fk(e){let t=k2(e).toLowerCase().split(/(?<=[.!?])|\n+/);for(let r of t){if(P2.test(r))return!0;if(!r.trimEnd().endsWith("?")){if(S2.some(n=>n.test(r))||!v2.test(r)&&_2.some(n=>n.test(r)))return!0;if(!E2.test(r)&&C2.some(n=>n.test(r)))return!0}}return!1}async function oD(e,t,r,n){try{let s=await eD(a=>e.issues.listEventsForTimeline({owner:t,repo:r,issue_number:n,per_page:100,page:a})),o=0,i=null;for(let a of s){let c=a;w2(c)&&(o++,i??=R2(c,{owner:t,repo:r,issueNumber:n}))}return{passed:o===0,linkedPR:i}}catch(s){Be(s);let o=Y(s);return H(Na,`Failed to check for existing PRs on ${t}/${r}#${n}: ${o}. Assuming no existing PR.`),{passed:!0,inconclusive:!0,reason:o,linkedPR:null}}}function gk(e,t){return Lr(`merged-prs:${e}/${t}`)}async function iD(e,t,r,n=fr()){let s=gt(),o=gk(t,r);return Yf(s,o,async()=>{let i=s.getIfFresh(o,A2);if(i!=null&&typeof i=="number")return i;try{await n.waitForBudget();try{let{data:a}=await e.search.issuesAndPullRequests({q:`repo:${t}/${r} is:pr is:merged author:@me`,per_page:1});return s.set(o,"",a.total_count),a.total_count}finally{n.recordCall()}}catch(a){Be(a);let c=Y(a);return H(Na,`Could not check merged PRs in ${t}/${r}: ${c}. Treating as unknown.`),null}})}async function aD(e,t,r,n,s){if(s===0)return{passed:!0};try{let i=Math.max(1,Math.ceil(s/100)),a=i>1?[i-1,i]:[1],c=[];for(let d of a){let p=await e.issues.listComments({owner:t,repo:r,issue_number:n,per_page:100,page:d});c.push(...p.data)}let u=c.length%100;if(c.length>0&&u===0){let d=await e.issues.listComments({owner:t,repo:r,issue_number:n,per_page:100,page:i+1});c.push(...d.data)}for(let d of c)if(fk(d.body||""))return{passed:!1};return{passed:!0}}catch(o){Be(o);let i=Y(o);return H(Na,`Failed to check claim status on ${t}/${r}#${n}: ${i}. Assuming not claimed.`),{passed:!0,inconclusive:!0,reason:i}}}function cD(e){if(!e||e.length<50)return!1;let t=/(^|\n)\s*\d+[.)]\s/.test(e)||/steps?\s+to\s+reproduce|\brepro(duction)?\b/i.test(e),r=/\b(expected|should)\b/i.test(e)&&/\b(actual(ly)?|instead|but|currently|observed|got)\b/i.test(e);return/```|`[^`\n]+`/.test(e)||/\b[\w/.-]+\.(ts|tsx|js|jsx|mjs|cjs|py|rb|go|rs|java|kt|swift|c|cc|cpp|h|hpp|cs|php|sh|vue|svelte)\b/.test(e)||/^\s+at\s+\S+\s+\(/m.test(e)||t&&r}var Na,Qf,S2,sD,_2,v2,C2,P2,E2,A2,hk=A(()=>{tD();ft();pt();Dn();Fa();Na="issue-eligibility",Qf=String.raw`(?:this\b|it\b|that\b|the\b|#\d+|issue\b)`,S2=[new RegExp(String.raw`\bi\s*(?:'ll|will) take ${Qf}`),new RegExp(String.raw`\bi\s*(?:'d|would) (?:like|love) to work on ${Qf}`),new RegExp(String.raw`\bi\s*(?:'d|would) (?:like|love) to (?:\w+ and )?(?:fix|tackle|take on|pick up|implement) ${Qf}`),/\bi\s*(?:'m|am) on it\b/,/\bi\s*(?:'ll|will) submit a pr\b/,/\bassigned to me\b/],sD=String.raw`(?:^\s*|\b(?:i\s*(?:'m|am|'d be|would be|'ll be|will be)|we\s*(?:'re|are|'d be|would be|'ll be|will be))\s+(?:(?:really|very|more than|absolutely|also)\s+)?)`,_2=[new RegExp(String.raw`${sD}(?:happy|glad|willing|keen) to (?:open|send|submit|make|put up|raise|contribute|write) (?:a |the |an )?(?:[\w-]+ ){0,2}(?:pr|pull request|patch|fix)\b`),new RegExp(String.raw`${sD}(?:happy|glad|willing|keen) to (?:have a go|take a stab)\b`),/\bi can (?:send|open|submit|put up) (?:this |it )?(?:as )?(?:a |the )?(?:pr|pull request|patch|fix)\b/,/\bi\s*(?:'ll|will) (?:open|send|put up|raise) a (?:pr|pull request)\b/,/\bi\s*(?:'d|would) love to contribute (?:this|it|a fix|the fix)\b/,/\bi plan to (?:make|send|submit|open) (?:a |the )?(?:[\w-]+ ){0,2}(?:pr|pull request|fix|change)\b/],v2=/\bnot\b|n't\b|\bbut\b|\bunless\b/;C2=[/\bworking on (?:this|it)\b/,/\bworking on a (?:fix|pr)\b/],P2=new RegExp(String.raw`\b(?:can|may|could) i (?:work on|take) ${Qf}`),E2=/\b(?:anyone|anybody|someone|somebody|who|whoever|nobody|no[- ]?one|not)\b/;A2=900*1e3});async function Ga(e,t,r,n){let s=`/repos/${t}/${r}/contents/${n}`,o=`missing:${s}`;if(gt().getIfFresh(o,$2)!==null)return{text:null,transient:!1};try{let i=await pl(gt(),s,a=>e.repos.getContent({owner:t,repo:r,path:n,headers:a}));return i&&typeof i=="object"&&"content"in i&&typeof i.content=="string"?{text:Buffer.from(i.content,"base64").toString("utf-8"),transient:!1}:{text:null,transient:!1}}catch(i){return Fe(i)===404?(gt().set(o,"",!0),{text:null,transient:!1}):(Be(i),H(T2,`Unexpected error fetching ${n} from ${t}/${r}: ${Y(i)}`),{text:null,transient:!0})}}var T2,$2,Xf=A(()=>{ft();pt();Dn();T2="probe-repo-file",$2=14400*1e3});async function x2(e,t,r){let n=new Date(Date.now()-I2*24*60*60*1e3).toISOString().slice(0,10),s=`repo:${t}/${r} is:pr closed:>=${n}`,o=await e.graphql(`query repoMergeStats($merged: String!, $closedUnmerged: String!) {
270
270
  merged: search(type: ISSUE, query: $merged, first: 0) { issueCount }
271
271
  closedUnmerged: search(type: ISSUE, query: $closedUnmerged, first: 0) { issueCount }
272
- }`,{merged:`${s} is:merged`,closedUnmerged:`${s} is:unmerged is:closed`}),i=o.merged.issueCount,a=o.closedUnmerged.issueCount,c=i+a;return{recentMergedPRCount:i,recentMergeRate:c>0?i/c:null}}function lD(){let e=Date.now();for(let[t,r]of Ln.entries())e-r.fetchedAt>dD&&Ln.delete(t);if(Ln.size>uD){let r=Array.from(Ln.entries()).sort((n,s)=>n[1].fetchedAt-s[1].fetchedAt).slice(0,Ln.size-uD);for(let[n]of r)Ln.delete(n)}}async function pD(e,t,r){let n=gt(),s=Lr(`health:${t}/${r}`);try{return await nD(n,s,x2,async()=>{let o=`/repos/${t}/${r}`,i=await pl(n,o,g=>e.repos.get({owner:t,repo:r,headers:g})),a=`/repos/${t}/${r}/commits?per_page=1`,d=(await pl(n,a,g=>e.repos.listCommits({owner:t,repo:r,per_page:1,headers:g})))[0]?.commit?.author?.date||i.pushed_at,p=Ma(new Date(d)),m="unknown",f=await I2(e,t,r);return{repo:`${t}/${r}`,lastCommitAt:d,daysSinceLastCommit:p,openIssuesCount:i.open_issues_count,avgIssueResponseDays:0,ciStatus:m,isActive:p<30,stargazersCount:i.stargazers_count,forksCount:i.forks_count,language:i.language,recentMergedPRCount:f.recentMergedPRCount,recentMergeRate:f.recentMergeRate}})}catch(o){Be(o);let i=Y(o);return H($2,`Error checking project health for ${t}/${r}: ${i}`),{repo:`${t}/${r}`,checkFailed:!0,failureReason:i}}}async function mD(e,t,r){let n=`${t}/${r}`,s=Ln.get(n);if(s&&Date.now()-s.fetchedAt<dD)return s.guidelines;let o=yk.get(n);if(o)return o;let i=D2(e,t,r);yk.set(n,i);try{return await i}finally{yk.delete(n)}}async function D2(e,t,r){let n=`${t}/${r}`,s=["CONTRIBUTING.md",".github/CONTRIBUTING.md","docs/CONTRIBUTING.md","contributing.md"],o=await Promise.allSettled(s.map(i=>Ga(e,t,r,i)));for(let i of o)if(i.status==="rejected"&&(Me(i.reason)===401||mt(i.reason)))throw i.reason;for(let i of o)if(i.status==="fulfilled"&&i.value.text){let a=L2(i.value.text);return Ln.set(n,{guidelines:a,fetchedAt:Date.now()}),lD(),a}Ln.set(n,{guidelines:void 0,fetchedAt:Date.now()}),lD()}function L2(e){let t={rawContent:e},r=e.toLowerCase();if(r.includes("branch")){let n=e.match(/branch[^\n]{0,200}?(?:named?|format|convention)[^\n]{0,200}?[`"]([^`"\n]{1,100})[`"]/i);n&&(t.branchNamingConvention=n[1])}if(r.includes("conventional commit"))t.commitMessageFormat="conventional commits";else if(r.includes("commit message")){let n=e.match(/commit message[^\n]{0,200}?[`"]([^`"\n]{1,100})[`"]/i);n&&(t.commitMessageFormat=n[1])}return r.includes("jest")?t.testFramework="Jest":r.includes("rspec")?t.testFramework="RSpec":r.includes("pytest")?t.testFramework="pytest":r.includes("mocha")&&(t.testFramework="Mocha"),r.includes("eslint")?t.linter="ESLint":r.includes("rubocop")?t.linter="RuboCop":r.includes("prettier")&&(t.formatter="Prettier"),(/\bcla\b/.test(r)||r.includes("contributor license agreement"))&&(t.claRequired=!0),t}var $2,O2,Ln,dD,x2,uD,yk,fD=A(()=>{It();ft();pt();Dn();Xf();$2="repo-health",O2=90;Ln=new Map,dD=3600*1e3,x2=14400*1e3,uD=100;yk=new Map});function wk(e){if(!e)return{matched:!1,matchedKeywords:[]};let t=e.toLowerCase(),r=bk.filter(n=>t.includes(n));return{matched:r.length>0,matchedKeywords:r}}async function N2(e,t,r,n){let s=await Promise.allSettled(n.map(i=>Ga(e,t,r,i))),o=!1;for(let i of s)if(i.status==="fulfilled"){if(i.value.transient&&(o=!0),i.value.text)return{text:i.value.text,hadTransientFailure:o}}else{if(mt(i.reason)||Me(i.reason)===401)throw i.reason;o=!0}return{text:null,hadTransientFailure:o}}function G2(e){if(!e||typeof e!="object")return!1;let t=e;return!(typeof t.matched!="boolean"||!Array.isArray(t.matchedKeywords)||t.sourceFile!==null&&typeof t.sourceFile!="string")}async function gD(e,t,r,n){let s=gt(),o=Lr(`anti-llm-policy:${t}/${r}`),i=s.getIfFresh(o,M2);if(G2(i))return i;let a=!1;for(let u of F2){let d,p=!1;if(u.canonical==="CONTRIBUTING.md"&&n?.contributingText!==void 0?d=n.contributingText:{text:d,hadTransientFailure:p}=await N2(e,t,r,u.paths),p&&(a=!0),!d)continue;let{matched:m,matchedKeywords:f}=wk(d);if(m){let g={matched:!0,matchedKeywords:f,sourceFile:u.canonical};return s.set(o,"",g),g}}let c={matched:!1,matchedKeywords:[],sourceFile:null};return a||s.set(o,"",c),c}var M2,bk,F2,Rk=A(()=>{ft();Dn();Xf();M2=3600*1e3,bk=["no ai-generated","no ai generated","no ai-assisted","no ai assisted","no llm-generated","no llm generated","no copilot-generated","no chatgpt-generated","human-authored only","human authored only","human-written only","human written only","ai-free contributions","llm-free contributions","ai-generated code is not allowed","ai-generated code will not be accepted","do not submit ai-generated","do not submit llm-generated","do not use ai to","do not use llms","do not use copilot","do not use chatgpt","without ai assistance","without llm assistance","no use of generative ai","ban on ai-generated","prohibit ai-generated","prohibits ai-generated","not be completed by automated agents","must not be done by automated agents","tasks are for humans only","do not generate code","explicitly rejected the generative use of agents","you are explicitly forbidden from modifying"];F2=[{canonical:"CONTRIBUTING.md",paths:["CONTRIBUTING.md",".github/CONTRIBUTING.md","docs/CONTRIBUTING.md","contributing.md"]},{canonical:"CODE_OF_CONDUCT.md",paths:["CODE_OF_CONDUCT.md",".github/CODE_OF_CONDUCT.md","docs/CODE_OF_CONDUCT.md","code_of_conduct.md"]},{canonical:"AGENTS.md",paths:["AGENTS.md"]},{canonical:"AI_POLICY.md",paths:["AI_POLICY.md",".github/AI_POLICY.md"]},{canonical:"README.md",paths:["README.md","readme.md","Readme.md"]}]});function _k(e){return e?/(?:^|-)bot(?:-|$)/i.test(e):!1}function eg(e,t,r){return`${e}/${t}#${r}`}function U2(e){return{id:e.databaseId,title:e.title,body:e.body??"",state:e.state==="CLOSED"?"closed":"open",labels:e.labels.nodes.map(t=>t.name),commentCount:e.comments.totalCount,createdAt:e.createdAt,updatedAt:e.updatedAt,authorLogin:e.author?.login,authorIsBot:e.author?.__typename==="Bot"||/\[bot\]$/i.test(e.author?.login??""),authorLooksLikeBot:_k(e.author?.login)}}async function yD(e,t){let r=new Map;if(t.length===0)return r;let n=[...new Map(t.map(u=>[eg(u.owner,u.repo,u.number),u])).values()],s=[],o=[],i={};n.forEach((u,d)=>{s.push(`$o${d}: String!, $n${d}: String!, $num${d}: Int!`),i[`o${d}`]=u.owner,i[`n${d}`]=u.repo,i[`num${d}`]=u.number,o.push(`i${d}: repository(owner: $o${d}, name: $n${d}) {
272
+ }`,{merged:`${s} is:merged`,closedUnmerged:`${s} is:unmerged is:closed`}),i=o.merged.issueCount,a=o.closedUnmerged.issueCount,c=i+a;return{recentMergedPRCount:i,recentMergeRate:c>0?i/c:null}}function lD(){let e=Date.now();for(let[t,r]of Ln.entries())e-r.fetchedAt>dD&&Ln.delete(t);if(Ln.size>uD){let r=Array.from(Ln.entries()).sort((n,s)=>n[1].fetchedAt-s[1].fetchedAt).slice(0,Ln.size-uD);for(let[n]of r)Ln.delete(n)}}async function pD(e,t,r){let n=gt(),s=Lr(`health:${t}/${r}`);try{return await nD(n,s,D2,async()=>{let o=`/repos/${t}/${r}`,i=await pl(n,o,g=>e.repos.get({owner:t,repo:r,headers:g})),a=`/repos/${t}/${r}/commits?per_page=1`,d=(await pl(n,a,g=>e.repos.listCommits({owner:t,repo:r,per_page:1,headers:g})))[0]?.commit?.author?.date||i.pushed_at,p=Ma(new Date(d)),m="unknown",f=await x2(e,t,r);return{repo:`${t}/${r}`,lastCommitAt:d,daysSinceLastCommit:p,openIssuesCount:i.open_issues_count,avgIssueResponseDays:0,ciStatus:m,isActive:p<30,stargazersCount:i.stargazers_count,forksCount:i.forks_count,language:i.language,recentMergedPRCount:f.recentMergedPRCount,recentMergeRate:f.recentMergeRate}})}catch(o){Be(o);let i=Y(o);return H(O2,`Error checking project health for ${t}/${r}: ${i}`),{repo:`${t}/${r}`,checkFailed:!0,failureReason:i}}}async function mD(e,t,r){let n=`${t}/${r}`,s=Ln.get(n);if(s&&Date.now()-s.fetchedAt<dD)return s.guidelines;let o=yk.get(n);if(o)return o;let i=L2(e,t,r);yk.set(n,i);try{return await i}finally{yk.delete(n)}}async function L2(e,t,r){let n=`${t}/${r}`,s=["CONTRIBUTING.md",".github/CONTRIBUTING.md","docs/CONTRIBUTING.md","contributing.md"],o=await Promise.allSettled(s.map(i=>Ga(e,t,r,i)));for(let i of o)if(i.status==="rejected"&&(Fe(i.reason)===401||mt(i.reason)))throw i.reason;for(let i of o)if(i.status==="fulfilled"&&i.value.text){let a=M2(i.value.text);return Ln.set(n,{guidelines:a,fetchedAt:Date.now()}),lD(),a}Ln.set(n,{guidelines:void 0,fetchedAt:Date.now()}),lD()}function M2(e){let t={rawContent:e},r=e.toLowerCase();if(r.includes("branch")){let n=e.match(/branch[^\n]{0,200}?(?:named?|format|convention)[^\n]{0,200}?[`"]([^`"\n]{1,100})[`"]/i);n&&(t.branchNamingConvention=n[1])}if(r.includes("conventional commit"))t.commitMessageFormat="conventional commits";else if(r.includes("commit message")){let n=e.match(/commit message[^\n]{0,200}?[`"]([^`"\n]{1,100})[`"]/i);n&&(t.commitMessageFormat=n[1])}return r.includes("jest")?t.testFramework="Jest":r.includes("rspec")?t.testFramework="RSpec":r.includes("pytest")?t.testFramework="pytest":r.includes("mocha")&&(t.testFramework="Mocha"),r.includes("eslint")?t.linter="ESLint":r.includes("rubocop")?t.linter="RuboCop":r.includes("prettier")&&(t.formatter="Prettier"),(/\bcla\b/.test(r)||r.includes("contributor license agreement"))&&(t.claRequired=!0),t}var O2,I2,Ln,dD,D2,uD,yk,fD=A(()=>{It();ft();pt();Dn();Xf();O2="repo-health",I2=90;Ln=new Map,dD=3600*1e3,D2=14400*1e3,uD=100;yk=new Map});function wk(e){if(!e)return{matched:!1,matchedKeywords:[]};let t=e.toLowerCase(),r=bk.filter(n=>t.includes(n));return{matched:r.length>0,matchedKeywords:r}}async function G2(e,t,r,n){let s=await Promise.allSettled(n.map(i=>Ga(e,t,r,i))),o=!1;for(let i of s)if(i.status==="fulfilled"){if(i.value.transient&&(o=!0),i.value.text)return{text:i.value.text,hadTransientFailure:o}}else{if(mt(i.reason)||Fe(i.reason)===401)throw i.reason;o=!0}return{text:null,hadTransientFailure:o}}function U2(e){if(!e||typeof e!="object")return!1;let t=e;return!(typeof t.matched!="boolean"||!Array.isArray(t.matchedKeywords)||t.sourceFile!==null&&typeof t.sourceFile!="string")}async function gD(e,t,r,n){let s=gt(),o=Lr(`anti-llm-policy:${t}/${r}`),i=s.getIfFresh(o,F2);if(U2(i))return i;let a=!1;for(let u of N2){let d,p=!1;if(u.canonical==="CONTRIBUTING.md"&&n?.contributingText!==void 0?d=n.contributingText:{text:d,hadTransientFailure:p}=await G2(e,t,r,u.paths),p&&(a=!0),!d)continue;let{matched:m,matchedKeywords:f}=wk(d);if(m){let g={matched:!0,matchedKeywords:f,sourceFile:u.canonical};return s.set(o,"",g),g}}let c={matched:!1,matchedKeywords:[],sourceFile:null};return a||s.set(o,"",c),c}var F2,bk,N2,Rk=A(()=>{ft();Dn();Xf();F2=3600*1e3,bk=["no ai-generated","no ai generated","no ai-assisted","no ai assisted","no llm-generated","no llm generated","no copilot-generated","no chatgpt-generated","human-authored only","human authored only","human-written only","human written only","ai-free contributions","llm-free contributions","ai-generated code is not allowed","ai-generated code will not be accepted","do not submit ai-generated","do not submit llm-generated","do not use ai to","do not use llms","do not use copilot","do not use chatgpt","without ai assistance","without llm assistance","no use of generative ai","ban on ai-generated","prohibit ai-generated","prohibits ai-generated","not be completed by automated agents","must not be done by automated agents","tasks are for humans only","do not generate code","explicitly rejected the generative use of agents","you are explicitly forbidden from modifying"];N2=[{canonical:"CONTRIBUTING.md",paths:["CONTRIBUTING.md",".github/CONTRIBUTING.md","docs/CONTRIBUTING.md","contributing.md"]},{canonical:"CODE_OF_CONDUCT.md",paths:["CODE_OF_CONDUCT.md",".github/CODE_OF_CONDUCT.md","docs/CODE_OF_CONDUCT.md","code_of_conduct.md"]},{canonical:"AGENTS.md",paths:["AGENTS.md"]},{canonical:"AI_POLICY.md",paths:["AI_POLICY.md",".github/AI_POLICY.md"]},{canonical:"README.md",paths:["README.md","readme.md","Readme.md"]}]});function _k(e){return e?/(?:^|-)bot(?:-|$)/i.test(e):!1}function eg(e,t,r){return`${e}/${t}#${r}`}function j2(e){return{id:e.databaseId,title:e.title,body:e.body??"",state:e.state==="CLOSED"?"closed":"open",labels:e.labels.nodes.map(t=>t.name),commentCount:e.comments.totalCount,createdAt:e.createdAt,updatedAt:e.updatedAt,authorLogin:e.author?.login,authorIsBot:e.author?.__typename==="Bot"||/\[bot\]$/i.test(e.author?.login??""),authorLooksLikeBot:_k(e.author?.login)}}async function yD(e,t){let r=new Map;if(t.length===0)return r;let n=[...new Map(t.map(u=>[eg(u.owner,u.repo,u.number),u])).values()],s=[],o=[],i={};n.forEach((u,d)=>{s.push(`$o${d}: String!, $n${d}: String!, $num${d}: Int!`),i[`o${d}`]=u.owner,i[`n${d}`]=u.repo,i[`num${d}`]=u.number,o.push(`i${d}: repository(owner: $o${d}, name: $n${d}) {
273
273
  issue(number: $num${d}) {
274
274
  databaseId
275
275
  title
@@ -284,7 +284,7 @@ The gh CLI is recommended - install from https://cli.github.com`);return e}var w
284
284
  }`)});let a=`query batchIssueCores(${s.join(", ")}) {
285
285
  ${o.join(`
286
286
  `)}
287
- }`,c;try{c=await e.graphql(a,i)}catch(u){Be(u);let d=u.data;if(d)c=d;else return H(Ua,`GraphQL prefetch failed, falling back to REST: ${Y(u)}`),r}return n.forEach((u,d)=>{let p=c?.[`i${d}`]?.issue;!p||p.databaseId==null||r.set(eg(u.owner,u.repo,u.number),U2(p))}),r}async function bD(e,t,r){if(r.length===0)return;if(!Sk.test(t)){H(Ua,"Skipping merged-PR prefetch: username failed validation (falling back to REST)");return}let n=new Set,s=[];for(let a of r){let c=`${a.owner}/${a.repo}`;if(!n.has(c)){if(n.add(c),!Sk.test(a.owner)||!Sk.test(a.repo)){H(Ua,`Skipping merged-PR prefetch for "${c}": failed validation (falling back to REST)`);continue}s.push(a)}}if(s.length===0)return;let o=gt(),i=[];for(let a=0;a<s.length;a+=hD)i.push(j2(e,t,s.slice(a,a+hD),o));await Promise.all(i)}async function j2(e,t,r,n){let s=[],o=["viewer { login }"],i={};r.forEach((d,p)=>{s.push(`$q${p}: String!`),i[`q${p}`]=`is:pr is:merged author:${t} repo:${d.owner}/${d.repo}`,o.push(`r${p}: search(query: $q${p}, type: ISSUE, first: 1) { issueCount }`)});let a=`query batchMergedPRCounts(${s.join(", ")}) {
287
+ }`,c;try{c=await e.graphql(a,i)}catch(u){Be(u);let d=u.data;if(d)c=d;else return H(Ua,`GraphQL prefetch failed, falling back to REST: ${Y(u)}`),r}return n.forEach((u,d)=>{let p=c?.[`i${d}`]?.issue;!p||p.databaseId==null||r.set(eg(u.owner,u.repo,u.number),j2(p))}),r}async function bD(e,t,r){if(r.length===0)return;if(!Sk.test(t)){H(Ua,"Skipping merged-PR prefetch: username failed validation (falling back to REST)");return}let n=new Set,s=[];for(let a of r){let c=`${a.owner}/${a.repo}`;if(!n.has(c)){if(n.add(c),!Sk.test(a.owner)||!Sk.test(a.repo)){H(Ua,`Skipping merged-PR prefetch for "${c}": failed validation (falling back to REST)`);continue}s.push(a)}}if(s.length===0)return;let o=gt(),i=[];for(let a=0;a<s.length;a+=hD)i.push(z2(e,t,s.slice(a,a+hD),o));await Promise.all(i)}async function z2(e,t,r,n){let s=[],o=["viewer { login }"],i={};r.forEach((d,p)=>{s.push(`$q${p}: String!`),i[`q${p}`]=`is:pr is:merged author:${t} repo:${d.owner}/${d.repo}`,o.push(`r${p}: search(query: $q${p}, type: ISSUE, first: 1) { issueCount }`)});let a=`query batchMergedPRCounts(${s.join(", ")}) {
288
288
  ${o.join(`
289
289
  `)}
290
290
  }`,c;try{c=await e.graphql(a,i)}catch(d){Be(d);let p=d.data;if(p)c=p;else{H(Ua,`Merged-PR prefetch batch failed, falling back to REST: ${Y(d)}`);return}}let u=c?.viewer?.login;if(!u||u.toLowerCase()!==t.toLowerCase()){u&&H(Ua,"Merged-PR prefetch identity mismatch (configured username != authenticated login); leaving cache cold so REST @me answers");return}r.forEach((d,p)=>{let m=c?.[`r${p}`],f=m&&"issueCount"in m?m.issueCount:void 0;typeof f=="number"&&n.set(gk(d.owner,d.repo),"",f)})}async function wD(e,t,r){let n=Math.min(Math.max(Math.trunc(r)||1,1),100),s=`query searchIssuesBroad($q: String!, $first: Int!) {
@@ -300,42 +300,42 @@ ${o.join(`
300
300
  }
301
301
  }
302
302
  }
303
- }`,o;try{o=await e.graphql(s,{q:t,first:n})}catch(c){Be(c);let u=c.data;if(u)o=u;else return H(Ua,`GraphQL broad search failed, falling back to REST: ${Y(c)}`),null}let i=o?.search;if(!i)return null;let a=[];for(let c of i.nodes??[]){if(!c?.url)continue;let u=c.repository?.nameWithOwner;u&&a.push({html_url:c.url,repository_url:`https://api.github.com/repos/${u}`,updated_at:c.updatedAt??"",title:c.title,labels:c.labels?.nodes??[],repositoryStars:c.repository?.stargazerCount})}return{total_count:i.issueCount??0,items:a}}var Ua,Sk,hD,vk=A(()=>{ft();pt();Dn();hk();Ua="issue-graphql";Sk=/^[A-Za-z0-9_.-]+$/,hD=15});function q2(e){let{issue:t,linkedPRExists:r}=e,n=(t.body??"").slice(0,W2);return["You triage open-source issues for an autonomous contribution agent.","Classify the issue into exactly one bucket:","- pursue: small, concrete bug or feature with clear acceptance; safe for an autonomous agent to attempt without further design input","- investigate: tractable but needs human reading first (ambiguous scope, design questions, recently-touched files)","- skip: not actionable autonomously (epic, creative, blocked, requires upstream change, requires infra)","","Return JSON only matching the provided schema. Reasons must be short phrases, not sentences. 1-3 reasons total.","","Issue:",`Title: ${t.title}`,`Body: ${n}`,`Labels: ${t.labels.join(", ")}`,`Linked PR exists: ${r}`].join(`
304
- `)}function RD(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="http:"&&t.protocol!=="https:")return!1;let r=t.hostname.replace(/^\[|\]$/g,"").toLowerCase();if(r==="localhost"||r==="::1")return!0;let n=r.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(n){let s=Number(n[1]),o=Number(n[2]);return s===127||s===10||s===192&&o===168||s===172&&o>=16&&o<=31}return r.includes(":")?r.startsWith("fc")||r.startsWith("fd")||r.startsWith("fe80"):!r.includes(".")||r.endsWith(".local")}function SD(e){if(!(e===""||RD(e)))throw new ot(`slmTriageHost must be an http(s) URL pointing at localhost or a private/LAN address (got "${e}"). Example: http://192.168.1.20:11434`)}async function _D(e,t){if(!t.model)return null;let r=t.host??B2;if(!RD(r))return H(z2,`slmTriageHost "${r}" is not a local/private address; skipping SLM triage`),null;let n=t.timeoutMs??H2,s=t.fetchImpl??fetch,o;try{o=await s(`${r}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t.model,messages:[{role:"user",content:q2(e)}],stream:!1,format:V2,options:{temperature:.1}}),signal:AbortSignal.timeout(n),redirect:"error"})}catch{return null}if(!o.ok)return null;let i;try{i=await o.json()}catch{return null}let a=i?.message?.content;if(typeof a!="string")return null;let c;try{c=JSON.parse(a)}catch{return null}return Z2(c)?{decision:c.decision,confidence:c.confidence,reasons:c.reasons,modelVersion:t.model}:null}function vD(e){return{issue:{title:e.issue.title,labels:e.issue.labels,body:e.issue.body},linkedPRExists:!!e.linkedPR}}function Z2(e){if(typeof e!="object"||e===null)return!1;let t=e;return!(t.decision!=="pursue"&&t.decision!=="investigate"&&t.decision!=="skip"||t.confidence!=="high"&&t.confidence!=="medium"&&t.confidence!=="low"||!Array.isArray(t.reasons)||t.reasons.length===0||t.reasons.length>3||!t.reasons.every(r=>typeof r=="string"))}var z2,B2,H2,W2,V2,kk=A(()=>{ft();pt();z2="slm-triage",B2="http://127.0.0.1:11434",H2=15e3,W2=2e3,V2={type:"object",properties:{decision:{type:"string",enum:["pursue","investigate","skip"]},confidence:{type:"string",enum:["high","medium","low"]},reasons:{type:"array",items:{type:"string"},minItems:1,maxItems:3}},required:["decision","confidence","reasons"]}});function Y2(e){return e.checkFailed||e.recentMergedPRCount==null?null:e.recentMergedPRCount>0?!0:e.recentMergeRate==null?null:!1}function Q2(e){let t=[],r=[],n=[];e.noExistingPR||t.push(e.ownPR?"Your PR is already in flight for this issue":e.linkedPRMerged?"A PR for this issue was already merged":e.linkedPRClosed?"A PR for this issue was closed without merging":"Existing PR found for this issue"),e.notClaimed||t.push("Issue appears to be claimed by someone"),e.existingPRInconclusive&&t.push(`Could not verify absence of existing PRs: ${e.existingPRReason||"API error"}`),e.claimInconclusive&&t.push(`Could not verify claim status: ${e.claimReason||"API error"}`),e.projectCheckFailed?t.push(`Could not verify project activity: ${e.projectFailureReason||"API error"}`):e.projectIsActive||t.push("Project may be inactive"),e.clearRequirements||t.push("Issue requirements are unclear"),e.contributionGuidelinesFound||t.push("No CONTRIBUTING.md found"),e.repoAcceptsContributions===!1?t.push("Repo has merged no PRs in the last 90 days"):e.repoAcceptsContributions===null&&t.push("Could not verify whether the repo merges PRs"),e.noExistingPR||(e.ownPR?n.push("You already have a PR in flight"):e.linkedPRMerged?n.push("Linked PR already merged"):e.linkedPRClosed?n.push("Linked PR closed without merge"):n.push("Has existing PR")),e.notClaimed||n.push("Already claimed"),!e.projectIsActive&&!e.projectCheckFailed&&n.push("Inactive project"),e.clearRequirements||n.push("Unclear requirements"),e.repoAcceptsContributions===!1&&n.push("Repo has no recent merged PRs"),e.noExistingPR&&r.push("No existing PR"),e.notClaimed&&r.push("Not claimed"),e.projectIsActive&&!e.projectCheckFailed&&r.push("Active project"),e.clearRequirements&&r.push("Clear requirements"),e.contributionGuidelinesFound&&r.push("Has contribution guidelines"),e.effectiveMergedCount>0&&r.push(`Trusted project (${e.effectiveMergedCount} PR${e.effectiveMergedCount>1?"s":""} merged)`),e.orgHasMergedPRs&&r.push(`Org affinity (merged PRs in other ${e.orgName} repos)`),e.matchesCategory&&r.push("Matches preferred project category"),e.issueClosed&&n.push("Issue is closed"),e.notTakeableReason&&n.push(e.notTakeableReason);let s;e.issueClosed||e.linkedPRMerged||e.linkedPRClosed||e.ownPR||e.notTakeableReason?s="skip":e.passedAllChecks&&e.repoAcceptsContributions!==!1?s="approve":n.length>2?s="skip":s="needs_review";let o=e.projectCheckFailed||e.existingPRInconclusive||e.claimInconclusive||e.mergedCountInconclusive||e.repoAcceptsContributions===null;return s==="approve"&&o&&(s="needs_review",t.push("Recommendation downgraded: one or more checks were inconclusive")),e.cautionReasons?.length&&(n.push(...e.cautionReasons),s==="approve"&&(s="needs_review")),{notes:t,reasonsToApprove:r,reasonsToSkip:n,recommendation:s}}var ja,K2,J2,Ss,tg=A(()=>{It();ft();pt();Y0();dk();hk();fD();Rk();vk();Dn();Fa();kk();ja="issue-vetting",K2=3,J2=900*1e3;Ss=class{octokit;stateReader;budgetTracker;constructor(t,r,n=fr()){this.octokit=t,this.stateReader=r,this.budgetTracker=n}async vetIssue(t,r){let n=gt(),s=r?.featureSignals?`:r${r.featureSignals.reactions}c${r.featureSignals.comments}m${r.featureSignals.hasMilestone?1:0}o${r.featureSignals.onRoadmap?1:0}w${r.featureSignals.wontfixNoContributor?1:0}`:"",o=Lr(`vet:${t}${s}`),i=n.getIfFresh(o,J2);if(i&&typeof i=="object"&&"issue"in i&&"viabilityScore"in i)return se(ja,`Vetting cache hit for ${t}`),i;let a=Ao(t);if(!a||a.type!=="issues")throw new ot(`Invalid issue URL: ${t}`);let{owner:c,repo:u,number:d}=a,p=`${c}/${u}`,m=r?.prefetched??await this.fetchIssueCore(c,u,d),f=this.stateReader.getReposWithMergedPRs(),g=f.includes(p),[h,b,w,y,S]=await Promise.all([oD(this.octokit,c,u,d),aD(this.octokit,c,u,d,m.commentCount),pD(this.octokit,c,u),mD(this.octokit,c,u),g?Promise.resolve(0):iD(this.octokit,c,u,this.budgetTracker)]),k=await gD(this.octokit,c,u,{contributingText:y?.rawContent}),R=h.passed,P=b.passed,C=this.stateReader.getGitHubUsername?.()??"",E=C!==""&&m.authorLogin?.toLowerCase()===C.toLowerCase(),T;m.authorIsBot?T="Filed by a bot account":!E&&fk(m.body)&&(T="Reporter offered to send the fix");let M=[];!m.authorIsBot&&m.authorLooksLikeBot&&M.push("Author login looks like a bot"),k.matched&&M.push(`AI contribution policy in ${k.sourceFile??"repo docs"}`);let G=h.linkedPR,X=!R&&!!G&&G.state==="open"&&!G.merged&&C!==""&&G.author.toLowerCase()===C.toLowerCase(),ve=!!G&&G.merged,he=!!G&&G.state==="closed"&&!G.merged,oe=cD(m.body),Z=w.checkFailed?!0:w.isActive,$e=Y2(w),Re={passedAllChecks:R&&P&&Z&&oe,checks:{noExistingPR:R,notClaimed:P,projectActive:Z,clearRequirements:oe,contributionGuidelinesFound:!!y},contributionGuidelines:y,linkedPR:h.linkedPR,notes:[]},Xe={id:m.id,url:t,repo:p,number:d,title:m.title,status:"candidate",labels:m.labels,createdAt:m.createdAt,updatedAt:m.updatedAt,vetted:!0,vettingResult:Re},Ke=!g&&S===null,tt=g?1:S??0,ct=p.split("/")[0],sr=!1;ct&&p.includes("/")&&(sr=f.some(Et=>Et.startsWith(ct+"/")&&Et!==p));let et=Q0(p,this.stateReader.getProjectCategories()),Je=m.state==="closed",Fr=w.checkFailed||!!h.inconclusive||!!b.inconclusive||Ke||$e===null,{notes:Ps,reasonsToApprove:Es,reasonsToSkip:Fn,recommendation:Wo}=Q2({noExistingPR:R,ownPR:X,linkedPRMerged:ve,linkedPRClosed:he,notClaimed:P,clearRequirements:oe,contributionGuidelinesFound:!!y,projectIsActive:w.checkFailed?!1:w.isActive,projectCheckFailed:!!w.checkFailed,projectFailureReason:w.failureReason,existingPRInconclusive:!!h.inconclusive,existingPRReason:h.inconclusive?h.reason:void 0,claimInconclusive:!!b.inconclusive,claimReason:b.inconclusive?b.reason:void 0,mergedCountInconclusive:Ke,effectiveMergedCount:tt,orgName:ct,orgHasMergedPRs:sr,matchesCategory:et,issueClosed:Je,passedAllChecks:Re.passedAllChecks,repoAcceptsContributions:$e,notTakeableReason:T,cautionReasons:M});Re.notes=Ps;let Vo=w.checkFailed?0:K0(w.stargazersCount??0,w.forksCount??0);w.checkFailed&&Vo===0&&Re.notes.push("Repo quality bonus unavailable: could not fetch star/fork counts due to API error");let qo=this.stateReader.getRepoScore(p),K=J0({repoScore:qo,hasExistingPR:!R,isClaimed:!P,clearRequirements:oe,hasContributionGuidelines:!!y,issueUpdatedAt:m.updatedAt,closedWithoutMergeCount:this.stateReader.getClosedWithoutMergeCount?.(p)??0,mergedPRCount:tt,orgHasMergedPRs:sr,repoQualityBonus:Vo,matchesPreferredCategory:et,featureSignals:r?.featureSignals}),He=this.stateReader.getStarredRepos(),Wt="normal";tt>0?Wt="merged_pr":He.includes(p)&&(Wt="starred");let qe=this.stateReader.getSLMTriageConfig(),xt=null;if(qe){let Et={model:qe.model};qe.host&&(Et.host=qe.host),xt=await _D(vD({issue:{...Xe,body:m.body},linkedPR:h.linkedPR??null}),Et)}let yr={issue:Xe,issueState:Je?"closed":"open",vettingResult:Re,projectHealth:w,antiLLMPolicy:k,slmTriage:xt,recommendation:Wo,reasonsToSkip:Fn,reasonsToApprove:Es,viabilityScore:K,searchPriority:Wt};return Fr||n.set(o,"",yr),yr}async fetchIssueCore(t,r,n){let{data:s}=await this.octokit.issues.get({owner:t,repo:r,issue_number:n});return{id:s.id,title:s.title,body:s.body||"",state:s.state==="closed"?"closed":"open",labels:s.labels.map(o=>typeof o=="string"?o:o.name||""),commentCount:s.comments,createdAt:s.created_at,updatedAt:s.updated_at,authorLogin:s.user?.login,authorIsBot:s.user?.type==="Bot"||/\[bot\]$/i.test(s.user?.login??""),authorLooksLikeBot:_k(s.user?.login)}}async prefetchMergedPRCounts(t){let r=this.stateReader.getGitHubUsername?.()??"";if(!r)return;let n=new Set(this.stateReader.getReposWithMergedPRs()),s=new Set,o=[];for(let{owner:i,repo:a}of t){let c=`${i}/${a}`;n.has(c)||s.has(c)||(s.add(c),o.push({owner:i,repo:a}))}o.length!==0&&await bD(this.octokit,r,o)}async vetIssuesParallel(t,r,n){let s=[],o=new Map,i=0,a=0,c=0,u=null,d=null,p=0,m=new Set,f=[...new Set(t)],g=f.flatMap(y=>{let S=Ao(y);return S&&S.type==="issues"?[{owner:S.owner,repo:S.repo,number:S.number}]:[]}),[h]=await Promise.all([yD(this.octokit,g),this.prefetchMergedPRCounts(g)]),b=y=>{let S=Ao(y);return S&&S.type==="issues"?h.get(eg(S.owner,S.repo,S.number)):void 0};for(let y of f){if(s.length>=r||u)break;let S=Ao(y),k=S?`${S.owner}/${S.repo}`:null;if(k&&m.has(k)){se(ja,`Skipping ${y}: repo already returned 403`);continue}c++;let R=b(y),P=this.vetIssue(y,R?{prefetched:R}:void 0).then(C=>{s.length<r&&(n&&(C.searchPriority=n),s.push(C))}).catch(C=>{if(Me(C)===401){u??=C;return}if(L0(C)){d??=C,p++,i++,k&&m.add(k),H(ja,`Access forbidden for ${y} (SAML/token scope?) \u2014 skipping this repo:`,Y(C));return}i++,mt(C)&&a++,H(ja,`Error vetting issue ${y}:`,Y(C))}).finally(()=>o.delete(y));o.set(y,P),o.size>=K2&&await Promise.race(o.values())}if(await Promise.allSettled(o.values()),u)throw s.length>0&&H(ja,`Auth failed mid-batch after ${s.length} successful vet(s) \u2014 discarding partial results`),u;if(d&&c>0&&p===c)throw d;let w=i===c&&c>0;return w&&H(ja,`All ${c} issue(s) failed vetting. This may indicate a systemic issue (rate limit, auth, network).`),{candidates:s.slice(0,r),allFailed:w,rateLimitHit:a>0}}}});function CD(){return Ck}function PD(){Ck=0}function t4(e){return e.length===0?"":`label:${e.map(t=>JSON.stringify(t)).join(",")}`}function ED(e,t){let r=new Set;for(let n of e)for(let s of cl[n]??[])r.add(s);for(let n of t)r.add(n);return[...r]}function AD(e){let t=[],r=Math.max(...e.map(n=>n.length),0);for(let n=0;n<r;n++)for(let s of e)n<s.length&&t.push(s[n]);return t}async function Pk(e,t,r=fr()){let n=Lr(`search:${t.q}:${t.sort}:${t.order}:${t.per_page}`),s=gt(),o=s.getIfFresh(n,TD);if(o)return se(gr,"Search cache hit for query"),o;await r.waitForBudget();let i;try{i=(await e.search.issuesAndPullRequests(t)).data}finally{r.recordCall()}return i.items.length>0?s.set(n,"",i):se(gr,"Skipping cache for empty search result (possible rate limit artifact)"),i}async function Ek(e,t,r=fr()){let n=Lr(`gqlsearch2:${t.q}:${t.sort}:${t.order}:${t.per_page}`),s=gt(),o=s.getIfFresh(n,TD);if(o)return se(gr,"GraphQL search cache hit for query"),o;let i=`${t.q} sort:${t.sort}-${t.order}`,a=await wD(e,i,Math.min(t.per_page,100));return a?(Ck++,a.items.length>0?s.set(n,"",a):se(gr,"Skipping cache for empty GraphQL search result (possible transient artifact)"),a):(H(gr,"GraphQL broad search unavailable; falling back to REST search API"),Pk(e,t,r))}async function $D(e,t,r,n){let s=[];for(let o of t){if(s.length>=n*3)break;let[i,a]=o.split("/");if(!(!i||!a))try{let{data:c}=await e.repos.get({owner:i,repo:a});if(!c.pushed_at)continue;let u=new Date(c.pushed_at),d=new Date;if(d.setDate(d.getDate()-30),u<d||(c.stargazers_count??0)<r||c.archived)continue;let{data:p}=await e.issues.listForRepo({owner:i,repo:a,state:"open",sort:"created",direction:"desc",per_page:5}),m=p.filter(f=>!f.pull_request&&!f.assignee);for(let f of m)s.push({html_url:f.html_url,repository_url:`https://api.github.com/repos/${o}`,updated_at:f.updated_at??"",title:f.title,labels:f.labels});await mr(kD)}catch(c){if(Me(c)===401)throw c;if(mt(c)){H(gr,`Rate limit hit fetching issues from ${o}:`,Y(c));break}H(gr,`Error fetching issues from ${o}:`,Y(c))}}return s}async function Ak(e,t,r,n,s,o,i,a=5){let c=[],u=0,d=0;for(let f=0;f<r.length&&!(c.length>=s);f++){f>0&&await mr(kD);let g=r[f],[h,b]=g.split("/");try{let w=n.length>0?n:[void 0],y=new Set,S=[];for(let P of w){let C=await e.issues.listForRepo({owner:h,repo:b,state:"open",sort:"created",direction:"desc",per_page:a,...P!==void 0?{labels:P}:{}});for(let E of C.data)y.has(E.html_url)||(y.add(E.html_url),S.push(E))}let R=S.filter(P=>!("pull_request"in P)&&!P.assignee).map(P=>({html_url:P.html_url,repository_url:`https://api.github.com/repos/${g}`,updated_at:P.updated_at??"",title:P.title,labels:P.labels}));if(R.length>0){let P=i(R);if(P.length>0){let C=Math.min(X2,s-c.length),{candidates:E,rateLimitHit:T}=await t.vetIssuesParallel(P.slice(0,C*2).map(M=>M.html_url),C,o);c.push(...E.slice(0,C)),T&&d++}}}catch(w){if(Me(w)===401)throw w;u++,mt(w)&&d++,H(gr,`Error fetching issues from ${g}:`,Y(w))}}let p=u===r.length&&r.length>0,m=d>0;return p&&H(gr,`All ${r.length} repo(s) failed for ${o} phase. This may indicate a systemic issue (rate limit, auth, network).`),{candidates:c,allReposFailed:p,rateLimitHit:m}}async function r4(e,t,r,n,s,o=fr()){return(await Ek(e,{q:n(t4(t)),sort:"created",order:"desc",per_page:s},o)).items}function n4(e,t,r){return t||e.length===0?[""]:e.length===1?[`language:${e[0]}`]:r?e.map(n=>`language:${n}`):[e.map(n=>`language:${n}`).join(" ")]}async function Tk(e,t,r,n,s,o,i=fr(),a=0,c=0){let u=n4(t,r,n.length>0),d=u.length>0?a%u.length:0,p=[...u.slice(d),...u.slice(0,d)],m=new Set,f=[];for(let g=0;g<p.length;g++){g>0&&await mr(e4);let h=await r4(e,n,c,b=>`${s(p[g])} ${b}`.replace(/ +/g," ").trim(),o,i);for(let b of h)m.has(b.html_url)||(m.add(b.html_url),f.push(b))}return f}async function ml(e,t,r,n,s,o,i){let a=q0(t);if(a.size>0){let h=t.filter(b=>a.has(it(b.repository_url)??"")).length;se(gr,`[SPAM_FILTER] Filtered ${h} issues from ${a.size} label-farming repos: ${[...a].join(", ")}`)}let c=0,u=r(t).filter(h=>{let b=it(h.repository_url);return!b||a.has(b)?!1:typeof h.repositoryStars=="number"&&h.repositoryStars<o?(c++,!1):n.every(w=>!w.has(b))}).slice(0,s*2);if(c>0&&se(gr,`[STAR_FILTER] Dropped ${c} ${i} items below ${o} stars before vetting`),u.length===0)return se(gr,`[${i}] All ${t.length} items filtered before vetting`),{candidates:[],allVetFailed:!1,rateLimitHit:!1};let{candidates:d,allFailed:p,rateLimitHit:m}=await e.vetIssuesParallel(u.map(h=>h.html_url),s,"normal"),f=d.filter(h=>h.projectHealth.checkFailed?!0:(h.projectHealth.stargazersCount??0)>=o),g=d.length-f.length;return g>0&&se(gr,`[STAR_FILTER] Filtered ${g} ${i} candidates below ${o} stars`),{candidates:f,allVetFailed:p,rateLimitHit:m}}var gr,kD,X2,e4,Ck,TD,$k=A(()=>{sk();ft();pt();Dn();lk();It();Fa();vk();gr="search-phases",kD=2e3,X2=2,e4=500,Ck=0;TD=900*1e3});function ng(e){return e.personalization?.kind==="boosted"?e.personalization.score:0}function rg(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(Boolean))}function OD(e,t={}){let r=rg(t.preferLanguages),n=rg(t.preferRepos),s=rg(t.avoidRepos),o=rg(t.boostIssueTypes);return r.size===0&&n.size===0&&s.size===0&&o.size===0?e:e.map(i=>{let a=0,c=[],u=i.issue.repo.toLowerCase();n.size>0&&n.has(u)&&(a+=20,c.push(`repo affinity: ${i.issue.repo}`));let d=i.projectHealth.checkFailed?null:i.projectHealth.language;if(r.size>0&&d&&r.has(d.toLowerCase())&&(a+=10,c.push(`language match: ${d}`)),o.size>0){let p=i.issue.labels.find(m=>o.has(m.toLowerCase()));p&&(a+=10,c.push(`issue type: ${p}`))}return s.size>0&&s.has(u)&&(a-=15,c.push(`avoided repo: ${i.issue.repo}`)),c.length===0?i:{...i,personalization:{kind:"boosted",score:a,reasons:c}}})}function ID(e,t,r){if(t<=0)return[];let n=Math.max(0,Math.min(1,r));if(n===0)return e.slice(0,t);let s=Math.min(Math.floor(t*n),t);if(s===0)return e.slice(0,t);let o=t-s,i=[],a=new Set;for(let c of e){if(i.length>=o)break;i.push(c),a.add(c.issue.url)}for(let c of e){if(i.length>=t)break;a.has(c.issue.url)||ng(c)===0&&(i.push({...c,personalization:{kind:"diversity"}}),a.add(c.issue.url))}for(let c of e){if(i.length>=t)break;a.has(c.issue.url)||(i.push(c),a.add(c.issue.url))}return i}var xD=A(()=>{});function Ok(e,t,r){if(e.length<=t)return[...e];let n=r*t%e.length;return Array.from({length:t},(s,o)=>e[(n+o)%e.length])}function LD(e){return t=>t.filter(r=>{let n=it(r.repository_url);if(!n)return!1;let s=n.toLowerCase();if(e.excludedRepos.has(s))return!1;if(e.excludeOrgs.size>0){let a=s.split("/")[0];if(a&&e.excludeOrgs.has(a))return!1}if(e.aiBlocklisted.has(s)||e.lowScoringRepos.has(s)||e.skippedUrls.has(r.html_url))return!1;let o=new Date(r.updated_at);return!(Number.isNaN(o.getTime())||Ma(o,e.now)>e.maxAgeDays||!e.includeDocIssues&&W0(r)||V0(r))})}async function u4(e,t,r,n,s){ze(Ce,`Phase 0: Searching issues in ${r.length} merged-PR repos (no label filter, ${DD}/repo)...`);let{candidates:o,allReposFailed:i,rateLimitHit:a}=await Ak(e,t,r,[],n,"merged_pr",s,DD);return ze(Ce,`Found ${o.length} candidates from merged-PR repos`),{candidates:o,error:i?"All merged-PR repo fetches failed":null,rateLimitHit:a}}async function l4(e,t,r,n,s,o,i,a,c,u,d,p){ze(Ce,`Orgs phase: searching ${r.length} preferred org(s)...`);let m=r.slice(0,sg);r.length>sg&&H(Ce,`Orgs phase: capping query at ${sg} org(s); dropping ${r.slice(sg).join(", ")}`);let f=m.map(g=>`org:${g}`).join(" ");try{let g=await Tk(e,n,s,o,y=>`is:issue is:open ${y} no:assignee ${f}`.replace(/ +/g," ").trim(),i*3,p,0,m.length),{candidates:h,allVetFailed:b,rateLimitHit:w}=await ml(t,g,d,[c,u],i,a,"Orgs phase");return ze(Ce,`Found ${h.length} candidates from preferred orgs`),{candidates:h,error:b?"all vetting failed":null,rateLimitHit:w}}catch(g){if(Me(g)===401)throw g;let h=Y(g);return H(Ce,`Error in preferred-orgs search: ${h}`),{candidates:[],error:h,rateLimitHit:mt(g)}}}async function d4(e,t,r,n,s,o){ze(Ce,`Phase 1: Searching issues in ${r.length} starred repos...`);let i=n.slice(0,3),a=r.slice(0,MD),{candidates:c,allReposFailed:u,rateLimitHit:d}=await Ak(e,t,a,i,s,"starred",o);return ze(Ce,`Found ${c.length} candidates from starred repos`),{candidates:c,error:u?"All starred repo fetches failed":null,rateLimitHit:d}}async function p4(e,t,r,n,s,o,i,a,c,u,d,p,m,f,g=0){ze(Ce,"Phase 2: General issue search...");let h=new Set(p.map(P=>P.issue.repo)),b=[];if(r&&r.length>1){for(let E of r){let T=cl[E]??[];if(T.length===0){H(Ce,`Scope "${E}" has no labels, skipping tier`);continue}b.push({tier:E,tierLabels:T})}let P=new Set(r.flatMap(E=>cl[E]??[])),C=s.filter(E=>!P.has(E));C.length>0&&b.push({tier:"custom",tierLabels:C})}else b.push({tier:"general",tierLabels:n});let w=Math.ceil(a/b.length),y=[],S=null,k=!1;for(let{tier:P,tierLabels:C}of b)try{let E=await Tk(e,o,i,C,X=>`is:issue is:open ${X} no:assignee`.replace(/ +/g," ").trim(),w*3,f,g);ze(Ce,`Phase 2 [${P}]: processing ${E.length} items...`);let{candidates:T,allVetFailed:M,rateLimitHit:G}=await ml(t,E,m,[u,d,h],w,c,`Phase 2 [${P}]`);y.push(T);for(let X of T)h.add(X.issue.repo);M&&(S=(S?S+"; ":"")+`${P}: all vetting failed`),G&&(k=!0),ze(Ce,`Found ${T.length} candidates from ${P} tier`)}catch(E){if(Me(E)===401)throw E;let T=Y(E);S=(S?S+"; ":"")+`${P}: ${T}`,mt(E)&&(k=!0),H(Ce,`Error in ${P} tier search: ${T}`),y.push([])}let R=AD(y);return R.length===0&&S&&H(Ce,`All ${b.length} scope tiers failed in Phase 2: ${S}`),{candidates:R.slice(0,a),error:S,rateLimitHit:k}}async function m4(e,t,r,n,s,o,i,a,c,u,d,p,m=0){ze(Ce,"Phase 3: Searching actively maintained repos...");let f=new Set(u.map(k=>k.issue.repo)),g=Ok(c,c4,m).filter(k=>!i.has(k)&&!f.has(k));if(g.length>0){ze(Ce,`Phase 3: Checking ${g.length} starred repos via REST API...`);let k=await $D(e,g,n,o);if(k.length>0)try{let{candidates:R,allVetFailed:P,rateLimitHit:C}=await ml(t,k,d,[i,f],o,n,"Phase 3 (REST)");if(R.length>0)return ze(Ce,`Found ${R.length} candidates from maintained-repo REST search`),{candidates:R,error:P?"all vetting failed":null,rateLimitHit:C}}catch(R){if(Me(R)===401)throw R;H(Ce,"Phase 3 REST vetting failed, falling back to Search API:",Y(R))}}ze(Ce,"Phase 3: Falling back to Search API...");let h=new Date;h.setDate(h.getDate()-30);let b=h.toISOString().split("T")[0],w=X0(s),y=w.length>0?`topic:${w[0]}`:"",S=`is:issue is:open no:assignee ${r} ${y} pushed:>=${b} archived:false`.replace(/ +/g," ").trim();try{let k=await Ek(e,{q:S,sort:"updated",order:"desc",per_page:o*3},p);ze(Ce,`Found ${k.total_count} issues in maintained-repo search, processing top ${k.items.length}...`);let{candidates:R,allVetFailed:P,rateLimitHit:C}=await ml(t,k.items,d,[i,a,f],o,n,"Phase 3");return ze(Ce,`Found ${R.length} candidates from maintained-repo search`),{candidates:R,error:P?"all vetting failed":null,rateLimitHit:C}}catch(k){if(Me(k)===401)throw k;let R=Y(k);return H(Ce,`Error in maintained-repo search: ${R}`),{candidates:[],error:R,rateLimitHit:mt(k)}}}var Ce,s4,za,DD,o4,i4,a4,MD,c4,sg,xo,Ik=A(()=>{Zf();Fa();It();sk();Io();ft();pt();lk();tg();dk();$k();xD();Ce="issue-discovery",s4=20,za=10,DD=30,o4=365,i4=.5,a4=10,MD=10,c4=15;sg=8;xo=class{preferences;stateReader;octokit;githubToken;vetter;budgetTracker;rateLimitWarning=null;constructor(t,r,n,s=fr()){this.preferences=r,this.stateReader=n,this.githubToken=t,this.octokit=In(t),this.budgetTracker=s,this.vetter=new Ss(this.octokit,this.stateReader,this.budgetTracker)}getStarredRepos(){return this.stateReader.getStarredRepos()}async searchIssues(t={}){let r=this.preferences,n=t.languages||r.languages,s=r.scope,o=t.labels||(s?ED(s,r.labels):r.labels),i=t.maxResults||10,a=r.minStars??50,c=t.interPhaseDelayMs??r.interPhaseDelayMs??0,u=Oo,p=((...K)=>K.find(He=>He&&He.length>0)??["all"])(t.strategies,r.defaultStrategy),m=new Set(p.includes("all")?u:p),f=[],g=[],h={},b=!1,w=async()=>{c>0&&(ze(Ce,`Waiting ${(c/1e3).toFixed(0)}s between phases for rate limit management...`),await mr(c))},y=(K,He)=>{g.push(...He.candidates),h[K]=He.error,He.rateLimitHit&&(b=!0)},S=()=>g.filter(K=>K.recommendation!=="skip").length;this.rateLimitWarning=null,PD();let k=this.budgetTracker,R=za-1,P=!1;try{let K=await qf(this.githubToken);if(R=K.remaining,k.init(K.remaining,K.resetAt),K.remaining<5){let He=new Date(K.resetAt).toLocaleTimeString("en-US",{hour12:!1});this.rateLimitWarning=`GitHub search API quota low (${K.remaining}/${K.limit} remaining, resets at ${He}). Search may be slow.`,H(Ce,this.rateLimitWarning)}R<za?ze(Ce,`Search budget critical (${R} remaining) \u2014 skipping the starred phase; broad/maintained still run on GraphQL (points bucket)`):R<s4&&ze(Ce,`Search budget low (${R} remaining) \u2014 broad/maintained run on GraphQL (points bucket), unaffected by REST search quota`)}catch(K){if(Me(K)===401)throw K;P=!0,k.init(za,new Date(Date.now()+6e4).toISOString()),H(Ce,"Could not check rate limit \u2014 using conservative budget, skipping the starred phase:",Y(K))}R<=0&&(this.rateLimitWarning="GitHub search API quota exhausted \u2014 skipping the starred phase; other phases don't use it.",H(Ce,this.rateLimitWarning));let C=this.stateReader.getReposWithMergedPRs(),E=this.stateReader.getReposWithOpenPRs(),T=this.getStarredRepos(),M=new Set(T),G=new Set(this.deriveLowScoringRepos(r.minRepoScoreThreshold).map(K=>K.toLowerCase())),X=n.some(K=>K.toLowerCase()==="any"),ve=X?"":n.map(K=>`language:${K}`).join(" "),he=new Set(r.aiPolicyBlocklist.map(K=>K.toLowerCase()));he.size>0&&se(Ce,`[AI_POLICY_FILTER] Filtering issues from ${he.size} blocklisted repo(s): ${[...he].join(", ")}`);let oe={excludedRepos:new Set(r.excludeRepos.map(K=>K.toLowerCase())),excludeOrgs:new Set((r.excludeOrgs??[]).map(K=>K.toLowerCase())),aiBlocklisted:he,lowScoringRepos:G,skippedUrls:t.skippedUrls??new Set,now:new Date,includeDocIssues:r.includeDocIssues??!0},Z=LD({...oe,maxAgeDays:r.maxIssueAgeDays||90}),$e=LD({...oe,maxAgeDays:o4}),Re=t.repoRotationOffsets??{},Xe=Ok([...new Set([...C,...E])],a4,Re.merged??0),Ke=new Set(Xe),tt=r.preferredOrgs??[],ct=Ok(T,MD,Re.starred??0).filter(K=>!Ke.has(K)),sr={all:!1,merged:Xe.length>0,orgs:tt.length>0,starred:ct.length>0&&R>=za,broad:!0,maintained:!0},et=t.broadPhaseDelayMs??r.broadPhaseDelayMs??0,Je={merged:async K=>{y("0",await u4(this.octokit,this.vetter,Xe,K,$e)),f.push("merged")},orgs:async K=>{y("orgs",await l4(this.octokit,this.vetter,tt,n,X,o,K,a,Ke,M,Z,k)),f.push("orgs")},starred:async K=>{y("1",await d4(this.octokit,this.vetter,ct,o,K,Z)),f.push("starred")},broad:async K=>{y("2",await p4(this.octokit,this.vetter,s,o,r.labels,n,X,K,a,Ke,M,g,Z,k,t.languageRotationOffset??0)),f.push("broad")},maintained:async K=>{y("3",await m4(this.octokit,this.vetter,ve,a,r.projectCategories??[],K,Ke,M,T,g,Z,k,Re.maintained??0)),f.push("maintained")}},Fr=R<za;if(t.strategyRotationOffset!==void 0){let K=t.strategyRotationOffset,He=Oo.length,Wt=Oo.map((qe,xt)=>Oo[(K+xt)%He]).filter(qe=>m.has(qe));Fr=!1;for(let qe of Wt){if(!sr[qe]){qe==="starred"&&ct.length>0&&(Fr=!0);continue}if(f.length>0&&await w(),ze(Ce,`Round-robin: running the ${qe} strategy`),await Je[qe](i-S()),S()>0)break}}else{let K=sr.orgs&&m.has("orgs"),He=K||T.length>0&&m.has("starred")||m.has("broad")||m.has("maintained");if(sr.merged&&m.has("merged")){let Et=He?Math.max(1,Math.ceil(i*i4)):i;await Je.merged(Math.min(i-g.length,Et))}g.length<i&&K&&(await w(),await Je.orgs(i-g.length)),g.length<i&&T.length>0&&R>=za&&m.has("starred")&&(await w(),ct.length>0&&await Je.starred(i-g.length));let Wt=r.skipBroadWhenSufficientResults??8,qe=Wt>0?Math.min(Wt,i-1):0,xt=S();if(xt>=i&&m.has("broad"))ze(Ce,`Skipping broad search: ${xt} viable candidate(s) already meet maxResults (${i})`);else if(m.has("broad")){let Et=new Set(tt.map(un=>un.toLowerCase())),Xa=g.filter(un=>un.recommendation!=="skip"&&!Ke.has(un.issue.repo)&&!M.has(un.issue.repo)&&!Et.has(un.issue.repo.split("/")[0]?.toLowerCase()??"")).length;qe>0&&Xa>=qe?ze(Ce,`Skipping broad search: already found ${Xa} viable candidate(s) from new repos (threshold: ${qe})`):(await w(),g.length>0&&et>0?(ze(Ce,`Waiting ${(et/1e3).toFixed(0)}s for rate limit cooldown before broad search...`),await mr(et)):g.length===0&&ze(Ce,"Skipping broad phase delay: no results from previous phases, proceeding immediately"),await Je.broad(i-xt))}let yr=S();yr>=i&&m.has("maintained")?ze(Ce,`Skipping maintained search: ${yr} viable candidate(s) already meet maxResults (${i})`):m.has("maintained")&&(await w(),await Je.maintained(i-yr))}let Ps=Fr,Es=Ps?P?" The starred-repo phase was skipped as a precaution because the rate-limit check failed (quota unknown); the other strategies don't use that quota.":` The starred-repo phase was skipped due to critically low API quota (${R} remaining); the other strategies don't use that quota.`:"";if(g.length===0){let K=[h[0]?`Phase 0 (merged-PR repos): ${h[0]}`:null,h.orgs?`Orgs phase (preferred orgs): ${h.orgs}`:null,h[1]?`Phase 1 (starred repos): ${h[1]}`:null,h[2]?`Phase 2 (general): ${h[2]}`:null,h[3]?`Phase 3 (maintained repos): ${h[3]}`:null].filter(Boolean),He=K.length>0?` ${K.join(". ")}.`:"";if(b||Ps)return this.rateLimitWarning=`Search returned no results due to GitHub API rate limits.${He}${Es} Try again after the rate limit resets.`,{candidates:[],strategiesUsed:f};throw new ot(`No issue candidates found across all search phases.${He} Try adjusting your search criteria (languages, labels) or check your network connection.`,f)}(b||Ps)&&(this.rateLimitWarning=`Search results may be incomplete: GitHub API rate limits were hit during search.${Es} Found ${g.length} candidate${g.length===1?"":"s"} but some search phases were limited. Try again after the rate limit resets for complete results.`);let Fn=OD(g,{preferLanguages:t.preferLanguages,preferRepos:t.preferRepos,avoidRepos:t.avoidRepos,boostIssueTypes:t.boostIssueTypes});Fn.sort((K,He)=>{let Wt={merged_pr:0,starred:1,normal:2},qe=Wt[K.searchPriority]-Wt[He.searchPriority];if(qe!==0)return qe;let xt={approve:0,needs_review:1,skip:2},yr=xt[K.recommendation]-xt[He.recommendation];if(yr!==0)return yr;let Et=ng(He)-ng(K);return Et!==0?Et:He.viabilityScore-K.viabilityScore});let Wo=[...Fn.filter(K=>K.recommendation!=="skip"),...Fn.filter(K=>K.recommendation==="skip")],Vo=Z0(Wo,2),qo=ID(Vo,i,t.diversityRatio??0);return ze(Ce,`Search complete: ${k.getTotalCalls()} REST Search API call(s) + ${CD()} GraphQL broad-search query/queries used, ${qo.length} candidates returned`),{candidates:qo,strategiesUsed:f}}async vetIssue(t){return this.vetter.vetIssue(t)}deriveLowScoringRepos(t){let r=[],n=new Set([...this.stateReader.getReposWithMergedPRs(),...this.stateReader.getStarredRepos()]);for(let s of n){let o=this.stateReader.getRepoScore(s);o!==null&&o<=t&&r.push(s)}return r}}});function FD(){let e=Date.now()-ND;for(let[t,r]of fl.entries())r.fetchedAt<e&&fl.delete(t)}function Dk(e,t,r){let n=new Set,s=`${t}/${r}`.toLowerCase(),o=d=>d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${o(t)}/${o(r)}#(\\d+)\\b`,"gi");for(let d of e.matchAll(i)){let p=Number.parseInt(d[1],10);p>0&&n.add(p)}let a=/\b[\w.-]+\/[\w.-]+#\d+\b/gi,c=!1;for(let d of e.split(`
305
- `)){if(/^\s*(```|~~~)/.test(d)){c=!c;continue}if(c||/^\s*#+\s/.test(d))continue;let p=d.replace(a,"").replace(/`[^`]*`/g,"");for(let m of p.matchAll(/(?:^|[^&\w])#(\d+)\b/g)){let f=Number.parseInt(m[1],10);f>0&&n.add(f)}}let u=/https?:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/issues\/(\d+)/gi;for(let d of e.matchAll(u))if(d[1].toLowerCase()===s){let p=Number.parseInt(d[2],10);p>0&&n.add(p)}return n}async function og(e,t,r){let n=`${t}/${r}`.toLowerCase(),s=fl.get(n);if(s&&Date.now()-s.fetchedAt<ND)return s.refs;let o=xk.get(n);if(o)return o;let i=g4(e,t,r,n);xk.set(n,i);try{return await i}finally{xk.delete(n)}}async function g4(e,t,r,n){for(let o of f4){let{text:i}=await Ga(e,t,r,o);if(!i)continue;let a=Dk(i,t,r);return fl.set(n,{refs:a,fetchedAt:Date.now()}),FD(),a}let s=new Set;return fl.set(n,{refs:s,fetchedAt:Date.now()}),FD(),s}var ND,f4,fl,xk,Lk=A(()=>{Xf();ND=3600*1e3,f4=["ROADMAP.md","docs/ROADMAP.md",".github/ROADMAP.md","Roadmap.md","roadmap.md"],fl=new Map;xk=new Map});function Nk(e,t=Fk){return Object.values(e).filter(r=>r.mergedPRCount>=t).sort((r,n)=>n.mergedPRCount-r.mergedPRCount).map(r=>r.repo)}function Gk(e){if(e.hasMilestone||e.isOnRoadmap)return"bigger-bet";for(let t of e.labels)if(b4.has(t.toLowerCase()))return"bigger-bet";return"quick-win"}function ig(e,t,r=y4){let n=e.filter(g=>g.horizon==="quick-win").sort((g,h)=>h.viabilityScore-g.viabilityScore),s=e.filter(g=>g.horizon==="bigger-bet").sort((g,h)=>h.viabilityScore-g.viabilityScore),o=Math.max(0,Math.min(1,r)),i=Math.round(t*o),a=t-i,c=Math.min(n.length,i),u=Math.min(s.length,a),d=c,p=u,m=i-c,f=a-u;return m>0&&(p=Math.min(s.length,p+m)),f>0&&(d=Math.min(n.length,d+f)),{quickWins:n.slice(0,d),biggerBets:s.slice(0,p)}}function S4(e){if(!e.labels.some(o=>w4.has(o.toLowerCase())))return!1;let r=new Date(e.createdAt);return Number.isNaN(r.getTime())?!1:((e.now??new Date).getTime()-r.getTime())/(1e3*60*60*24)>=(e.minAgeDays??R4)}function BD(e){let t=new Set([...e.excludeRepos??[],...e.aiPolicyBlocklist??[]].map(n=>n.toLowerCase())),r=new Set((e.excludeOrgs??[]).map(n=>n.toLowerCase()));return n=>{let s=n.toLowerCase();if(t.has(s))return!1;let o=s.split("/")[0];return!(o&&r.has(o))}}function HD(e){return Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t?.name).filter(t=>typeof t=="string"):[]}function WD(e){let t=HD(e).map(r=>r.toLowerCase());return t.length===0||t.some(r=>zD.has(r))?!1:t.some(r=>ag.includes(r))}async function VD(e,t,r){let n=HD(e),s=!!e.milestone,o=e.reactions?.total_count??0,i=e.comments??0,a=e.created_at?S4({labels:n,createdAt:e.created_at}):!1,c=r!==void 0,u=c&&typeof e.number=="number"&&r.has(e.number),d;try{d=await t.vetIssue(e.html_url,{featureSignals:{reactions:o,comments:i,hasMilestone:s,wontfixNoContributor:a,...c?{onRoadmap:u}:{}}})}catch(m){return Be(m),H(Mk,`vet failed for ${e.html_url}: ${Y(m)}`),null}let p=Gk({hasMilestone:s,labels:n,...c?{isOnRoadmap:u}:{}});return{...d,horizon:p}}async function cg(e){let t=BD(e),r=Nk(e.repoScores,e.anchorThreshold).filter(t);if(r.length===0)return{quickWins:[],biggerBets:[],anchorRepos:[],message:Uk};let n=[];for(let a=0;a<r.length;a++){a>0&&await mr(h4);let[c,u]=r[a].split("/"),d,p;try{let[f,g]=await Promise.all([e.octokit.issues.listForRepo({owner:c,repo:u,state:"open",sort:"updated",direction:"desc",per_page:20}),og(e.octokit,c,u)]);d=f,p=g}catch(f){Be(f),H(Mk,`failed to list issues for ${r[a]}: ${Y(f)}`);continue}let m=d.data.filter(f=>!f.pull_request&&!f.assignee&&WD(f));for(let f of m){let g=await VD(f,e.vetter,p);g&&n.push(g)}}let s=n.filter(a=>a.viabilityScore>=jD),o=ig(s,e.count,e.splitRatio),i=o.quickWins.length+o.biggerBets.length;return{...o,anchorRepos:r,message:i===0?jk:null}}function UD(e){let t=["is:issue","is:open","no:assignee"],r=`label:${ag.map(n=>JSON.stringify(n)).join(",")}`;t.push(r);for(let n of zD)t.push(`-label:"${n}"`);e.language&&t.push(`language:${e.language}`);for(let n of e.excludeRepos??[])t.push(`-repo:${n}`);for(let n of e.excludeOrgs??[])t.push(`-user:${n}`);return t.join(" ")}function v4(e){let t={excludeRepos:e.excludeRepos,excludeOrgs:e.excludeOrgs},r=(e.languages??[]).filter(n=>n&&n.toLowerCase()!=="any");return r.length===0?[UD(t)]:r.map(n=>UD({...t,language:n}))}async function qD(e){let t=v4({languages:e.languages,excludeRepos:e.excludeRepos,excludeOrgs:e.excludeOrgs}),r=e.maxToVet??_4,n;try{let c=[],u=new Set;for(let p of t){let m=await Pk(e.octokit,{q:p,sort:"interactions",order:"desc",per_page:r});for(let f of m.items)u.has(f.html_url)||(u.add(f.html_url),c.push(f))}let d=BD(e);n=c.filter(p=>!p.pull_request&&!p.assignee&&WD(p)).filter(p=>{let m=it(p.html_url);return m===null||d(m)}).slice(0,r)}catch(c){return Be(c),H(Mk,`broad feature search failed: ${Y(c)}`),{quickWins:[],biggerBets:[],anchorRepos:[],message:GD}}let s=[];for(let c of n){let u=await VD(c,e.vetter);u&&s.push(u)}let o=s.filter(c=>c.viabilityScore>=jD),i=ig(o,e.count,e.splitRatio),a=i.quickWins.length+i.biggerBets.length;return{...i,anchorRepos:[],message:a===0?GD:null}}var Mk,h4,jD,Fk,y4,b4,ag,zD,w4,R4,Uk,jk,GD,_4,zk=A(()=>{ft();pt();It();Lk();$k();Mk="feature-discovery",h4=2e3,jD=40,Fk=3,y4=.6;b4=new Set(["roadmap","accepted-rfc","proposal"]);ag=["enhancement","feature","feature-request","proposal","roadmap","accepted-rfc"],zD=new Set(["good first issue","bug","documentation"]),w4=new Set(["help wanted","contributions welcome","up-for-grabs","bounty","pinned","unmaintained"]),R4=60;Uk="No anchor repos yet (need 3+ merged PRs in a repo). Try `scout search` to build relationships first.",jk="No open feature opportunities in your anchor repos right now. Check back next week, or try `scout search` for fix-mode work.";GD="No open feature opportunities matched your filters. Try widening your language preferences in `scout config`.",_4=30});function P4(e){if(mt(e))return"rate_limit";let t=Me(e);if(t!==void 0&&t>=500&&t<600)return"server";if(e&&typeof e=="object"&&"code"in e){let r=e.code;if(r==="ECONNREFUSED"||r==="ENOTFOUND"||r==="ETIMEDOUT"||r==="ECONNRESET"||r==="EAI_AGAIN")return"network"}return e instanceof Error&&e.message.toLowerCase().includes("fetch failed")?"network":"unknown"}function JD(){return Wk.join(Rs(),k4)}function YD(){return Wk.join(Rs(),C4)}function A4(e,t){let r=Date.now()-E4,n=new Map;for(let s of[...e,...t]){let o=n.get(s.url);(!o||s.removedAt>o.removedAt)&&n.set(s.url,s)}return[...n.values()].filter(s=>{let o=new Date(s.removedAt).getTime();return Number.isFinite(o)&&o>=r})}function QD(e,t,r,n){if(t.length===0)return e;let s=new Map(t.map(o=>[o.url,o.removedAt]));return e.filter(o=>{let i=s.get(r(o));return i===void 0?!0:n(o)>i})}function gl(e,t){let r=A4(e.tombstones??[],t.tombstones??[]),n=QD(I4(e.savedResults??[],t.savedResults??[]),r,b=>b.issueUrl,b=>b.lastSeenAt),s=QD(x4(e.skippedIssues??[],t.skippedIssues??[]),r,b=>b.url,b=>b.skippedAt),o=new Set(s.map(b=>b.url)),i=n.filter(b=>!o.has(b.issueUrl)),a=e.preferencesUpdatedAt,c=t.preferencesUpdatedAt,d=a!==void 0&&(c===void 0||a>c)?e.preferences:t.preferences,p=ug(a,c),m=Hk(e.mergedPRs,t.mergedPRs),f=Hk(e.closedPRs,t.closedPRs),g=new Set([...m.map(b=>b.url),...f.map(b=>b.url)]),h=Hk(e.openPRs??[],t.openPRs??[]).filter(b=>!g.has(b.url));return{...e,...t,version:1,stateRevision:Math.max(e.stateRevision,t.stateRevision),preferences:d,preferencesUpdatedAt:p,tombstones:r,repoScores:$4(e.repoScores,t.repoScores),starredRepos:O4(e,t),starredReposLastFetched:ug(e.starredReposLastFetched,t.starredReposLastFetched),mergedPRs:m,closedPRs:f,openPRs:h,savedResults:i,skippedIssues:s,lastSearchAt:ug(e.lastSearchAt,t.lastSearchAt),lastRunAt:ug(e.lastRunAt,t.lastRunAt)??new Date().toISOString(),gistId:t.gistId??e.gistId,searchRotation:T4(e.searchRotation,t.searchRotation)}}function T4(e,t){let r=e??{languageOffset:0},n=t??{languageOffset:0},s=r.lastRotatedAt,o=n.lastRotatedAt;return s&&o?s>=o?r:n:s?r:o||n.languageOffset>=r.languageOffset?n:r}function $4(e,t){let r=Object.assign(Object.create(null),e);for(let[n,s]of Object.entries(t)){let o=r[n];if(!o)r[n]=s;else{let i=o.mergedPRCount+o.closedWithoutMergeCount,a=s.mergedPRCount+s.closedWithoutMergeCount;r[n]=a>=i?s:o}}return r}function O4(e,t){let r=e.starredReposLastFetched,n=t.starredReposLastFetched;return!r&&!n?t.starredRepos.length>=e.starredRepos.length?t.starredRepos:e.starredRepos:r?n&&n>=r?t.starredRepos:e.starredRepos:t.starredRepos}function Hk(e,t){let r=new Map;for(let n of e)r.set(n.url,n);for(let n of t)r.set(n.url,n);return[...r.values()]}function I4(e,t){let r=new Map;for(let n of e)r.set(n.issueUrl,n);for(let n of t){let s=r.get(n.issueUrl);(!s||n.lastSeenAt>s.lastSeenAt)&&r.set(n.issueUrl,n)}return[...r.values()]}function x4(e,t){let r=new Map;for(let n of e)r.set(n.url,n);for(let n of t){let s=r.get(n.url);(!s||n.skippedAt>s.skippedAt)&&r.set(n.url,n)}return[...r.values()]}function ug(e,t){return e?t?e>=t?e:t:e:t}var Ba,Wk,at,ZD,Bk,k4,C4,KD,lg,E4,XD=A(()=>{Ba=B(require("fs"),1),Wk=B(require("path"),1);Io();It();pt();ft();at="gist-state",ZD="oss-scout-state",Bk="state.json",k4="gist-id",C4="state-cache.json",KD=10;lg=class{octokit;gistId=null;constructor(t){this.octokit=t}async bootstrap(){try{return await this.bootstrapFromApi()}catch(t){if(Me(t)===401)throw t;return H(at,`API bootstrap failed: ${Y(t)}`),this.bootstrapFromCache(P4(t))}}async push(t){if(!this.gistId)return H(at,"No gist ID \u2014 cannot push"),this.writeCache(t),!1;let r=t;try{let s=await this.fetchGistState(this.gistId);if(s.kind==="ok")r=gl(t,s.state);else if(s.kind==="invalid")return this.writeCache(t),H(at,"Remote gist content failed validation \u2014 not overwriting it. Changes saved locally; gist sync skipped."),!1}catch(s){Be(s),H(at,`Could not fetch gist before push, writing local snapshot: ${Y(s)}`)}this.writeCache(r);let n=JSON.stringify(r,null,2);if(n.length>9e5)return H(at,`State too large for gist (${Math.round(n.length/1024)}KB). Consider clearing old results with 'oss-scout results clear'.`),!1;try{return await this.octokit.gists.update({gist_id:this.gistId,files:{[Bk]:{content:n}}}),se(at,"State pushed to gist"),!0}catch(s){return Be(s),H(at,`Failed to push: ${Y(s)}`),!1}}getGistId(){return this.gistId}async bootstrapFromApi(){let t=this.readCachedGistId();if(t){se(at,`Trying cached gist ID: ${t}`);try{let o=await this.fetchGistState(t);if(o.kind==="ok"){this.gistId=t;let i=this.mergeCacheInto(o.state);return this.writeCache(i),{gistId:t,state:i,created:!1}}}catch(o){if(Me(o)!==404)throw o;se(at,`Cached gist gone (404): ${Y(o)}`)}se(at,"Cached gist ID invalid, searching...")}let r=await this.searchForGist();if(r.id){se(at,`Found gist via search: ${r.id}`),this.saveGistId(r.id),this.gistId=r.id;let o=await this.fetchGistState(r.id);if(o.kind==="ok"){let i=this.mergeCacheInto(o.state);return this.writeCache(i),{gistId:r.id,state:i,created:!1}}return H(at,`Found existing gist ${r.id} but content failed validation. Using local cache to avoid data loss.`),this.bootstrapFromCache("unknown")}r.exhaustive||H(at,`Scanned the first ${KD*100} gists without finding an oss-scout state gist, but the account has more. Creating a new state gist; if one already exists, copy its id into the gist-id file in the oss-scout data directory to avoid a duplicate.`),se(at,"No existing gist found, creating new one");let n=xn.parse({version:1}),s=await this.createGist(n);return this.saveGistId(s),this.gistId=s,this.writeCache(n),{gistId:s,state:n,created:!0}}bootstrapFromCache(t){let r=this.readCache();if(r){se(at,"Bootstrapped from local cache (degraded mode)");let s=this.readCachedGistId();return s&&(this.gistId=s),{gistId:s??"",state:r,created:!1,degraded:!0,degradedReason:t}}return se(at,"No cache available, using fresh state (degraded mode)"),{gistId:"",state:xn.parse({version:1}),created:!1,degraded:!0,degradedReason:t}}async fetchGistState(t){let{data:r}=await this.octokit.gists.get({gist_id:t}),n=r.files?.[Bk];if(!n?.content)return{kind:"missing"};try{let s=JSON.parse(n.content);return{kind:"ok",state:dl(s)}}catch(s){return H(at,`Gist content failed validation: ${Y(s)}`),{kind:"invalid"}}}async searchForGist(){for(let t=1;t<=KD;t++){let{data:r}=await this.octokit.gists.list({per_page:100,page:t});if(r.length===0)return{id:null,exhaustive:!0};let n=r.find(s=>s.description===ZD);if(n)return{id:n.id,exhaustive:!0};if(r.length<100)return{id:null,exhaustive:!0}}return{id:null,exhaustive:!1}}async createGist(t){let{data:r}=await this.octokit.gists.create({description:ZD,public:!1,files:{[Bk]:{content:JSON.stringify(t,null,2)}}});return r.id}readCachedGistId(){try{return Ba.readFileSync(JD(),"utf-8").trim()||null}catch(t){return t?.code!=="ENOENT"&&H(at,`Failed to read cached gist ID: ${Y(t)}`),null}}saveGistId(t){Ba.writeFileSync(JD(),t+`
303
+ }`,o;try{o=await e.graphql(s,{q:t,first:n})}catch(c){Be(c);let u=c.data;if(u)o=u;else return H(Ua,`GraphQL broad search failed, falling back to REST: ${Y(c)}`),null}let i=o?.search;if(!i)return null;let a=[];for(let c of i.nodes??[]){if(!c?.url)continue;let u=c.repository?.nameWithOwner;u&&a.push({html_url:c.url,repository_url:`https://api.github.com/repos/${u}`,updated_at:c.updatedAt??"",title:c.title,labels:c.labels?.nodes??[],repositoryStars:c.repository?.stargazerCount})}return{total_count:i.issueCount??0,items:a}}var Ua,Sk,hD,vk=A(()=>{ft();pt();Dn();hk();Ua="issue-graphql";Sk=/^[A-Za-z0-9_.-]+$/,hD=15});function Z2(e){let{issue:t,linkedPRExists:r}=e,n=(t.body??"").slice(0,V2);return["You triage open-source issues for an autonomous contribution agent.","Classify the issue into exactly one bucket:","- pursue: small, concrete bug or feature with clear acceptance; safe for an autonomous agent to attempt without further design input","- investigate: tractable but needs human reading first (ambiguous scope, design questions, recently-touched files)","- skip: not actionable autonomously (epic, creative, blocked, requires upstream change, requires infra)","","Return JSON only matching the provided schema. Reasons must be short phrases, not sentences. 1-3 reasons total.","","Issue:",`Title: ${t.title}`,`Body: ${n}`,`Labels: ${t.labels.join(", ")}`,`Linked PR exists: ${r}`].join(`
304
+ `)}function RD(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="http:"&&t.protocol!=="https:")return!1;let r=t.hostname.replace(/^\[|\]$/g,"").toLowerCase();if(r==="localhost"||r==="::1")return!0;let n=r.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(n){let s=Number(n[1]),o=Number(n[2]);return s===127||s===10||s===192&&o===168||s===172&&o>=16&&o<=31}return r.includes(":")?r.startsWith("fc")||r.startsWith("fd")||r.startsWith("fe80"):!r.includes(".")||r.endsWith(".local")}function SD(e){if(!(e===""||RD(e)))throw new ot(`slmTriageHost must be an http(s) URL pointing at localhost or a private/LAN address (got "${e}"). Example: http://192.168.1.20:11434`)}async function _D(e,t){if(!t.model)return null;let r=t.host??H2;if(!RD(r))return H(B2,`slmTriageHost "${r}" is not a local/private address; skipping SLM triage`),null;let n=t.timeoutMs??W2,s=t.fetchImpl??fetch,o;try{o=await s(`${r}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t.model,messages:[{role:"user",content:Z2(e)}],stream:!1,format:q2,options:{temperature:.1}}),signal:AbortSignal.timeout(n),redirect:"error"})}catch{return null}if(!o.ok)return null;let i;try{i=await o.json()}catch{return null}let a=i?.message?.content;if(typeof a!="string")return null;let c;try{c=JSON.parse(a)}catch{return null}return K2(c)?{decision:c.decision,confidence:c.confidence,reasons:c.reasons,modelVersion:t.model}:null}function vD(e){return{issue:{title:e.issue.title,labels:e.issue.labels,body:e.issue.body},linkedPRExists:!!e.linkedPR}}function K2(e){if(typeof e!="object"||e===null)return!1;let t=e;return!(t.decision!=="pursue"&&t.decision!=="investigate"&&t.decision!=="skip"||t.confidence!=="high"&&t.confidence!=="medium"&&t.confidence!=="low"||!Array.isArray(t.reasons)||t.reasons.length===0||t.reasons.length>3||!t.reasons.every(r=>typeof r=="string"))}var B2,H2,W2,V2,q2,kk=A(()=>{ft();pt();B2="slm-triage",H2="http://127.0.0.1:11434",W2=15e3,V2=2e3,q2={type:"object",properties:{decision:{type:"string",enum:["pursue","investigate","skip"]},confidence:{type:"string",enum:["high","medium","low"]},reasons:{type:"array",items:{type:"string"},minItems:1,maxItems:3}},required:["decision","confidence","reasons"]}});function Q2(e){return e.checkFailed||e.recentMergedPRCount==null?null:e.recentMergedPRCount>0?!0:e.recentMergeRate==null?null:!1}function X2(e){let t=[],r=[],n=[];e.noExistingPR||t.push(e.ownPR?"Your PR is already in flight for this issue":e.linkedPRMerged?"A PR for this issue was already merged":e.linkedPRClosed?"A PR for this issue was closed without merging":"Existing PR found for this issue"),e.notClaimed||t.push("Issue appears to be claimed by someone"),e.existingPRInconclusive&&t.push(`Could not verify absence of existing PRs: ${e.existingPRReason||"API error"}`),e.claimInconclusive&&t.push(`Could not verify claim status: ${e.claimReason||"API error"}`),e.projectCheckFailed?t.push(`Could not verify project activity: ${e.projectFailureReason||"API error"}`):e.projectIsActive||t.push("Project may be inactive"),e.clearRequirements||t.push("Issue requirements are unclear"),e.contributionGuidelinesFound||t.push("No CONTRIBUTING.md found"),e.repoAcceptsContributions===!1?t.push("Repo has merged no PRs in the last 90 days"):e.repoAcceptsContributions===null&&t.push("Could not verify whether the repo merges PRs"),e.noExistingPR||(e.ownPR?n.push("You already have a PR in flight"):e.linkedPRMerged?n.push("Linked PR already merged"):e.linkedPRClosed?n.push("Linked PR closed without merge"):n.push("Has existing PR")),e.notClaimed||n.push("Already claimed"),!e.projectIsActive&&!e.projectCheckFailed&&n.push("Inactive project"),e.clearRequirements||n.push("Unclear requirements"),e.repoAcceptsContributions===!1&&n.push("Repo has no recent merged PRs"),e.noExistingPR&&r.push("No existing PR"),e.notClaimed&&r.push("Not claimed"),e.projectIsActive&&!e.projectCheckFailed&&r.push("Active project"),e.clearRequirements&&r.push("Clear requirements"),e.contributionGuidelinesFound&&r.push("Has contribution guidelines"),e.effectiveMergedCount>0&&r.push(`Trusted project (${e.effectiveMergedCount} PR${e.effectiveMergedCount>1?"s":""} merged)`),e.orgHasMergedPRs&&r.push(`Org affinity (merged PRs in other ${e.orgName} repos)`),e.matchesCategory&&r.push("Matches preferred project category"),e.issueClosed&&n.push("Issue is closed"),e.notTakeableReason&&n.push(e.notTakeableReason);let s;e.issueClosed||e.linkedPRMerged||e.linkedPRClosed||e.ownPR||e.notTakeableReason?s="skip":e.passedAllChecks&&e.repoAcceptsContributions!==!1?s="approve":n.length>2?s="skip":s="needs_review";let o=e.projectCheckFailed||e.existingPRInconclusive||e.claimInconclusive||e.mergedCountInconclusive||e.repoAcceptsContributions===null;return s==="approve"&&o&&(s="needs_review",t.push("Recommendation downgraded: one or more checks were inconclusive")),e.cautionReasons?.length&&(n.push(...e.cautionReasons),s==="approve"&&(s="needs_review")),{notes:t,reasonsToApprove:r,reasonsToSkip:n,recommendation:s}}var ja,J2,Y2,Ss,tg=A(()=>{It();ft();pt();Y0();dk();hk();fD();Rk();vk();Dn();Fa();kk();ja="issue-vetting",J2=3,Y2=900*1e3;Ss=class{octokit;stateReader;budgetTracker;constructor(t,r,n=fr()){this.octokit=t,this.stateReader=r,this.budgetTracker=n}async vetIssue(t,r){let n=gt(),s=r?.featureSignals?`:r${r.featureSignals.reactions}c${r.featureSignals.comments}m${r.featureSignals.hasMilestone?1:0}o${r.featureSignals.onRoadmap?1:0}w${r.featureSignals.wontfixNoContributor?1:0}`:"",o=Lr(`vet:${t}${s}`),i=n.getIfFresh(o,Y2);if(i&&typeof i=="object"&&"issue"in i&&"viabilityScore"in i)return se(ja,`Vetting cache hit for ${t}`),i;let a=Ao(t);if(!a||a.type!=="issues")throw new ot(`Invalid issue URL: ${t}`);let{owner:c,repo:u,number:d}=a,p=`${c}/${u}`,m=r?.prefetched??await this.fetchIssueCore(c,u,d),f=this.stateReader.getReposWithMergedPRs(),g=f.includes(p),[h,b,w,y,S]=await Promise.all([oD(this.octokit,c,u,d),aD(this.octokit,c,u,d,m.commentCount),pD(this.octokit,c,u),mD(this.octokit,c,u),g?Promise.resolve(0):iD(this.octokit,c,u,this.budgetTracker)]),k=await gD(this.octokit,c,u,{contributingText:y?.rawContent}),R=h.passed,P=b.passed,C=this.stateReader.getGitHubUsername?.()??"",E=C!==""&&m.authorLogin?.toLowerCase()===C.toLowerCase(),T;m.authorIsBot?T="Filed by a bot account":!E&&fk(m.body)&&(T="Reporter offered to send the fix");let M=[];!m.authorIsBot&&m.authorLooksLikeBot&&M.push("Author login looks like a bot"),k.matched&&M.push(`AI contribution policy in ${k.sourceFile??"repo docs"}`);let G=h.linkedPR,X=!R&&!!G&&G.state==="open"&&!G.merged&&C!==""&&G.author.toLowerCase()===C.toLowerCase(),ve=!!G&&G.merged,he=!!G&&G.state==="closed"&&!G.merged,oe=cD(m.body),Z=w.checkFailed?!0:w.isActive,$e=Q2(w),Re={passedAllChecks:R&&P&&Z&&oe,checks:{noExistingPR:R,notClaimed:P,projectActive:Z,clearRequirements:oe,contributionGuidelinesFound:!!y},contributionGuidelines:y,linkedPR:h.linkedPR,notes:[]},Xe={id:m.id,url:t,repo:p,number:d,title:m.title,status:"candidate",labels:m.labels,createdAt:m.createdAt,updatedAt:m.updatedAt,vetted:!0,vettingResult:Re},Ke=!g&&S===null,tt=g?1:S??0,ct=p.split("/")[0],sr=!1;ct&&p.includes("/")&&(sr=f.some(Et=>Et.startsWith(ct+"/")&&Et!==p));let et=Q0(p,this.stateReader.getProjectCategories()),Je=m.state==="closed",Fr=w.checkFailed||!!h.inconclusive||!!b.inconclusive||Ke||$e===null,{notes:Ps,reasonsToApprove:Es,reasonsToSkip:Fn,recommendation:Wo}=X2({noExistingPR:R,ownPR:X,linkedPRMerged:ve,linkedPRClosed:he,notClaimed:P,clearRequirements:oe,contributionGuidelinesFound:!!y,projectIsActive:w.checkFailed?!1:w.isActive,projectCheckFailed:!!w.checkFailed,projectFailureReason:w.failureReason,existingPRInconclusive:!!h.inconclusive,existingPRReason:h.inconclusive?h.reason:void 0,claimInconclusive:!!b.inconclusive,claimReason:b.inconclusive?b.reason:void 0,mergedCountInconclusive:Ke,effectiveMergedCount:tt,orgName:ct,orgHasMergedPRs:sr,matchesCategory:et,issueClosed:Je,passedAllChecks:Re.passedAllChecks,repoAcceptsContributions:$e,notTakeableReason:T,cautionReasons:M});Re.notes=Ps;let Vo=w.checkFailed?0:K0(w.stargazersCount??0,w.forksCount??0);w.checkFailed&&Vo===0&&Re.notes.push("Repo quality bonus unavailable: could not fetch star/fork counts due to API error");let qo=this.stateReader.getRepoScore(p),K=J0({repoScore:qo,hasExistingPR:!R,isClaimed:!P,clearRequirements:oe,hasContributionGuidelines:!!y,issueUpdatedAt:m.updatedAt,closedWithoutMergeCount:this.stateReader.getClosedWithoutMergeCount?.(p)??0,mergedPRCount:tt,orgHasMergedPRs:sr,repoQualityBonus:Vo,matchesPreferredCategory:et,featureSignals:r?.featureSignals}),He=this.stateReader.getStarredRepos(),Wt="normal";tt>0?Wt="merged_pr":He.includes(p)&&(Wt="starred");let qe=this.stateReader.getSLMTriageConfig(),xt=null;if(qe){let Et={model:qe.model};qe.host&&(Et.host=qe.host),xt=await _D(vD({issue:{...Xe,body:m.body},linkedPR:h.linkedPR??null}),Et)}let yr={issue:Xe,issueState:Je?"closed":"open",vettingResult:Re,projectHealth:w,antiLLMPolicy:k,slmTriage:xt,recommendation:Wo,reasonsToSkip:Fn,reasonsToApprove:Es,viabilityScore:K,searchPriority:Wt};return Fr||n.set(o,"",yr),yr}async fetchIssueCore(t,r,n){let{data:s}=await this.octokit.issues.get({owner:t,repo:r,issue_number:n});return{id:s.id,title:s.title,body:s.body||"",state:s.state==="closed"?"closed":"open",labels:s.labels.map(o=>typeof o=="string"?o:o.name||""),commentCount:s.comments,createdAt:s.created_at,updatedAt:s.updated_at,authorLogin:s.user?.login,authorIsBot:s.user?.type==="Bot"||/\[bot\]$/i.test(s.user?.login??""),authorLooksLikeBot:_k(s.user?.login)}}async prefetchMergedPRCounts(t){let r=this.stateReader.getGitHubUsername?.()??"";if(!r)return;let n=new Set(this.stateReader.getReposWithMergedPRs()),s=new Set,o=[];for(let{owner:i,repo:a}of t){let c=`${i}/${a}`;n.has(c)||s.has(c)||(s.add(c),o.push({owner:i,repo:a}))}o.length!==0&&await bD(this.octokit,r,o)}async vetIssuesParallel(t,r,n){let s=[],o=new Map,i=0,a=0,c=0,u=null,d=null,p=0,m=new Set,f=[...new Set(t)],g=f.flatMap(y=>{let S=Ao(y);return S&&S.type==="issues"?[{owner:S.owner,repo:S.repo,number:S.number}]:[]}),[h]=await Promise.all([yD(this.octokit,g),this.prefetchMergedPRCounts(g)]),b=y=>{let S=Ao(y);return S&&S.type==="issues"?h.get(eg(S.owner,S.repo,S.number)):void 0};for(let y of f){if(s.length>=r||u)break;let S=Ao(y),k=S?`${S.owner}/${S.repo}`:null;if(k&&m.has(k)){se(ja,`Skipping ${y}: repo already returned 403`);continue}c++;let R=b(y),P=this.vetIssue(y,R?{prefetched:R}:void 0).then(C=>{s.length<r&&(n&&(C.searchPriority=n),s.push(C))}).catch(C=>{if(Fe(C)===401){u??=C;return}if(L0(C)){d??=C,p++,i++,k&&m.add(k),H(ja,`Access forbidden for ${y} (SAML/token scope?) \u2014 skipping this repo:`,Y(C));return}i++,mt(C)&&a++,H(ja,`Error vetting issue ${y}:`,Y(C))}).finally(()=>o.delete(y));o.set(y,P),o.size>=J2&&await Promise.race(o.values())}if(await Promise.allSettled(o.values()),u)throw s.length>0&&H(ja,`Auth failed mid-batch after ${s.length} successful vet(s) \u2014 discarding partial results`),u;if(d&&c>0&&p===c)throw d;let w=i===c&&c>0;return w&&H(ja,`All ${c} issue(s) failed vetting. This may indicate a systemic issue (rate limit, auth, network).`),{candidates:s.slice(0,r),allFailed:w,rateLimitHit:a>0}}}});function CD(){return Ck}function PD(){Ck=0}function r4(e){return e.length===0?"":`label:${e.map(t=>JSON.stringify(t)).join(",")}`}function ED(e,t){let r=new Set;for(let n of e)for(let s of cl[n]??[])r.add(s);for(let n of t)r.add(n);return[...r]}function AD(e){let t=[],r=Math.max(...e.map(n=>n.length),0);for(let n=0;n<r;n++)for(let s of e)n<s.length&&t.push(s[n]);return t}async function Pk(e,t,r=fr()){let n=Lr(`search:${t.q}:${t.sort}:${t.order}:${t.per_page}`),s=gt(),o=s.getIfFresh(n,TD);if(o)return se(gr,"Search cache hit for query"),o;await r.waitForBudget();let i;try{i=(await e.search.issuesAndPullRequests(t)).data}finally{r.recordCall()}return i.items.length>0?s.set(n,"",i):se(gr,"Skipping cache for empty search result (possible rate limit artifact)"),i}async function Ek(e,t,r=fr()){let n=Lr(`gqlsearch2:${t.q}:${t.sort}:${t.order}:${t.per_page}`),s=gt(),o=s.getIfFresh(n,TD);if(o)return se(gr,"GraphQL search cache hit for query"),o;let i=`${t.q} sort:${t.sort}-${t.order}`,a=await wD(e,i,Math.min(t.per_page,100));return a?(Ck++,a.items.length>0?s.set(n,"",a):se(gr,"Skipping cache for empty GraphQL search result (possible transient artifact)"),a):(H(gr,"GraphQL broad search unavailable; falling back to REST search API"),Pk(e,t,r))}async function $D(e,t,r,n){let s=[];for(let o of t){if(s.length>=n*3)break;let[i,a]=o.split("/");if(!(!i||!a))try{let{data:c}=await e.repos.get({owner:i,repo:a});if(!c.pushed_at)continue;let u=new Date(c.pushed_at),d=new Date;if(d.setDate(d.getDate()-30),u<d||(c.stargazers_count??0)<r||c.archived)continue;let{data:p}=await e.issues.listForRepo({owner:i,repo:a,state:"open",sort:"created",direction:"desc",per_page:5}),m=p.filter(f=>!f.pull_request&&!f.assignee);for(let f of m)s.push({html_url:f.html_url,repository_url:`https://api.github.com/repos/${o}`,updated_at:f.updated_at??"",title:f.title,labels:f.labels});await mr(kD)}catch(c){if(Fe(c)===401)throw c;if(mt(c)){H(gr,`Rate limit hit fetching issues from ${o}:`,Y(c));break}H(gr,`Error fetching issues from ${o}:`,Y(c))}}return s}async function Ak(e,t,r,n,s,o,i,a=5){let c=[],u=0,d=0;for(let f=0;f<r.length&&!(c.length>=s);f++){f>0&&await mr(kD);let g=r[f],[h,b]=g.split("/");try{let w=n.length>0?n:[void 0],y=new Set,S=[];for(let P of w){let C=await e.issues.listForRepo({owner:h,repo:b,state:"open",sort:"created",direction:"desc",per_page:a,...P!==void 0?{labels:P}:{}});for(let E of C.data)y.has(E.html_url)||(y.add(E.html_url),S.push(E))}let R=S.filter(P=>!("pull_request"in P)&&!P.assignee).map(P=>({html_url:P.html_url,repository_url:`https://api.github.com/repos/${g}`,updated_at:P.updated_at??"",title:P.title,labels:P.labels}));if(R.length>0){let P=i(R);if(P.length>0){let C=Math.min(e4,s-c.length),{candidates:E,rateLimitHit:T}=await t.vetIssuesParallel(P.slice(0,C*2).map(M=>M.html_url),C,o);c.push(...E.slice(0,C)),T&&d++}}}catch(w){if(Fe(w)===401)throw w;u++,mt(w)&&d++,H(gr,`Error fetching issues from ${g}:`,Y(w))}}let p=u===r.length&&r.length>0,m=d>0;return p&&H(gr,`All ${r.length} repo(s) failed for ${o} phase. This may indicate a systemic issue (rate limit, auth, network).`),{candidates:c,allReposFailed:p,rateLimitHit:m}}async function n4(e,t,r,n,s,o=fr()){return(await Ek(e,{q:n(r4(t)),sort:"created",order:"desc",per_page:s},o)).items}function s4(e,t,r){return t||e.length===0?[""]:e.length===1?[`language:${e[0]}`]:r?e.map(n=>`language:${n}`):[e.map(n=>`language:${n}`).join(" ")]}async function Tk(e,t,r,n,s,o,i=fr(),a=0,c=0){let u=s4(t,r,n.length>0),d=u.length>0?a%u.length:0,p=[...u.slice(d),...u.slice(0,d)],m=new Set,f=[];for(let g=0;g<p.length;g++){g>0&&await mr(t4);let h=await n4(e,n,c,b=>`${s(p[g])} ${b}`.replace(/ +/g," ").trim(),o,i);for(let b of h)m.has(b.html_url)||(m.add(b.html_url),f.push(b))}return f}async function ml(e,t,r,n,s,o,i){let a=q0(t);if(a.size>0){let h=t.filter(b=>a.has(it(b.repository_url)??"")).length;se(gr,`[SPAM_FILTER] Filtered ${h} issues from ${a.size} label-farming repos: ${[...a].join(", ")}`)}let c=0,u=r(t).filter(h=>{let b=it(h.repository_url);return!b||a.has(b)?!1:typeof h.repositoryStars=="number"&&h.repositoryStars<o?(c++,!1):n.every(w=>!w.has(b))}).slice(0,s*2);if(c>0&&se(gr,`[STAR_FILTER] Dropped ${c} ${i} items below ${o} stars before vetting`),u.length===0)return se(gr,`[${i}] All ${t.length} items filtered before vetting`),{candidates:[],allVetFailed:!1,rateLimitHit:!1};let{candidates:d,allFailed:p,rateLimitHit:m}=await e.vetIssuesParallel(u.map(h=>h.html_url),s,"normal"),f=d.filter(h=>h.projectHealth.checkFailed?!0:(h.projectHealth.stargazersCount??0)>=o),g=d.length-f.length;return g>0&&se(gr,`[STAR_FILTER] Filtered ${g} ${i} candidates below ${o} stars`),{candidates:f,allVetFailed:p,rateLimitHit:m}}var gr,kD,e4,t4,Ck,TD,$k=A(()=>{sk();ft();pt();Dn();lk();It();Fa();vk();gr="search-phases",kD=2e3,e4=2,t4=500,Ck=0;TD=900*1e3});function ng(e){return e.personalization?.kind==="boosted"?e.personalization.score:0}function rg(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(Boolean))}function OD(e,t={}){let r=rg(t.preferLanguages),n=rg(t.preferRepos),s=rg(t.avoidRepos),o=rg(t.boostIssueTypes);return r.size===0&&n.size===0&&s.size===0&&o.size===0?e:e.map(i=>{let a=0,c=[],u=i.issue.repo.toLowerCase();n.size>0&&n.has(u)&&(a+=20,c.push(`repo affinity: ${i.issue.repo}`));let d=i.projectHealth.checkFailed?null:i.projectHealth.language;if(r.size>0&&d&&r.has(d.toLowerCase())&&(a+=10,c.push(`language match: ${d}`)),o.size>0){let p=i.issue.labels.find(m=>o.has(m.toLowerCase()));p&&(a+=10,c.push(`issue type: ${p}`))}return s.size>0&&s.has(u)&&(a-=15,c.push(`avoided repo: ${i.issue.repo}`)),c.length===0?i:{...i,personalization:{kind:"boosted",score:a,reasons:c}}})}function ID(e,t,r){if(t<=0)return[];let n=Math.max(0,Math.min(1,r));if(n===0)return e.slice(0,t);let s=Math.min(Math.floor(t*n),t);if(s===0)return e.slice(0,t);let o=t-s,i=[],a=new Set;for(let c of e){if(i.length>=o)break;i.push(c),a.add(c.issue.url)}for(let c of e){if(i.length>=t)break;a.has(c.issue.url)||ng(c)===0&&(i.push({...c,personalization:{kind:"diversity"}}),a.add(c.issue.url))}for(let c of e){if(i.length>=t)break;a.has(c.issue.url)||(i.push(c),a.add(c.issue.url))}return i}var xD=A(()=>{});function Ok(e,t,r){if(e.length<=t)return[...e];let n=r*t%e.length;return Array.from({length:t},(s,o)=>e[(n+o)%e.length])}function LD(e){return t=>t.filter(r=>{let n=it(r.repository_url);if(!n)return!1;let s=n.toLowerCase();if(e.excludedRepos.has(s))return!1;if(e.excludeOrgs.size>0){let a=s.split("/")[0];if(a&&e.excludeOrgs.has(a))return!1}if(e.aiBlocklisted.has(s)||e.lowScoringRepos.has(s)||e.skippedUrls.has(r.html_url))return!1;let o=new Date(r.updated_at);return!(Number.isNaN(o.getTime())||Ma(o,e.now)>e.maxAgeDays||!e.includeDocIssues&&W0(r)||V0(r))})}async function l4(e,t,r,n,s){ze(Ce,`Phase 0: Searching issues in ${r.length} merged-PR repos (no label filter, ${DD}/repo)...`);let{candidates:o,allReposFailed:i,rateLimitHit:a}=await Ak(e,t,r,[],n,"merged_pr",s,DD);return ze(Ce,`Found ${o.length} candidates from merged-PR repos`),{candidates:o,error:i?"All merged-PR repo fetches failed":null,rateLimitHit:a}}async function d4(e,t,r,n,s,o,i,a,c,u,d,p){ze(Ce,`Orgs phase: searching ${r.length} preferred org(s)...`);let m=r.slice(0,sg);r.length>sg&&H(Ce,`Orgs phase: capping query at ${sg} org(s); dropping ${r.slice(sg).join(", ")}`);let f=m.map(g=>`org:${g}`).join(" ");try{let g=await Tk(e,n,s,o,y=>`is:issue is:open ${y} no:assignee ${f}`.replace(/ +/g," ").trim(),i*3,p,0,m.length),{candidates:h,allVetFailed:b,rateLimitHit:w}=await ml(t,g,d,[c,u],i,a,"Orgs phase");return ze(Ce,`Found ${h.length} candidates from preferred orgs`),{candidates:h,error:b?"all vetting failed":null,rateLimitHit:w}}catch(g){if(Fe(g)===401)throw g;let h=Y(g);return H(Ce,`Error in preferred-orgs search: ${h}`),{candidates:[],error:h,rateLimitHit:mt(g)}}}async function p4(e,t,r,n,s,o){ze(Ce,`Phase 1: Searching issues in ${r.length} starred repos...`);let i=n.slice(0,3),a=r.slice(0,MD),{candidates:c,allReposFailed:u,rateLimitHit:d}=await Ak(e,t,a,i,s,"starred",o);return ze(Ce,`Found ${c.length} candidates from starred repos`),{candidates:c,error:u?"All starred repo fetches failed":null,rateLimitHit:d}}async function m4(e,t,r,n,s,o,i,a,c,u,d,p,m,f,g=0){ze(Ce,"Phase 2: General issue search...");let h=new Set(p.map(P=>P.issue.repo)),b=[];if(r&&r.length>1){for(let E of r){let T=cl[E]??[];if(T.length===0){H(Ce,`Scope "${E}" has no labels, skipping tier`);continue}b.push({tier:E,tierLabels:T})}let P=new Set(r.flatMap(E=>cl[E]??[])),C=s.filter(E=>!P.has(E));C.length>0&&b.push({tier:"custom",tierLabels:C})}else b.push({tier:"general",tierLabels:n});let w=Math.ceil(a/b.length),y=[],S=null,k=!1;for(let{tier:P,tierLabels:C}of b)try{let E=await Tk(e,o,i,C,X=>`is:issue is:open ${X} no:assignee`.replace(/ +/g," ").trim(),w*3,f,g);ze(Ce,`Phase 2 [${P}]: processing ${E.length} items...`);let{candidates:T,allVetFailed:M,rateLimitHit:G}=await ml(t,E,m,[u,d,h],w,c,`Phase 2 [${P}]`);y.push(T);for(let X of T)h.add(X.issue.repo);M&&(S=(S?S+"; ":"")+`${P}: all vetting failed`),G&&(k=!0),ze(Ce,`Found ${T.length} candidates from ${P} tier`)}catch(E){if(Fe(E)===401)throw E;let T=Y(E);S=(S?S+"; ":"")+`${P}: ${T}`,mt(E)&&(k=!0),H(Ce,`Error in ${P} tier search: ${T}`),y.push([])}let R=AD(y);return R.length===0&&S&&H(Ce,`All ${b.length} scope tiers failed in Phase 2: ${S}`),{candidates:R.slice(0,a),error:S,rateLimitHit:k}}async function f4(e,t,r,n,s,o,i,a,c,u,d,p,m=0){ze(Ce,"Phase 3: Searching actively maintained repos...");let f=new Set(u.map(k=>k.issue.repo)),g=Ok(c,u4,m).filter(k=>!i.has(k)&&!f.has(k));if(g.length>0){ze(Ce,`Phase 3: Checking ${g.length} starred repos via REST API...`);let k=await $D(e,g,n,o);if(k.length>0)try{let{candidates:R,allVetFailed:P,rateLimitHit:C}=await ml(t,k,d,[i,f],o,n,"Phase 3 (REST)");if(R.length>0)return ze(Ce,`Found ${R.length} candidates from maintained-repo REST search`),{candidates:R,error:P?"all vetting failed":null,rateLimitHit:C}}catch(R){if(Fe(R)===401)throw R;H(Ce,"Phase 3 REST vetting failed, falling back to Search API:",Y(R))}}ze(Ce,"Phase 3: Falling back to Search API...");let h=new Date;h.setDate(h.getDate()-30);let b=h.toISOString().split("T")[0],w=X0(s),y=w.length>0?`topic:${w[0]}`:"",S=`is:issue is:open no:assignee ${r} ${y} pushed:>=${b} archived:false`.replace(/ +/g," ").trim();try{let k=await Ek(e,{q:S,sort:"updated",order:"desc",per_page:o*3},p);ze(Ce,`Found ${k.total_count} issues in maintained-repo search, processing top ${k.items.length}...`);let{candidates:R,allVetFailed:P,rateLimitHit:C}=await ml(t,k.items,d,[i,a,f],o,n,"Phase 3");return ze(Ce,`Found ${R.length} candidates from maintained-repo search`),{candidates:R,error:P?"all vetting failed":null,rateLimitHit:C}}catch(k){if(Fe(k)===401)throw k;let R=Y(k);return H(Ce,`Error in maintained-repo search: ${R}`),{candidates:[],error:R,rateLimitHit:mt(k)}}}var Ce,o4,za,DD,i4,a4,c4,MD,u4,sg,xo,Ik=A(()=>{Zf();Fa();It();sk();Io();ft();pt();lk();tg();dk();$k();xD();Ce="issue-discovery",o4=20,za=10,DD=30,i4=365,a4=.5,c4=10,MD=10,u4=15;sg=8;xo=class{preferences;stateReader;octokit;githubToken;vetter;budgetTracker;rateLimitWarning=null;constructor(t,r,n,s=fr()){this.preferences=r,this.stateReader=n,this.githubToken=t,this.octokit=In(t),this.budgetTracker=s,this.vetter=new Ss(this.octokit,this.stateReader,this.budgetTracker)}getStarredRepos(){return this.stateReader.getStarredRepos()}async searchIssues(t={}){let r=this.preferences,n=t.languages||r.languages,s=r.scope,o=t.labels||(s?ED(s,r.labels):r.labels),i=t.maxResults||10,a=r.minStars??50,c=t.interPhaseDelayMs??r.interPhaseDelayMs??0,u=Oo,p=((...K)=>K.find(He=>He&&He.length>0)??["all"])(t.strategies,r.defaultStrategy),m=new Set(p.includes("all")?u:p),f=[],g=[],h={},b=!1,w=async()=>{c>0&&(ze(Ce,`Waiting ${(c/1e3).toFixed(0)}s between phases for rate limit management...`),await mr(c))},y=(K,He)=>{g.push(...He.candidates),h[K]=He.error,He.rateLimitHit&&(b=!0)},S=()=>g.filter(K=>K.recommendation!=="skip").length;this.rateLimitWarning=null,PD();let k=this.budgetTracker,R=za-1,P=!1;try{let K=await qf(this.githubToken);if(R=K.remaining,k.init(K.remaining,K.resetAt),K.remaining<5){let He=new Date(K.resetAt).toLocaleTimeString("en-US",{hour12:!1});this.rateLimitWarning=`GitHub search API quota low (${K.remaining}/${K.limit} remaining, resets at ${He}). Search may be slow.`,H(Ce,this.rateLimitWarning)}R<za?ze(Ce,`Search budget critical (${R} remaining) \u2014 skipping the starred phase; broad/maintained still run on GraphQL (points bucket)`):R<o4&&ze(Ce,`Search budget low (${R} remaining) \u2014 broad/maintained run on GraphQL (points bucket), unaffected by REST search quota`)}catch(K){if(Fe(K)===401)throw K;P=!0,k.init(za,new Date(Date.now()+6e4).toISOString()),H(Ce,"Could not check rate limit \u2014 using conservative budget, skipping the starred phase:",Y(K))}R<=0&&(this.rateLimitWarning="GitHub search API quota exhausted \u2014 skipping the starred phase; other phases don't use it.",H(Ce,this.rateLimitWarning));let C=this.stateReader.getReposWithMergedPRs(),E=this.stateReader.getReposWithOpenPRs(),T=this.getStarredRepos(),M=new Set(T),G=new Set(this.deriveLowScoringRepos(r.minRepoScoreThreshold).map(K=>K.toLowerCase())),X=n.some(K=>K.toLowerCase()==="any"),ve=X?"":n.map(K=>`language:${K}`).join(" "),he=new Set(r.aiPolicyBlocklist.map(K=>K.toLowerCase()));he.size>0&&se(Ce,`[AI_POLICY_FILTER] Filtering issues from ${he.size} blocklisted repo(s): ${[...he].join(", ")}`);let oe={excludedRepos:new Set(r.excludeRepos.map(K=>K.toLowerCase())),excludeOrgs:new Set((r.excludeOrgs??[]).map(K=>K.toLowerCase())),aiBlocklisted:he,lowScoringRepos:G,skippedUrls:t.skippedUrls??new Set,now:new Date,includeDocIssues:r.includeDocIssues??!0},Z=LD({...oe,maxAgeDays:r.maxIssueAgeDays||90}),$e=LD({...oe,maxAgeDays:i4}),Re=t.repoRotationOffsets??{},Xe=Ok([...new Set([...C,...E])],c4,Re.merged??0),Ke=new Set(Xe),tt=r.preferredOrgs??[],ct=Ok(T,MD,Re.starred??0).filter(K=>!Ke.has(K)),sr={all:!1,merged:Xe.length>0,orgs:tt.length>0,starred:ct.length>0&&R>=za,broad:!0,maintained:!0},et=t.broadPhaseDelayMs??r.broadPhaseDelayMs??0,Je={merged:async K=>{y("0",await l4(this.octokit,this.vetter,Xe,K,$e)),f.push("merged")},orgs:async K=>{y("orgs",await d4(this.octokit,this.vetter,tt,n,X,o,K,a,Ke,M,Z,k)),f.push("orgs")},starred:async K=>{y("1",await p4(this.octokit,this.vetter,ct,o,K,Z)),f.push("starred")},broad:async K=>{y("2",await m4(this.octokit,this.vetter,s,o,r.labels,n,X,K,a,Ke,M,g,Z,k,t.languageRotationOffset??0)),f.push("broad")},maintained:async K=>{y("3",await f4(this.octokit,this.vetter,ve,a,r.projectCategories??[],K,Ke,M,T,g,Z,k,Re.maintained??0)),f.push("maintained")}},Fr=R<za;if(t.strategyRotationOffset!==void 0){let K=t.strategyRotationOffset,He=Oo.length,Wt=Oo.map((qe,xt)=>Oo[(K+xt)%He]).filter(qe=>m.has(qe));Fr=!1;for(let qe of Wt){if(!sr[qe]){qe==="starred"&&ct.length>0&&(Fr=!0);continue}if(f.length>0&&await w(),ze(Ce,`Round-robin: running the ${qe} strategy`),await Je[qe](i-S()),S()>0)break}}else{let K=sr.orgs&&m.has("orgs"),He=K||T.length>0&&m.has("starred")||m.has("broad")||m.has("maintained");if(sr.merged&&m.has("merged")){let Et=He?Math.max(1,Math.ceil(i*a4)):i;await Je.merged(Math.min(i-g.length,Et))}g.length<i&&K&&(await w(),await Je.orgs(i-g.length)),g.length<i&&T.length>0&&R>=za&&m.has("starred")&&(await w(),ct.length>0&&await Je.starred(i-g.length));let Wt=r.skipBroadWhenSufficientResults??8,qe=Wt>0?Math.min(Wt,i-1):0,xt=S();if(xt>=i&&m.has("broad"))ze(Ce,`Skipping broad search: ${xt} viable candidate(s) already meet maxResults (${i})`);else if(m.has("broad")){let Et=new Set(tt.map(un=>un.toLowerCase())),Xa=g.filter(un=>un.recommendation!=="skip"&&!Ke.has(un.issue.repo)&&!M.has(un.issue.repo)&&!Et.has(un.issue.repo.split("/")[0]?.toLowerCase()??"")).length;qe>0&&Xa>=qe?ze(Ce,`Skipping broad search: already found ${Xa} viable candidate(s) from new repos (threshold: ${qe})`):(await w(),g.length>0&&et>0?(ze(Ce,`Waiting ${(et/1e3).toFixed(0)}s for rate limit cooldown before broad search...`),await mr(et)):g.length===0&&ze(Ce,"Skipping broad phase delay: no results from previous phases, proceeding immediately"),await Je.broad(i-xt))}let yr=S();yr>=i&&m.has("maintained")?ze(Ce,`Skipping maintained search: ${yr} viable candidate(s) already meet maxResults (${i})`):m.has("maintained")&&(await w(),await Je.maintained(i-yr))}let Ps=Fr,Es=Ps?P?" The starred-repo phase was skipped as a precaution because the rate-limit check failed (quota unknown); the other strategies don't use that quota.":` The starred-repo phase was skipped due to critically low API quota (${R} remaining); the other strategies don't use that quota.`:"";if(g.length===0){let K=[h[0]?`Phase 0 (merged-PR repos): ${h[0]}`:null,h.orgs?`Orgs phase (preferred orgs): ${h.orgs}`:null,h[1]?`Phase 1 (starred repos): ${h[1]}`:null,h[2]?`Phase 2 (general): ${h[2]}`:null,h[3]?`Phase 3 (maintained repos): ${h[3]}`:null].filter(Boolean),He=K.length>0?` ${K.join(". ")}.`:"";if(b||Ps)return this.rateLimitWarning=`Search returned no results due to GitHub API rate limits.${He}${Es} Try again after the rate limit resets.`,{candidates:[],strategiesUsed:f};throw new ot(`No issue candidates found across all search phases.${He} Try adjusting your search criteria (languages, labels) or check your network connection.`,f)}(b||Ps)&&(this.rateLimitWarning=`Search results may be incomplete: GitHub API rate limits were hit during search.${Es} Found ${g.length} candidate${g.length===1?"":"s"} but some search phases were limited. Try again after the rate limit resets for complete results.`);let Fn=OD(g,{preferLanguages:t.preferLanguages,preferRepos:t.preferRepos,avoidRepos:t.avoidRepos,boostIssueTypes:t.boostIssueTypes});Fn.sort((K,He)=>{let Wt={merged_pr:0,starred:1,normal:2},qe=Wt[K.searchPriority]-Wt[He.searchPriority];if(qe!==0)return qe;let xt={approve:0,needs_review:1,skip:2},yr=xt[K.recommendation]-xt[He.recommendation];if(yr!==0)return yr;let Et=ng(He)-ng(K);return Et!==0?Et:He.viabilityScore-K.viabilityScore});let Wo=[...Fn.filter(K=>K.recommendation!=="skip"),...Fn.filter(K=>K.recommendation==="skip")],Vo=Z0(Wo,2),qo=ID(Vo,i,t.diversityRatio??0);return ze(Ce,`Search complete: ${k.getTotalCalls()} REST Search API call(s) + ${CD()} GraphQL broad-search query/queries used, ${qo.length} candidates returned`),{candidates:qo,strategiesUsed:f}}async vetIssue(t){return this.vetter.vetIssue(t)}deriveLowScoringRepos(t){let r=[],n=new Set([...this.stateReader.getReposWithMergedPRs(),...this.stateReader.getStarredRepos()]);for(let s of n){let o=this.stateReader.getRepoScore(s);o!==null&&o<=t&&r.push(s)}return r}}});function FD(){let e=Date.now()-ND;for(let[t,r]of fl.entries())r.fetchedAt<e&&fl.delete(t)}function Dk(e,t,r){let n=new Set,s=`${t}/${r}`.toLowerCase(),o=d=>d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${o(t)}/${o(r)}#(\\d+)\\b`,"gi");for(let d of e.matchAll(i)){let p=Number.parseInt(d[1],10);p>0&&n.add(p)}let a=/\b[\w.-]+\/[\w.-]+#\d+\b/gi,c=!1;for(let d of e.split(`
305
+ `)){if(/^\s*(```|~~~)/.test(d)){c=!c;continue}if(c||/^\s*#+\s/.test(d))continue;let p=d.replace(a,"").replace(/`[^`]*`/g,"");for(let m of p.matchAll(/(?:^|[^&\w])#(\d+)\b/g)){let f=Number.parseInt(m[1],10);f>0&&n.add(f)}}let u=/https?:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/issues\/(\d+)/gi;for(let d of e.matchAll(u))if(d[1].toLowerCase()===s){let p=Number.parseInt(d[2],10);p>0&&n.add(p)}return n}async function og(e,t,r){let n=`${t}/${r}`.toLowerCase(),s=fl.get(n);if(s&&Date.now()-s.fetchedAt<ND)return s.refs;let o=xk.get(n);if(o)return o;let i=h4(e,t,r,n);xk.set(n,i);try{return await i}finally{xk.delete(n)}}async function h4(e,t,r,n){for(let o of g4){let{text:i}=await Ga(e,t,r,o);if(!i)continue;let a=Dk(i,t,r);return fl.set(n,{refs:a,fetchedAt:Date.now()}),FD(),a}let s=new Set;return fl.set(n,{refs:s,fetchedAt:Date.now()}),FD(),s}var ND,g4,fl,xk,Lk=A(()=>{Xf();ND=3600*1e3,g4=["ROADMAP.md","docs/ROADMAP.md",".github/ROADMAP.md","Roadmap.md","roadmap.md"],fl=new Map;xk=new Map});function Nk(e,t=Fk){return Object.values(e).filter(r=>r.mergedPRCount>=t).sort((r,n)=>n.mergedPRCount-r.mergedPRCount).map(r=>r.repo)}function Gk(e){if(e.hasMilestone||e.isOnRoadmap)return"bigger-bet";for(let t of e.labels)if(w4.has(t.toLowerCase()))return"bigger-bet";return"quick-win"}function ig(e,t,r=b4){let n=e.filter(g=>g.horizon==="quick-win").sort((g,h)=>h.viabilityScore-g.viabilityScore),s=e.filter(g=>g.horizon==="bigger-bet").sort((g,h)=>h.viabilityScore-g.viabilityScore),o=Math.max(0,Math.min(1,r)),i=Math.round(t*o),a=t-i,c=Math.min(n.length,i),u=Math.min(s.length,a),d=c,p=u,m=i-c,f=a-u;return m>0&&(p=Math.min(s.length,p+m)),f>0&&(d=Math.min(n.length,d+f)),{quickWins:n.slice(0,d),biggerBets:s.slice(0,p)}}function _4(e){if(!e.labels.some(o=>R4.has(o.toLowerCase())))return!1;let r=new Date(e.createdAt);return Number.isNaN(r.getTime())?!1:((e.now??new Date).getTime()-r.getTime())/(1e3*60*60*24)>=(e.minAgeDays??S4)}function BD(e){let t=new Set([...e.excludeRepos??[],...e.aiPolicyBlocklist??[]].map(n=>n.toLowerCase())),r=new Set((e.excludeOrgs??[]).map(n=>n.toLowerCase()));return n=>{let s=n.toLowerCase();if(t.has(s))return!1;let o=s.split("/")[0];return!(o&&r.has(o))}}function HD(e){return Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t?.name).filter(t=>typeof t=="string"):[]}function WD(e){let t=HD(e).map(r=>r.toLowerCase());return t.length===0||t.some(r=>zD.has(r))?!1:t.some(r=>ag.includes(r))}async function VD(e,t,r){let n=HD(e),s=!!e.milestone,o=e.reactions?.total_count??0,i=e.comments??0,a=e.created_at?_4({labels:n,createdAt:e.created_at}):!1,c=r!==void 0,u=c&&typeof e.number=="number"&&r.has(e.number),d;try{d=await t.vetIssue(e.html_url,{featureSignals:{reactions:o,comments:i,hasMilestone:s,wontfixNoContributor:a,...c?{onRoadmap:u}:{}}})}catch(m){return Be(m),H(Mk,`vet failed for ${e.html_url}: ${Y(m)}`),null}let p=Gk({hasMilestone:s,labels:n,...c?{isOnRoadmap:u}:{}});return{...d,horizon:p}}async function cg(e){let t=BD(e),r=Nk(e.repoScores,e.anchorThreshold).filter(t);if(r.length===0)return{quickWins:[],biggerBets:[],anchorRepos:[],message:Uk};let n=[];for(let a=0;a<r.length;a++){a>0&&await mr(y4);let[c,u]=r[a].split("/"),d,p;try{let[f,g]=await Promise.all([e.octokit.issues.listForRepo({owner:c,repo:u,state:"open",sort:"updated",direction:"desc",per_page:20}),og(e.octokit,c,u)]);d=f,p=g}catch(f){Be(f),H(Mk,`failed to list issues for ${r[a]}: ${Y(f)}`);continue}let m=d.data.filter(f=>!f.pull_request&&!f.assignee&&WD(f));for(let f of m){let g=await VD(f,e.vetter,p);g&&n.push(g)}}let s=n.filter(a=>a.viabilityScore>=jD),o=ig(s,e.count,e.splitRatio),i=o.quickWins.length+o.biggerBets.length;return{...o,anchorRepos:r,message:i===0?jk:null}}function UD(e){let t=["is:issue","is:open","no:assignee"],r=`label:${ag.map(n=>JSON.stringify(n)).join(",")}`;t.push(r);for(let n of zD)t.push(`-label:"${n}"`);e.language&&t.push(`language:${e.language}`);for(let n of e.excludeRepos??[])t.push(`-repo:${n}`);for(let n of e.excludeOrgs??[])t.push(`-user:${n}`);return t.join(" ")}function k4(e){let t={excludeRepos:e.excludeRepos,excludeOrgs:e.excludeOrgs},r=(e.languages??[]).filter(n=>n&&n.toLowerCase()!=="any");return r.length===0?[UD(t)]:r.map(n=>UD({...t,language:n}))}async function qD(e){let t=k4({languages:e.languages,excludeRepos:e.excludeRepos,excludeOrgs:e.excludeOrgs}),r=e.maxToVet??v4,n;try{let c=[],u=new Set;for(let p of t){let m=await Pk(e.octokit,{q:p,sort:"interactions",order:"desc",per_page:r});for(let f of m.items)u.has(f.html_url)||(u.add(f.html_url),c.push(f))}let d=BD(e);n=c.filter(p=>!p.pull_request&&!p.assignee&&WD(p)).filter(p=>{let m=it(p.html_url);return m===null||d(m)}).slice(0,r)}catch(c){return Be(c),H(Mk,`broad feature search failed: ${Y(c)}`),{quickWins:[],biggerBets:[],anchorRepos:[],message:GD}}let s=[];for(let c of n){let u=await VD(c,e.vetter);u&&s.push(u)}let o=s.filter(c=>c.viabilityScore>=jD),i=ig(o,e.count,e.splitRatio),a=i.quickWins.length+i.biggerBets.length;return{...i,anchorRepos:[],message:a===0?GD:null}}var Mk,y4,jD,Fk,b4,w4,ag,zD,R4,S4,Uk,jk,GD,v4,zk=A(()=>{ft();pt();It();Lk();$k();Mk="feature-discovery",y4=2e3,jD=40,Fk=3,b4=.6;w4=new Set(["roadmap","accepted-rfc","proposal"]);ag=["enhancement","feature","feature-request","proposal","roadmap","accepted-rfc"],zD=new Set(["good first issue","bug","documentation"]),R4=new Set(["help wanted","contributions welcome","up-for-grabs","bounty","pinned","unmaintained"]),S4=60;Uk="No anchor repos yet (need 3+ merged PRs in a repo). Try `scout search` to build relationships first.",jk="No open feature opportunities in your anchor repos right now. Check back next week, or try `scout search` for fix-mode work.";GD="No open feature opportunities matched your filters. Try widening your language preferences in `scout config`.",v4=30});function E4(e){if(mt(e))return"rate_limit";let t=Fe(e);if(t!==void 0&&t>=500&&t<600)return"server";if(e&&typeof e=="object"&&"code"in e){let r=e.code;if(r==="ECONNREFUSED"||r==="ENOTFOUND"||r==="ETIMEDOUT"||r==="ECONNRESET"||r==="EAI_AGAIN")return"network"}return e instanceof Error&&e.message.toLowerCase().includes("fetch failed")?"network":"unknown"}function JD(){return Wk.join(Rs(),C4)}function YD(){return Wk.join(Rs(),P4)}function T4(e,t){let r=Date.now()-A4,n=new Map;for(let s of[...e,...t]){let o=n.get(s.url);(!o||s.removedAt>o.removedAt)&&n.set(s.url,s)}return[...n.values()].filter(s=>{let o=new Date(s.removedAt).getTime();return Number.isFinite(o)&&o>=r})}function QD(e,t,r,n){if(t.length===0)return e;let s=new Map(t.map(o=>[o.url,o.removedAt]));return e.filter(o=>{let i=s.get(r(o));return i===void 0?!0:n(o)>i})}function gl(e,t){let r=T4(e.tombstones??[],t.tombstones??[]),n=QD(x4(e.savedResults??[],t.savedResults??[]),r,b=>b.issueUrl,b=>b.lastSeenAt),s=QD(D4(e.skippedIssues??[],t.skippedIssues??[]),r,b=>b.url,b=>b.skippedAt),o=new Set(s.map(b=>b.url)),i=n.filter(b=>!o.has(b.issueUrl)),a=e.preferencesUpdatedAt,c=t.preferencesUpdatedAt,d=a!==void 0&&(c===void 0||a>c)?e.preferences:t.preferences,p=ug(a,c),m=Hk(e.mergedPRs,t.mergedPRs),f=Hk(e.closedPRs,t.closedPRs),g=new Set([...m.map(b=>b.url),...f.map(b=>b.url)]),h=Hk(e.openPRs??[],t.openPRs??[]).filter(b=>!g.has(b.url));return{...e,...t,version:1,stateRevision:Math.max(e.stateRevision,t.stateRevision),preferences:d,preferencesUpdatedAt:p,tombstones:r,repoScores:O4(e.repoScores,t.repoScores),starredRepos:I4(e,t),starredReposLastFetched:ug(e.starredReposLastFetched,t.starredReposLastFetched),mergedPRs:m,closedPRs:f,openPRs:h,savedResults:i,skippedIssues:s,lastSearchAt:ug(e.lastSearchAt,t.lastSearchAt),lastRunAt:ug(e.lastRunAt,t.lastRunAt)??new Date().toISOString(),gistId:t.gistId??e.gistId,searchRotation:$4(e.searchRotation,t.searchRotation)}}function $4(e,t){let r=e??{languageOffset:0},n=t??{languageOffset:0},s=r.lastRotatedAt,o=n.lastRotatedAt;return s&&o?s>=o?r:n:s?r:o||n.languageOffset>=r.languageOffset?n:r}function O4(e,t){let r=Object.assign(Object.create(null),e);for(let[n,s]of Object.entries(t)){let o=r[n];if(!o)r[n]=s;else{let i=o.mergedPRCount+o.closedWithoutMergeCount,a=s.mergedPRCount+s.closedWithoutMergeCount;r[n]=a>=i?s:o}}return r}function I4(e,t){let r=e.starredReposLastFetched,n=t.starredReposLastFetched;return!r&&!n?t.starredRepos.length>=e.starredRepos.length?t.starredRepos:e.starredRepos:r?n&&n>=r?t.starredRepos:e.starredRepos:t.starredRepos}function Hk(e,t){let r=new Map;for(let n of e)r.set(n.url,n);for(let n of t)r.set(n.url,n);return[...r.values()]}function x4(e,t){let r=new Map;for(let n of e)r.set(n.issueUrl,n);for(let n of t){let s=r.get(n.issueUrl);(!s||n.lastSeenAt>s.lastSeenAt)&&r.set(n.issueUrl,n)}return[...r.values()]}function D4(e,t){let r=new Map;for(let n of e)r.set(n.url,n);for(let n of t){let s=r.get(n.url);(!s||n.skippedAt>s.skippedAt)&&r.set(n.url,n)}return[...r.values()]}function ug(e,t){return e?t?e>=t?e:t:e:t}var Ba,Wk,at,ZD,Bk,C4,P4,KD,lg,A4,XD=A(()=>{Ba=B(require("fs"),1),Wk=B(require("path"),1);Io();It();pt();ft();at="gist-state",ZD="oss-scout-state",Bk="state.json",C4="gist-id",P4="state-cache.json",KD=10;lg=class{octokit;gistId=null;constructor(t){this.octokit=t}async bootstrap(){try{return await this.bootstrapFromApi()}catch(t){if(Fe(t)===401)throw t;return H(at,`API bootstrap failed: ${Y(t)}`),this.bootstrapFromCache(E4(t))}}async push(t){if(!this.gistId)return H(at,"No gist ID \u2014 cannot push"),this.writeCache(t),!1;let r=t;try{let s=await this.fetchGistState(this.gistId);if(s.kind==="ok")r=gl(t,s.state);else if(s.kind==="invalid")return this.writeCache(t),H(at,"Remote gist content failed validation \u2014 not overwriting it. Changes saved locally; gist sync skipped."),!1}catch(s){Be(s),H(at,`Could not fetch gist before push, writing local snapshot: ${Y(s)}`)}this.writeCache(r);let n=JSON.stringify(r,null,2);if(n.length>9e5)return H(at,`State too large for gist (${Math.round(n.length/1024)}KB). Consider clearing old results with 'oss-scout results clear'.`),!1;try{return await this.octokit.gists.update({gist_id:this.gistId,files:{[Bk]:{content:n}}}),se(at,"State pushed to gist"),!0}catch(s){return Be(s),H(at,`Failed to push: ${Y(s)}`),!1}}getGistId(){return this.gistId}async bootstrapFromApi(){let t=this.readCachedGistId();if(t){se(at,`Trying cached gist ID: ${t}`);try{let o=await this.fetchGistState(t);if(o.kind==="ok"){this.gistId=t;let i=this.mergeCacheInto(o.state);return this.writeCache(i),{gistId:t,state:i,created:!1}}}catch(o){if(Fe(o)!==404)throw o;se(at,`Cached gist gone (404): ${Y(o)}`)}se(at,"Cached gist ID invalid, searching...")}let r=await this.searchForGist();if(r.id){se(at,`Found gist via search: ${r.id}`),this.saveGistId(r.id),this.gistId=r.id;let o=await this.fetchGistState(r.id);if(o.kind==="ok"){let i=this.mergeCacheInto(o.state);return this.writeCache(i),{gistId:r.id,state:i,created:!1}}return H(at,`Found existing gist ${r.id} but content failed validation. Using local cache to avoid data loss.`),this.bootstrapFromCache("unknown")}r.exhaustive||H(at,`Scanned the first ${KD*100} gists without finding an oss-scout state gist, but the account has more. Creating a new state gist; if one already exists, copy its id into the gist-id file in the oss-scout data directory to avoid a duplicate.`),se(at,"No existing gist found, creating new one");let n=xn.parse({version:1}),s=await this.createGist(n);return this.saveGistId(s),this.gistId=s,this.writeCache(n),{gistId:s,state:n,created:!0}}bootstrapFromCache(t){let r=this.readCache();if(r){se(at,"Bootstrapped from local cache (degraded mode)");let s=this.readCachedGistId();return s&&(this.gistId=s),{gistId:s??"",state:r,created:!1,degraded:!0,degradedReason:t}}return se(at,"No cache available, using fresh state (degraded mode)"),{gistId:"",state:xn.parse({version:1}),created:!1,degraded:!0,degradedReason:t}}async fetchGistState(t){let{data:r}=await this.octokit.gists.get({gist_id:t}),n=r.files?.[Bk];if(!n?.content)return{kind:"missing"};try{let s=JSON.parse(n.content);return{kind:"ok",state:dl(s)}}catch(s){return H(at,`Gist content failed validation: ${Y(s)}`),{kind:"invalid"}}}async searchForGist(){for(let t=1;t<=KD;t++){let{data:r}=await this.octokit.gists.list({per_page:100,page:t});if(r.length===0)return{id:null,exhaustive:!0};let n=r.find(s=>s.description===ZD);if(n)return{id:n.id,exhaustive:!0};if(r.length<100)return{id:null,exhaustive:!0}}return{id:null,exhaustive:!1}}async createGist(t){let{data:r}=await this.octokit.gists.create({description:ZD,public:!1,files:{[Bk]:{content:JSON.stringify(t,null,2)}}});return r.id}readCachedGistId(){try{return Ba.readFileSync(JD(),"utf-8").trim()||null}catch(t){return t?.code!=="ENOENT"&&H(at,`Failed to read cached gist ID: ${Y(t)}`),null}}saveGistId(t){Ba.writeFileSync(JD(),t+`
306
306
  `,{mode:384})}mergeCacheInto(t){let r=this.readCache();return r?gl(r,t):t}readCache(){try{let t=Ba.readFileSync(YD(),"utf-8");return dl(JSON.parse(t))}catch(t){return t?.code!=="ENOENT"&&H(at,`Failed to read state cache: ${Y(t)}`),null}}writeCache(t){try{Ba.writeFileSync(YD(),JSON.stringify(t,null,2)+`
307
- `,{mode:384})}catch(r){H(at,`Failed to write cache: ${Y(r)}`)}}},E4=2160*60*60*1e3});function tL(){return eL.join(Rs(),"state.json")}function pg(){let e=tL();try{let t=Mr.readFileSync(e,"utf-8");return dl(JSON.parse(t))}catch(t){if(t?.code==="ENOENT")return xn.parse({version:1});H(dg,`Failed to load state from ${e}: ${Y(t)}. Using defaults.`);try{let n=`${e}.corrupt.${Date.now()}`;Mr.copyFileSync(e,n),H(dg,`Corrupt state backed up to ${n}`)}catch(n){H(dg,`Failed to back up corrupt state: ${Y(n)}`)}return xn.parse({version:1})}}function rL(e){let t=tL(),r=`${t}.tmp.${process.pid}.${D4++}`,n=JSON.stringify(e,null,2)+`
308
- `;Mr.writeFileSync(r,n,{mode:384});try{Mr.renameSync(r,t)}catch(s){try{Mr.unlinkSync(r)}catch{}throw s}se(dg,"State saved")}var Mr,eL,dg,D4,nL=A(()=>{Mr=B(require("fs"),1),eL=B(require("path"),1);Io();It();pt();ft();dg="local-state";D4=0});function L4(e){let t="Changes will only be saved locally.";switch(e){case"rate_limit":return`Gist sync unavailable \u2014 GitHub API rate limit exceeded. ${t} Try again after the rate limit resets.`;case"network":return`Gist sync unavailable \u2014 could not reach GitHub. ${t} Check your network connection.`;case"server":return`Gist sync unavailable \u2014 GitHub returned a server error. ${t} Try again later.`;case"unknown":case void 0:return`Gist sync unavailable \u2014 running in offline mode. ${t}`}}function M4(e){return{gists:{async get(t){let{data:r}=await e.gists.get(t);if(!r.id)throw new Error("Gist get returned no id");let n=r.files?Object.fromEntries(Object.entries(r.files).map(([s,o])=>[s,o?{content:o.content}:void 0])):null;return{data:{id:r.id,files:n}}},async create(t){let{data:r}=await e.gists.create(t);if(!r.id)throw new Error("Gist create returned no id");return{data:{id:r.id}}},async update(t){let{data:r}=await e.gists.update(t);if(!r.id)throw new Error("Gist update returned no id");return{data:{id:r.id}}},async list(t){let{data:r}=await e.gists.list(t);return{data:r.filter(n=>n.id).map(n=>({id:n.id,description:n.description??null}))}}}}}async function mg(e){e.logLevel!==void 0&&jf(e.logLevel);let t,r=null,n=!1;if(e.persistence==="provided")t=e.initialState;else if(e.persistence==="gist"){r=new lg(M4(In(e.githubToken)));let s=await r.bootstrap();s.degraded&&H("scout",L4(s.degradedReason));let o=pg();t=gl(o,s.state),e.gistId?t.gistId=e.gistId:s.gistId&&(t.gistId=s.gistId)}else t=pg(),n=!0;return new hl(e.githubToken,t,r,{persistLocal:n})}var hl,sL=A(()=>{Ik();tg();zk();Io();XD();Zf();nL();pt();It();ft();Dn();hl=class{githubToken;gistStore;state;dirty=!1;persistLocal;constructor(t,r,n=null,s={}){this.githubToken=t,this.gistStore=n,this.state=r,this.persistLocal=s.persistLocal??!1}evictStaleCacheEntries(){gt().evictStale()}async search(t){this.evictStaleCacheEntries(),this.cullExpiredSkips();let r=new Set((this.state.skippedIssues??[]).map(w=>w.url));if(t?.excludeRecentlySurfaced??!0){let w=t?.recentlySurfacedTtlDays??7,y=Date.now()-w*24*60*60*1e3;for(let S of this.state.savedResults??[]){let k=Date.parse(S.lastSeenAt);!Number.isNaN(k)&&k>=y&&r.add(S.issueUrl)}}let n=new xo(this.githubToken,this.state.preferences,this),s=this.state.preferences,o=s.preferLanguages??[],i=s.preferRepos??[],a=t?.preferLanguages??(o.length>0?o:void 0),c=t?.preferRepos??(i.length>0?i:void 0),u=s.avoidRepos??[],d=s.boostIssueTypes??[],p=t?.avoidRepos??(u.length>0?u:void 0),m=t?.boostIssueTypes??(d.length>0?d:void 0),f=t?.diversityRatio??s.diversityRatio??0,g=this.state.searchRotation??{languageOffset:0},h,b;try{({candidates:h,strategiesUsed:b}=await n.searchIssues({maxResults:t?.maxResults,strategies:t?.strategies,skippedUrls:r,preferLanguages:a,preferRepos:c,avoidRepos:p,boostIssueTypes:m,diversityRatio:f,interPhaseDelayMs:t?.interPhaseDelayMs,broadPhaseDelayMs:t?.broadPhaseDelayMs,languageRotationOffset:g.languageOffset,repoRotationOffsets:{merged:g.phase0Offset??0,starred:g.starredOffset??0,maintained:g.maintainedOffset??0},strategyRotationOffset:t?.full?void 0:g.strategyOffset??0}))}catch(w){throw w instanceof ot&&this.advanceRotation(g,w.strategiesUsed??[],t?.full),w}this.advanceRotation(g,b,t?.full);for(let w of h)this.updateRepoSignalsFromHealth(w.projectHealth);return this.state.lastSearchAt=new Date().toISOString(),this.dirty=!0,{candidates:h,excludedRepos:this.state.preferences.excludeRepos,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,rateLimitWarning:n.rateLimitWarning??void 0,strategiesUsed:b}}advanceRotation(t,r,n=!1){let s=o=>r.includes(o)?1:0;r.length!==0&&(this.state.searchRotation={...t,languageOffset:t.languageOffset+s("broad"),phase0Offset:(t.phase0Offset??0)+s("merged"),starredOffset:(t.starredOffset??0)+s("starred"),maintainedOffset:(t.maintainedOffset??0)+s("maintained"),strategyOffset:n?t.strategyOffset:Oo.indexOf(r[0])+1,lastRotatedAt:new Date().toISOString()},this.dirty=!0)}updateRepoSignalsFromHealth(t){t.checkFailed||this.updateRepoScore(t.repo,{signals:{hasActiveMaintainers:t.isActive}})}async vetIssue(t){return new xo(this.githubToken,this.state.preferences,this).vetIssue(t)}async features(t){this.evictStaleCacheEntries();let r=t?.count??10,n=In(this.githubToken),s=new Ss(n,this),o=t?.broad?await qD({octokit:n,vetter:s,count:r,languages:this.state.preferences.languages,excludeRepos:this.state.preferences.excludeRepos,excludeOrgs:this.state.preferences.excludeOrgs,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,splitRatio:t?.splitRatio??this.state.preferences.featuresSplitRatio}):await cg({octokit:n,vetter:s,repoScores:this.state.repoScores??{},count:r,excludeRepos:this.state.preferences.excludeRepos,excludeOrgs:this.state.preferences.excludeOrgs,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,anchorThreshold:t?.anchorThreshold??this.state.preferences.featuresAnchorThreshold,splitRatio:t?.splitRatio??this.state.preferences.featuresSplitRatio});return this.saveResults([...o.quickWins,...o.biggerBets]),this.state.lastSearchAt=new Date().toISOString(),this.dirty=!0,o}async vetList(t){this.evictStaleCacheEntries();let r=this.getSavedResults(),n=t?.concurrency??5,s=[],o=new Map,i=null;for(let m of r){if(i)break;let f=this.vetIssue(m.issueUrl).then(g=>{s.push({issueUrl:m.issueUrl,repo:m.repo,number:m.number,title:m.title,status:this.classifyVetResult(g),ok:!0,recommendation:g.recommendation,viabilityScore:g.viabilityScore})}).catch(g=>{if(Me(g)===401||mt(g)){i??=g;return}let h=Me(g),b=h===404||h===410;s.push({issueUrl:m.issueUrl,repo:m.repo,number:m.number,title:m.title,status:b?"closed":"error",ok:!1,errorMessage:Y(g)})}).finally(()=>{o.delete(m.issueUrl)});o.set(m.issueUrl,f),o.size>=n&&await Promise.race(o.values())}if(await Promise.allSettled(o.values()),i)throw s.length>0&&H("scout",`vetList aborted mid-batch after ${s.length} result(s) \u2014 discarding partial results due to auth/rate-limit failure`),i;let a={total:s.length,stillAvailable:s.filter(m=>m.status==="still_available").length,claimed:s.filter(m=>m.status==="claimed").length,closed:s.filter(m=>m.status==="closed").length,hasPR:s.filter(m=>m.status==="has_pr").length,errors:s.filter(m=>m.status==="error").length},c=new Map((this.state.savedResults??[]).map(m=>[m.issueUrl,m.lastStatus])),u=s.filter(m=>m.status!=="error").filter(m=>{let f=c.get(m.issueUrl);return f!==void 0&&f!==m.status}).map(m=>({issueUrl:m.issueUrl,repo:m.repo,number:m.number,from:c.get(m.issueUrl),to:m.status})),d=new Map(s.map(m=>[m.issueUrl,m.status]));for(let m of this.state.savedResults??[]){let f=d.get(m.issueUrl);f!==void 0&&f!=="error"&&(m.lastStatus=f)}s.length>0&&(this.dirty=!0);let p;if(t?.prune){let m=new Set(s.filter(g=>g.status!=="still_available").map(g=>g.issueUrl)),f=(this.state.savedResults??[]).length;this.state.savedResults=(this.state.savedResults??[]).filter(g=>!m.has(g.issueUrl)),p=f-(this.state.savedResults?.length??0),p>0&&this.addTombstones([...m]),this.dirty=!0}return{results:s,summary:a,prunedCount:p,transitions:u}}classifyVetResult(t){if(t.issueState==="closed")return"closed";let r=t.vettingResult.checks;return r.noExistingPR?r.notClaimed?"still_available":"claimed":"has_pr"}getReposWithMergedPRs(){let t=new Map;for(let r of this.state.mergedPRs??[]){let n=it(r.url);n&&t.set(n,(t.get(n)??0)+1)}return[...t.entries()].sort((r,n)=>n[1]-r[1]).map(([r])=>r)}getReposWithOpenPRs(){let t=new Map;for(let r of this.state.openPRs??[]){let n=it(r.url);n&&t.set(n,(t.get(n)??0)+1)}return[...t.entries()].sort((r,n)=>n[1]-r[1]).map(([r])=>r)}getStarredRepos(){return this.state.starredRepos}getProjectCategories(){return this.state.preferences.projectCategories}getGitHubUsername(){return this.state.preferences.githubUsername}getRepoScore(t){let r=this.state.repoScores[t];return r?r.score:null}getClosedWithoutMergeCount(t){let r=this.state.repoScores[t];return r?r.closedWithoutMergeCount:(this.state.closedPRs??[]).filter(n=>it(n.url)===t).length}getSLMTriageConfig(){let t=this.state.preferences.slmTriageModel??"";return t?{model:t,host:this.state.preferences.slmTriageHost??""}:null}getPreferences(){return this.state.preferences}getRepoScoreRecord(t){return this.state.repoScores[t]}recordMergedPR(t){let r=this.state.mergedPRs??[];r.some(n=>n.url===t.url)||(this.state.mergedPRs=[...r,{url:t.url,title:t.title,mergedAt:t.mergedAt}],this.updateRepoScoreFromPRs(t.repo),this.dirty=!0)}recordClosedPR(t){let r=this.state.closedPRs??[];r.some(n=>n.url===t.url)||(this.state.closedPRs=[...r,{url:t.url,title:t.title,closedAt:t.closedAt}],this.updateRepoScoreFromPRs(t.repo),this.dirty=!0)}recordOpenPR(t){let r=this.state.openPRs??[];r.some(n=>n.url===t.url)||(this.state.openPRs=[...r,{url:t.url,title:t.title,openedAt:t.openedAt}],this.dirty=!0)}async syncOpenPRs(){let t=In(this.githubToken),r=this.state.openPRs??[],n={checked:r.length,merged:0,closed:0,stillOpen:0,errors:0},s=[];for(let o of r){let i=Ao(o.url);if(!i||i.type!=="pull"){s.push(o),n.errors++;continue}let a=`${i.owner}/${i.repo}`;try{let{data:c}=await t.pulls.get({owner:i.owner,repo:i.repo,pull_number:i.number});c.merged?(this.recordMergedPR({url:o.url,title:o.title,mergedAt:c.merged_at??new Date().toISOString(),repo:a}),n.merged++):c.state==="closed"?(this.recordClosedPR({url:o.url,title:o.title,closedAt:c.closed_at??new Date().toISOString(),repo:a}),n.closed++):(s.push(o),n.stillOpen++)}catch(c){Be(c),H("scout",`sync: could not check ${o.url}: ${Y(c)}`),s.push(o),n.errors++}}return this.state.openPRs=s,this.dirty=!0,await this.checkpoint(),n}updateRepoScore(t,r){let s=this.state.repoScores[t]??{repo:t,score:5,mergedPRCount:0,closedWithoutMergeCount:0,avgResponseDays:null,lastEvaluatedAt:new Date().toISOString(),signals:{hasActiveMaintainers:!1,isResponsive:!1,hasHostileComments:!1}},o={...s,...r,repo:t,lastEvaluatedAt:new Date().toISOString(),signals:{...s.signals,...r.signals??{}}};o.score=this.calculateScore(o),this.state.repoScores[t]=o,this.dirty=!0}updatePreferences(t){this.state.preferences={...this.state.preferences,...t},this.state.preferencesUpdatedAt=new Date().toISOString(),this.dirty=!0}setStarredRepos(t){this.state.starredRepos=t,this.state.starredReposLastFetched=new Date().toISOString(),this.dirty=!0}saveResults(t){let r=new Date().toISOString(),n=new Map((this.state.savedResults??[]).map(s=>[s.issueUrl,s]));for(let s of t){if(s.recommendation==="skip"){n.delete(s.issue.url);let i=new Set(["Issue is closed","Linked PR already merged"]),a=s.reasonsToSkip.some(c=>i.has(c));this.skipIssue(s.issue.url,{repo:s.issue.repo,number:s.issue.number,title:s.issue.title,reason:s.reasonsToSkip.join("; ")||"vetter: skip",permanent:a});continue}let o=n.get(s.issue.url);n.set(s.issue.url,{issueUrl:s.issue.url,repo:s.issue.repo,number:s.issue.number,title:s.issue.title,labels:s.issue.labels,recommendation:s.recommendation,viabilityScore:s.viabilityScore,searchPriority:s.searchPriority,firstSeenAt:o?.firstSeenAt??r,lastSeenAt:r,lastScore:s.viabilityScore,horizon:"horizon"in s?s.horizon:void 0})}this.state.savedResults=[...n.values()],this.dirty=!0}getSavedResults(){return this.state.savedResults??[]}clearResults(){this.addTombstones((this.state.savedResults??[]).map(t=>t.issueUrl)),this.state.savedResults=[],this.dirty=!0}addTombstones(t){if(t.length===0)return;let r=new Date().toISOString(),n=this.state.tombstones??[],s=new Map(n.map(o=>[o.url,o]));for(let o of t)s.set(o,{url:o,removedAt:r});this.state.tombstones=[...s.values()]}skipIssue(t,r){let n=this.state.skippedIssues??[],s=n.find(i=>i.url===t);if(s){r?.permanent===!0&&s.permanent!==!0&&(s.permanent=!0,s.skippedAt=new Date().toISOString(),this.dirty=!0);return}let o=r?.permanent??!0;this.state.skippedIssues=[...n,{url:t,repo:r?.repo??"",number:r?.number??0,title:r?.title??"",skippedAt:new Date().toISOString(),permanent:o,...r?.reason?{reason:r.reason}:{}}],this.state.savedResults&&(this.state.savedResults=this.state.savedResults.filter(i=>i.issueUrl!==t)),this.dirty=!0}getSkippedIssues(){return this.state.skippedIssues??[]}unskipIssue(t){let r=(this.state.skippedIssues??[]).length;this.state.skippedIssues=(this.state.skippedIssues??[]).filter(n=>n.url!==t),this.state.skippedIssues.length<r&&this.addTombstones([t]),this.dirty=!0}clearSkippedIssues(){this.addTombstones((this.state.skippedIssues??[]).map(t=>t.url)),this.state.skippedIssues=[],this.dirty=!0}cullExpiredSkips(t=90){let r=new Date;r.setDate(r.getDate()-t);let n=[];return this.state.skippedIssues=(this.state.skippedIssues??[]).filter(s=>{if(s.permanent!==!1)return!0;let o=new Date(s.skippedAt);return isNaN(o.getTime())||o>=r?!0:(n.push(s.url),!1)}),n.length>0&&(this.addTombstones(n),this.dirty=!0),n.length}isDirty(){return this.dirty}async checkpoint(){if(!this.dirty)return!0;if(this.state.lastRunAt=new Date().toISOString(),this.gistStore&&!await this.gistStore.push(this.state))return!1;if(this.persistLocal)try{this.state=gl(this.state,pg()),rL(this.state)}catch{return!1}return this.dirty=!1,!0}getState(){return this.state}updateRepoScoreFromPRs(t){let r=(this.state.mergedPRs??[]).filter(s=>it(s.url)===t).length,n=(this.state.closedPRs??[]).filter(s=>it(s.url)===t).length;this.updateRepoScore(t,{mergedPRCount:r,closedWithoutMergeCount:n,lastMergedAt:r>0?(this.state.mergedPRs??[]).filter(s=>it(s.url)===t).sort((s,o)=>o.mergedAt.localeCompare(s.mergedAt))[0]?.mergedAt:void 0})}calculateScore(t){let r=5;return r+=Math.min(t.mergedPRCount,3),r-=Math.min(t.closedWithoutMergeCount,3),t.signals.hasActiveMaintainers&&(r+=1),t.signals.hasHostileComments&&(r-=2),Math.max(1,Math.min(10,r))}}});function oL(){let e=bl.filter(r=>!(r in yl));if(e.length>0)throw new Error(`FIELD_CONFIGS is missing entries for preference keys: ${e.join(", ")}`);let t=Object.keys(yl).filter(r=>!bl.includes(r));if(t.length>0)throw new Error(`FIELD_CONFIGS has entries for unknown preference keys: ${t.join(", ")}`)}function F4(e){let t=e.toLowerCase();if(t==="true"||t==="yes")return!0;if(t==="false"||t==="no")return!1;throw new ot(`Invalid boolean value: "${e}". Use true/false or yes/no.`)}function N4(e,t){let r=parseInt(e,10);if(isNaN(r))throw new ot(`Invalid number for "${t}": "${e}"`);return r}function G4(e,t){let r=Number.parseFloat(e);if(isNaN(r))throw new ot(`Invalid number for "${t}": "${e}"`);return r}function Vk(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function fg(e,t){if(t.startsWith("+")){let r=Vk(t.slice(1)),n=[...e];for(let s of r)n.includes(s)||n.push(s);return n}if(t.startsWith("-")){let r=new Set(Vk(t.slice(1)));return e.filter(n=>!r.has(n))}return Vk(t)}function iL(e,t,r){let n=yl[t];if(!n)throw new ot(`Unknown config key: "${t}". Valid keys: ${qk.join(", ")}`);let s={...e};switch(n.type){case"string":t==="slmTriageHost"&&SD(r),s[t]=r;break;case"boolean":s[t]=F4(r);break;case"number":s[t]=N4(r,t);break;case"float":s[t]=G4(r,t);break;case"array":{let o=s[t]??[];s[t]=fg(o,r);break}case"enum":{let o=n.validValues;if(!o.includes(r))throw new ot(`Invalid value for "${t}": "${r}". Valid: ${o.join(", ")}`);s[t]=r;break}case"enum-array":{let o=s[t]??[],i=fg(o,r),a=n.validValues,c=i.filter(u=>!a.includes(u));if(c.length>0)throw new ot(`Invalid value(s) for "${t}": ${c.join(", ")}. Valid: ${a.join(", ")}`);t==="scope"?s[t]=i.length>0?i:void 0:s[t]=i;break}}return To.parse(s)}var yl,bl,qk,aL=A(()=>{Io();ft();kk();yl={githubUsername:{type:"string"},languages:{type:"array"},labels:{type:"array"},scope:{type:"enum-array",validValues:ll.options},excludeRepos:{type:"array"},excludeOrgs:{type:"array"},preferredOrgs:{type:"array"},aiPolicyBlocklist:{type:"array"},projectCategories:{type:"enum-array",validValues:ul.options},minStars:{type:"number"},maxIssueAgeDays:{type:"number"},includeDocIssues:{type:"boolean"},minRepoScoreThreshold:{type:"number"},interPhaseDelayMs:{type:"number"},persistence:{type:"enum",validValues:uk.options},defaultStrategy:{type:"enum-array",validValues:$o.options},broadPhaseDelayMs:{type:"number"},skipBroadWhenSufficientResults:{type:"number"},preferLanguages:{type:"array"},preferRepos:{type:"array"},diversityRatio:{type:"float"},avoidRepos:{type:"array"},boostIssueTypes:{type:"array"},slmTriageModel:{type:"string"},slmTriageHost:{type:"string"},featuresAnchorThreshold:{type:"number"},featuresSplitRatio:{type:"float"}},bl=Object.keys(To.shape),qk=[...bl].sort()});async function cL(e,t,r=fr()){let n=e.getPreferences().githubUsername;if(!n)throw new Da("GitHub username not configured. Run `oss-scout setup` first.");let s=await qf(t);if(se(nn,`Rate limit: ${s.remaining}/${s.limit}, resets at ${s.resetAt}`),s.remaining<15)return se(nn,"Insufficient rate limit, skipping bootstrap"),{starredRepoCount:0,mergedPRCount:0,closedPRCount:0,openPRCount:0,reposScoredCount:0,skippedDueToRateLimit:!0,errors:[]};let o=In(t),i=[],a=[],c=0,u=new Set;try{let f=0;for await(let g of o.paginate.iterator(o.activity.listReposStarredByAuthenticatedUser,{per_page:Do,headers:{accept:"application/vnd.github.v3+json"}})){for(let h of g.data){let b=h;a.push(b.full_name)}if(f++,f>=U4)break}se(nn,`Fetched ${a.length} starred repos`),e.setStarredRepos(a),c=a.length}catch(f){Be(f),H(nn,`Failed to fetch starred repos: ${Y(f)}`),i.push("starred repos fetch failed")}let d=0;try{for(let f=1;f<=Zk;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:merged author:${n}`,per_page:Do,page:f})).data}finally{r.recordCall()}for(let h of g.items){let b=it(h.html_url);b&&(e.recordMergedPR({url:h.html_url,title:h.title,mergedAt:h.closed_at??new Date().toISOString(),repo:b}),u.add(b),d++)}if(g.items.length<Do)break}se(nn,`Imported ${d} merged PRs`)}catch(f){Be(f),H(nn,`Failed to fetch merged PRs: ${Y(f)}`),i.push("merged PR fetch failed")}let p=0;try{for(let f=1;f<=Zk;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:closed is:unmerged author:${n}`,per_page:Do,page:f})).data}finally{r.recordCall()}for(let h of g.items){let b=it(h.html_url);b&&(e.recordClosedPR({url:h.html_url,title:h.title,closedAt:h.closed_at??new Date().toISOString(),repo:b}),u.add(b),p++)}if(g.items.length<Do)break}se(nn,`Imported ${p} closed PRs`)}catch(f){Be(f),H(nn,`Failed to fetch closed PRs: ${Y(f)}`),i.push("closed PR fetch failed")}let m=0;try{for(let f=1;f<=Zk;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:open author:${n}`,per_page:Do,page:f})).data}finally{r.recordCall()}for(let h of g.items){let b=it(h.html_url);b&&(e.recordOpenPR({url:h.html_url,title:h.title,openedAt:h.created_at??new Date().toISOString(),repo:b}),m++)}if(g.items.length<Do)break}se(nn,`Imported ${m} open PRs`)}catch(f){Be(f),H(nn,`Failed to fetch open PRs: ${Y(f)}`),i.push("open PR fetch failed")}return{starredRepoCount:c,mergedPRCount:d,closedPRCount:p,openPRCount:m,reposScoredCount:u.size,skippedDueToRateLimit:!1,errors:i}}var nn,U4,Zk,Do,uL=A(()=>{Zf();pt();ft();It();Fa();nn="bootstrap",U4=5,Zk=3,Do=100});function dL(e,t=new Date,r=30){if(!e||e.state!=="open"||!e.updatedAt)return!1;let n=new Date(e.updatedAt);return Number.isNaN(n.getTime())?!1:(t.getTime()-n.getTime())/(1e3*60*60*24)>=r}var lL,pL=A(()=>{lL=30});function gL(e,t,r){if(!t.test(e))throw new ot(`Invalid ${r} URL: ${e}. Expected format: https://github.com/owner/repo/issues/123`)}function hL(e){if(e.length>mL)throw new ot(`URL exceeds maximum length of ${mL} characters`);return e}var fL,mL,yL=A(()=>{ft();fL=/^https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+$/,mL=2048});var bL={};re(bL,{ANCHOR_THRESHOLD:()=>Fk,ANTI_LLM_KEYWORDS:()=>bk,FEATURE_LABELS:()=>ag,FIELD_CONFIGS:()=>yl,HorizonSchema:()=>ck,ISSUE_URL_PATTERN:()=>fL,IssueDiscovery:()=>xo,IssueScopeSchema:()=>ll,IssueVetter:()=>Ss,NO_ANCHORS_MESSAGE:()=>Uk,NO_RESULTS_MESSAGE:()=>jk,OssScout:()=>hl,PREFERENCE_KEYS:()=>bl,ProjectCategorySchema:()=>ul,RepoScoreSchema:()=>ik,SORTED_PREFERENCE_KEYS:()=>qk,STALLED_PR_THRESHOLD_DAYS:()=>lL,ScoutPreferencesSchema:()=>To,ScoutStateSchema:()=>xn,SearchStrategySchema:()=>$o,SkippedIssueSchema:()=>ak,applyPreferenceField:()=>iL,assertFieldConfigsCover:()=>oL,bootstrapScout:()=>cL,classifyHorizon:()=>Gk,createScout:()=>mg,discoverFeatures:()=>cg,enableDebug:()=>D0,fetchRoadmapIssueRefs:()=>og,getGitHubToken:()=>Qv,getLogLevel:()=>x0,isLinkedPRStalled:()=>dL,parseRoadmapIssueRefs:()=>Dk,requireGitHubToken:()=>j0,resolveAnchorRepos:()=>Nk,scanForAntiLLMPolicy:()=>wk,setLogLevel:()=>jf,splitByHorizon:()=>ig,updateArray:()=>fg,validateGitHubUrl:()=>gL,validateUrl:()=>hL});var gg=A(()=>{sL();Io();aL();It();Ik();tg();Rk();uL();pt();zk();pL();Lk();yL()});function B4(e){let t=[],r=e.split(/\r?\n/);for(let n=0;n<r.length;n++){let s=n+1,o=r[n].trim();if(o===""||o.startsWith("#"))continue;let i=o.match(/^(\S+)\s+(\S+)(?:\s+#.*)?$/);if(!i){v("skip-file-parser",`Line ${s}: malformed (expected "<date> <url>"): ${o}`);continue}let[,a,c]=i;if(!j4.test(a)){v("skip-file-parser",`Line ${s}: invalid date format (expected YYYY-MM-DD): ${o}`);continue}let u=Date.parse(`${a}T00:00:00.000Z`);if(Number.isNaN(u)){v("skip-file-parser",`Line ${s}: unparseable date: ${o}`);continue}let d=new Date(u).toISOString().slice(0,10);if(d!==a){v("skip-file-parser",`Line ${s}: invalid calendar date ${a} (would be normalized to ${d}): ${o}`);continue}let p=c.match(z4);if(!p){v("skip-file-parser",`Line ${s}: non-GitHub-issue URL: ${o}`);continue}let[,m,f]=p,g=Number.parseInt(f,10);t.push({url:c,repo:m,number:g,title:"",skippedAt:new Date(u).toISOString(),permanent:!0})}return t}function Kk(e){if(!e)return{issues:[]};let t=wL.resolve(e);if(!hg.existsSync(t))return v("skip-file-parser",`Configured skipped-issues file not found at ${t} (cwd ${process.cwd()}); proceeding with an EMPTY skip list \u2014 previously skipped issues may resurface. Use an absolute skippedIssuesPath, or run from the directory that contains "${e}".`),{issues:[],notFound:!0,resolvedPath:t};let r;try{r=hg.readFileSync(t,"utf8")}catch(n){return v("skip-file-parser",`Failed to read skipped-issues file at ${t}: ${I(n)}`),{issues:[],readError:I(n),resolvedPath:t}}return{issues:B4(r),resolvedPath:t}}function RL(e){return Kk(e).issues}var hg,wL,j4,z4,Jk=A(()=>{"use strict";hg=B(require("node:fs"),1),wL=B(require("node:path"),1);ce();ee();j4=/^\d{4}-\d{2}-\d{2}$/,z4=/^https:\/\/github\.com\/([^/]+\/[^/]+)\/(?:issues|pull)\/(\d+)(?:[#/?].*)?$/});function Lo(e){if(!e)return null;let t={author:{login:e.author},state:e.merged?"merged":e.state};return e.updatedAt!==void 0&&(t.updatedAt=e.updatedAt),t}function _s(e){if(!e)return;let t=Lo(e);if(!t)return;let r={number:e.number,state:t.state,url:e.url,isStalled:Qm(t)};return e.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}function H4(e){let t=L().getState(),{config:r}=t,n=Kk(r.skippedIssuesPath);(n.readError!==void 0||n.notFound)&&e&&(e.skipListUnavailable=!0);let s=[...n.issues],o=new Set(s.map(d=>d.url));for(let[d,p]of Object.entries(r.dismissedIssues??{})){if(o.has(d)||!dr.test(d))continue;let m=q(d);o.add(d),s.push({url:d,repo:m?`${m.owner}/${m.repo}`:"",number:m?.number??0,title:"",skippedAt:p,reason:"dismissed",permanent:!0})}let i=cr(t.workClaims??[]);for(let d of i){if(d.kind!=="implementation"||o.has(d.url)||!dr.test(d.url))continue;let p=q(d.url);o.add(d.url),s.push({url:d.url,repo:p?`${p.owner}/${p.repo}`:"",number:p?.number??0,title:"",skippedAt:d.startedAt,reason:`implementation in progress (session ${d.session})`,permanent:!0})}let a=gs(t),c=Nf(t),u=new Set(c.map(d=>d.toLowerCase()));return{version:1,stateRevision:1,preferences:{githubUsername:r.githubUsername,languages:r.languages,labels:r.labels,scope:r.scope,excludeRepos:[...r.excludeRepos,...c],excludeOrgs:r.excludeOrgs??[],preferredOrgs:r.preferredOrgs??[],aiPolicyBlocklist:r.aiPolicyBlocklist,projectCategories:r.projectCategories??[],minStars:r.minStars,maxIssueAgeDays:r.maxIssueAgeDays,includeDocIssues:r.includeDocIssues,minRepoScoreThreshold:r.minRepoScoreThreshold,interPhaseDelayMs:0,broadPhaseDelayMs:0,skipBroadWhenSufficientResults:r.skipBroadWhenSufficientResults,persistence:r.persistence,slmTriageModel:r.slmTriageModel,slmTriageHost:r.slmTriageHost,featuresAnchorThreshold:3,featuresSplitRatio:.6,preferLanguages:a?.recommendations.languages??[],preferRepos:(a?.recommendations.repos??[]).filter(d=>!u.has(d.toLowerCase())),diversityRatio:wl,avoidRepos:r.avoidRepos??[],boostIssueTypes:r.boostIssueTypes??[]},repoScores:t.repoScores,tombstones:[],starredRepos:r.starredRepos,starredReposLastFetched:r.starredReposLastFetched,mergedPRs:(t.mergedPRs??[]).map(d=>({url:d.url,title:d.title,mergedAt:d.mergedAt})),closedPRs:(t.closedPRs??[]).map(d=>({url:d.url,title:d.title,closedAt:d.closedAt})),openPRs:(t.lastDigest?.openPRs??[]).map(d=>({url:d.url,title:d.title,openedAt:d.createdAt})),savedResults:(t.searchSeen??[]).map(d=>({issueUrl:d.url,repo:"",number:0,title:"",labels:[],recommendation:"skip",viabilityScore:0,searchPriority:"normal",firstSeenAt:d.lastSeenAt,lastSeenAt:d.lastSeenAt,lastScore:0})),skippedIssues:s,lastRunAt:t.lastRunAt,searchRotation:t.searchRotation??PS.parse({})}}async function vs(e){let t=ke();return mg({githubToken:t,persistence:"provided",initialState:H4(e)})}var wl,Ha=A(()=>{"use strict";xa();gg();le();gn();Ju();Jk();Ot();wl=.2});function ks(e,t){return e==="approve"&&t.score<4?"needs_review":e}function W4(e){return e.reduce((t,r)=>r.score<t.score?r:t)}function V4(e){let t=Mo.indexOf(e);return t===-1?Mo[Mo.length-1]:Mo[Math.min(t+1,Mo.length-1)]}function Mn(e,t,r){return typeof e!="number"||!Number.isFinite(e)||e<t||e>r?null:e}function q4(e){return e<3?{score:10,detail:`~${Math.round(e)}-day avg response`}:e<14?{score:7,detail:`${Math.round(e)}-day avg response`}:e<=60?{score:4,detail:`${Math.round(e)}-day avg response`}:{score:1,detail:"unresponsive maintainers"}}function Z4(e){let t=Math.round(e*100);return e>.7?{score:10,detail:`merges ${t}% of PRs`}:e>=.4?{score:7,detail:`merges ${t}% of PRs`}:e>=.1?{score:4,detail:`merges ${t}% of PRs`}:{score:1,detail:`merges ${t}% of PRs`}}function K4(e){return e<7?{score:10,detail:"commits in last week"}:e<30?{score:7,detail:"commits in last month"}:e<90?{score:4,detail:"commits in last 90 days"}:{score:1,detail:`no commits in ${e}+ days`}}function J4(e){let{projectHealth:t,repoScore:r}=e,n=!t.checkFailed,s=Mn(r?.avgResponseDays,0,Number.MAX_SAFE_INTEGER)??(n?Mn(t.avgIssueResponseDays,.001,Number.MAX_SAFE_INTEGER):null),o=n?Mn(t.daysSinceLastCommit,0,Number.MAX_SAFE_INTEGER):null,i=n?Mn(t.recentMergeRate,0,1):null;if(i===null&&r){let a=Mn(r.mergedPRCount,0,Number.MAX_SAFE_INTEGER),c=Mn(r.closedWithoutMergeCount,0,Number.MAX_SAFE_INTEGER);if(a!==null&&c!==null){let u=a+c;i=u===0?null:a/u}}return{avgResponseDays:s,mergeRate:i,daysSinceLastCommit:o}}function Cs(e){let t=e.getRepoScore(e.repo),r=e.projectHealth,n=r.checkFailed?{avgIssueResponseDays:null,daysSinceLastCommit:null,checkFailed:!0}:{avgIssueResponseDays:r.avgIssueResponseDays,daysSinceLastCommit:r.daysSinceLastCommit,recentMergeRate:r.recentMergeRate??null,checkFailed:!1};return Yk(J4({projectHealth:n,repoScore:t?{mergedPRCount:t.mergedPRCount,closedWithoutMergeCount:t.closedWithoutMergeCount,avgResponseDays:t.avgResponseDays}:null}))}function Yk(e){let t=[],r=[],n=Mn(e.avgResponseDays,0,Number.MAX_SAFE_INTEGER);n===null?r.push("maintainer responsiveness"):t.push(q4(n));let s=Mn(e.mergeRate,0,1);s===null?r.push("merge rate"):t.push(Z4(s));let o=Mn(e.daysSinceLastCommit,0,Number.MAX_SAFE_INTEGER);if(o===null?r.push("activity"):t.push(K4(o)),t.length===0)return{score:Mo[Mo.length-1],reason:`unknown ${r.join(", ")}`};let i=W4(t),a=r.length>0?V4(i.score):i.score,c=[i.detail];return r.length>0&&c.push(`unknown ${r.join(", ")}`),{score:a,reason:c.join(", ")}}var Mo,Rl=A(()=>{"use strict";Mo=[10,7,4,1]});async function X4(e){let t=[],r=0;for await(let n of e.paginate.iterator(e.activity.listReposStarredByAuthenticatedUser,{per_page:Y4,headers:{accept:"application/vnd.github.v3+json"}})){for(let s of n.data)s.full_name&&t.push(s.full_name);if(r+=1,r>=Q4)break}return t}async function SL(e){if(!e.isStarredReposStale())return e.getStarredRepos().length;let t=ke(),r;try{r=await X4(be(t))}catch(n){return v(Qk,`Failed to refresh starred repos; continuing with cached list (${e.getStarredRepos().length}): ${n instanceof Error?n.message:String(n)}`),e.getStarredRepos().length}return r.length===0?(O(Qk,"Starred-repo fetch returned 0; keeping existing cache"),e.getStarredRepos().length):(e.setStarredRepos(r),O(Qk,`Refreshed starred repos from GitHub: ${r.length} cached`),r.length)}var Qk,Y4,Q4,_L=A(()=>{"use strict";so();Lm();ce();Qk="starred-repos",Y4=100,Q4=5});var CL={};re(CL,{DEFAULT_SEARCH_RESULTS:()=>tK,MAX_SEARCH_RESULTS:()=>eK,SEARCH_DIVERSITY_RATIO:()=>wl,SEARCH_SEEN_RETENTION_DAYS:()=>uu,parseSearchStrategies:()=>rK,recordSearchSeen:()=>kL,runSearch:()=>sK});function rK(e){if(e===void 0)return;let t=e.split(",").map(n=>n.trim()).filter(Boolean);if(t.length===0)return;let r=[];for(let n of t){let s=$o.safeParse(n);if(!s.success)throw new Error(`Unknown search strategy "${n}". Valid strategies: merged, orgs, starred, broad, maintained, all`);r.push(s.data)}return r}function nK(e){return typeof e!="number"||!Number.isFinite(e)||e<0||e>100?(v(Wa,`Ignoring out-of-contract viabilityScore from scout: ${JSON.stringify(e)}`),0):e}function vL(e){let t=process.env[e];if(t===void 0||t==="")return;let r=Number(t);if(!Number.isInteger(r)||r<0){v(Wa,`Ignoring invalid ${e}="${t}" (expected a non-negative integer); using scout's default delay`);return}return r}function kL(e,t){let r=Date.now(),n=new Date(r).toISOString(),s=r-uu*24*60*60*1e3,o=new Map(e.getSearchSeen().map(a=>[a.url,a]));for(let a of t)o.set(a,{url:a,lastSeenAt:n});let i=[...o.values()].filter(a=>{let c=Date.parse(a.lastSeenAt);return Number.isNaN(c)?!1:c>=s});e.setSearchSeen(i)}async function sK(e){let t={},r=L();await SL(r);let n=await vs(t),s=gs(r.getState()),o=s?.recommendations.languages??void 0,i=Nf(r.getState()),a=new Set(i.map(w=>w.toLowerCase())),c=s?.recommendations.repos?.filter(w=>!a.has(w.toLowerCase()));(o?.length||c?.length)&&O(Wa,`Applying strategy bias to search: preferLanguages=${JSON.stringify(o??[])}, preferRepos=${JSON.stringify(c??[])}`);let u=vL("OSS_AUTOPILOT_SCOUT_INTER_PHASE_DELAY_MS"),d=vL("OSS_AUTOPILOT_SCOUT_BROAD_PHASE_DELAY_MS"),p=await n.search({maxResults:e.maxResults,...e.strategies&&{strategies:e.strategies},...e.full&&{full:!0},preferLanguages:o,preferRepos:c,diversityRatio:wl,recentlySurfacedTtlDays:OS,...u!==void 0&&{interPhaseDelayMs:u},...d!==void 0&&{broadPhaseDelayMs:d}}),m=null;if(e.record!==!1){let w=()=>{kL(r,p.candidates.map(y=>y.issue.url)),r.setSearchRotation(n.getState().searchRotation)};w(),m=await we(r,Wa,w)}let f=r.getState().config?.githubUsername??"";f===""&&v(Wa,"githubUsername not configured \u2014 the own-PR filter (#1354) cannot run; hiddenOwnPRCount will be 0");let g=p.candidates.filter(w=>ms({linkedPR:Lo(w.vettingResult?.linkedPR),userLogin:f})!=="user_open"),h=p.candidates.length-g.length;h>0&&O(Wa,`Hid ${h} candidate(s) with the user's own open PR (#1354)`);let b={candidates:g.map(w=>{let y=r.getRepoScore(w.issue.repo),S=Cs({repo:w.issue.repo,projectHealth:w.projectHealth??{repo:w.issue.repo,checkFailed:!0,failureReason:"health not supplied by the caller"},getRepoScore:R=>{let P=r.getRepoScore(R);return P?{mergedPRCount:P.mergedPRCount,closedWithoutMergeCount:P.closedWithoutMergeCount,avgResponseDays:P.avgResponseDays??null}:void 0}}),k=_s(w.vettingResult?.linkedPR);return{issue:{repo:w.issue.repo,repoUrl:`https://github.com/${w.issue.repo}`,number:w.issue.number,title:w.issue.title,url:w.issue.url,labels:w.issue.labels},recommendation:ks(w.recommendation,S),reasonsToApprove:w.reasonsToApprove,reasonsToSkip:w.reasonsToSkip,searchPriority:w.searchPriority,viabilityScore:nK(w.viabilityScore),grade:S,repoScore:y?{score:y.score,mergedPRCount:y.mergedPRCount,closedWithoutMergeCount:y.closedWithoutMergeCount,isResponsive:y.signals?.isResponsive??!1,lastMergedAt:y.lastMergedAt}:void 0,...k&&{linkedPR:k},...w.personalization?.kind==="boosted"&&{boostScore:w.personalization.score},...w.personalization?.kind==="boosted"&&w.personalization.reasons.length>0&&{boostReasons:w.personalization.reasons},...w.personalization?.kind==="diversity"&&{diversitySlot:!0}}}),excludedRepos:p.excludedRepos,aiPolicyBlocklist:p.aiPolicyBlocklist,hiddenOwnPRCount:h,reposAtCap:i};return m&&(b.gistSyncWarning=m),p.rateLimitWarning&&(b.rateLimitWarning=p.rateLimitWarning),t.skipListUnavailable&&(b.skipListUnavailable=!0),b}var Wa,eK,tK,PL=A(()=>{"use strict";Ha();gg();le();Rl();Ju();_L();ce();xa();Ui();Ha();Ui();Wa="search",eK=100,tK=15});var AL={};re(AL,{MAX_FEATURES_RESULTS:()=>iK,runFeatures:()=>cK});function aK(e){return typeof e!="number"||!Number.isFinite(e)||e<0||e>100?(v(oK,`Ignoring out-of-contract viabilityScore from scout: ${JSON.stringify(e)}`),0):e}function EL(e,t){let r=t.getRepoScore(e.issue.repo),n=Cs({repo:e.issue.repo,projectHealth:e.projectHealth??{repo:e.issue.repo,checkFailed:!0,failureReason:"health not supplied by the caller"},getRepoScore:o=>{let i=t.getRepoScore(o);return i?{mergedPRCount:i.mergedPRCount,closedWithoutMergeCount:i.closedWithoutMergeCount,avgResponseDays:i.avgResponseDays??null}:void 0}}),s=_s(e.vettingResult?.linkedPR);return{issue:{repo:e.issue.repo,repoUrl:`https://github.com/${e.issue.repo}`,number:e.issue.number,title:e.issue.title,url:e.issue.url,labels:e.issue.labels},recommendation:ks(e.recommendation,n),reasonsToApprove:e.reasonsToApprove,reasonsToSkip:e.reasonsToSkip,searchPriority:e.searchPriority,viabilityScore:aK(e.viabilityScore),grade:n,repoScore:r?{score:r.score,mergedPRCount:r.mergedPRCount,closedWithoutMergeCount:r.closedWithoutMergeCount,isResponsive:r.signals?.isResponsive??!1,lastMergedAt:r.lastMergedAt}:void 0,...s&&{linkedPR:s},horizon:e.horizon}}async function cK(e){let r=await(await vs()).features({count:e.maxResults,anchorThreshold:e.anchorThreshold,splitRatio:e.splitRatio}),n=L();return{quickWins:r.quickWins.map(o=>EL(o,n)),biggerBets:r.biggerBets.map(o=>EL(o,n)),anchorRepos:r.anchorRepos,message:r.message}}var oK,iK,TL=A(()=>{"use strict";Ha();le();Rl();ce();oK="features",iK=100});var $L={};re($L,{runVet:()=>uK});async function uK(e){Ze(e.issueUrl),Qe(e.issueUrl,dr,"issue");let r=await(await vs()).vetIssue(e.issueUrl),n=Cs({repo:r.issue.repo,projectHealth:r.projectHealth,getRepoScore:d=>L().getRepoScore(d)}),s=L().getState().config.githubUsername,o=ms({linkedPR:Lo(r.vettingResult.linkedPR),userLogin:s}),i=_s(r.vettingResult.linkedPR),a={issue:{repo:r.issue.repo,number:r.issue.number,title:r.issue.title,url:r.issue.url,labels:r.issue.labels},recommendation:ks(r.recommendation,n),reasonsToApprove:r.reasonsToApprove,reasonsToSkip:r.reasonsToSkip,projectHealth:r.projectHealth,vettingResult:r.vettingResult,antiLLMPolicy:r.antiLLMPolicy,linkedPRClassification:o,...i&&{linkedPR:i},slmTriage:r.slmTriage??null,grade:n,...Gf(L().getState(),r.issue.repo)},c=Gi(L().getState().workClaims??[],e.issueUrl);if(c)return{...a,...c,reasonsToSkip:[...a.reasonsToSkip,...c.reasonsToSkip]};let u=await lK(a);return{...a,...await _a(L(),u?[u]:[])}}async function lK(e){if(e.linkedPRClassification?.startsWith("user_"))return;let{repo:t,number:r,url:n}=e.issue,[s,o]=t.split("/",2),i;try{i=await yo(be(ke()),{repo:o,owner:s,number:r})}catch(a){v("vet",`Could not verify ${n} for pick traits: ${I(a)}`)}if(!(i&&ba.has(i.verdict)))return wa(e,"vet",{...i&&Ra(i),firstInRepo:Sa(t,L().getRepoScore(t),L().getState().mergedPRs)})}var OL=A(()=>{"use strict";Ha();Ot();Rl();xa();le()});var IL={};re(IL,{runVerifyIssue:()=>dK});async function dK(e){Ze(e.issueUrl),Qe(e.issueUrl,dr,"issue");let t=q(e.issueUrl);if(!t||t.type!=="issues")throw new j(`Not a parseable GitHub issue URL: ${e.issueUrl}`);let r=be(ke());return yo(r,{owner:t.owner,repo:t.repo,number:t.number})}var xL=A(()=>{"use strict";le();ee();Ot()});var FL={};re(FL,{classifyListStatus:()=>LL,extractSkipReason:()=>DL,listStatusFromVerdict:()=>ML,runVetList:()=>hK});function mK(e,t){switch(e){case"issue_closed":return"closed";case"claimed":return"claimed";case"has_linked_pr":return t.linkedPR?.state==="open"&&t.linkedPR.isStalled?"has_stalled_pr":"has_pr";case"score_too_low":case"anti_llm_policy":case"other":return null}}function DL(e){if(typeof e!="object"||e===null)return;let t=e.skipReason;if(typeof t=="string")return pK.has(t)?t:void 0}function LL(e,t){if(t){let r=mK(t,e);if(r)return r}else{let r=e.reasonsToSkip.map(n=>n.toLowerCase());if(r.some(n=>n.includes("closed")))return"closed";if(r.some(n=>n.includes("claimed")||n.includes("assigned")))return"claimed";if(r.some(n=>n.includes("existing pr")||n.includes("linked pr")||n.includes("pull request")))return e.linkedPR?.state==="open"&&e.linkedPR.isStalled?"has_stalled_pr":"has_pr"}return e.recommendation==="approve"||e.recommendation==="needs_review","still_available"}function ML(e){switch(e){case"closed":return"closed";case"own-open-pr":return"own_open_pr";case"taken":return"claimed";case"at-risk":return"at_risk";case"available":return"still_available"}}function fK(e){return{verdict:e.verdict,verdictReason:e.verdictReason,state:e.state,stateReason:e.stateReason,assignees:e.assignees,linkedPRs:e.linkedPRs}}function gK(e){return{issue:{repo:`${e.owner}/${e.repo}`,number:e.number,title:e.title,url:e.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:[e.verdictReason],projectHealth:{},vettingResult:{},grade:eC}}function Xk(e){return e instanceof Error?e.message:String(e)}async function hK(e={}){let t=e.concurrency??5,r=e.issueListPath;if(!r){let R=Eo();if(!R)throw new Error("No issue list found. Provide a path with --path or configure issueListPath in settings.");r=R.path}let n=await Ev({filePath:r}),s=[...n.available,...n.blocked];if(s.length===0)return{results:[],summary:{total:0,stillAvailable:0,claimed:0,closed:0,hasPR:0,hasStalledPR:0,atRisk:0,ownOpenPr:0,errors:0}};let o=be(ke()),i=[];s.forEach((R,P)=>{let C=q(R.url);C&&C.type==="issues"&&i.push({index:P,params:{owner:C.owner,repo:C.repo,number:C.number}})});let a=await Xm(o,i.map(R=>R.params),{concurrency:t}),c=new Map;i.forEach((R,P)=>c.set(R.index,a[P]));let u=await vs(),d=[];async function p(R,P){let C=await u.vetIssue(R.url),E=Cs({repo:C.issue.repo,projectHealth:C.projectHealth,getRepoScore:ve=>L().getRepoScore(ve)}),T=L().getState().config.githubUsername,M=ms({linkedPR:Lo(C.vettingResult.linkedPR),userLogin:T}),G=_s(C.vettingResult.linkedPR),X={issue:{repo:C.issue.repo,number:C.issue.number,title:C.issue.title,url:C.issue.url,labels:C.issue.labels},recommendation:ks(C.recommendation,E),reasonsToApprove:C.reasonsToApprove,reasonsToSkip:C.reasonsToSkip,projectHealth:C.projectHealth,vettingResult:C.vettingResult,antiLLMPolicy:C.antiLLMPolicy,linkedPRClassification:M,...G&&{linkedPR:G},slmTriage:C.slmTriage??null,grade:E,...Gf(L().getState(),C.issue.repo)};if(P){let ve=wa(X,"vet-list",{...Ra(P),firstInRepo:Sa(C.issue.repo,L().getRepoScore(C.issue.repo),L().getState().mergedPRs)});ve&&d.push(ve)}return{vetResult:X,skipReason:DL(C)}}function m(R,P){let C=Xk(P);return{issue:{repo:R.repo,number:R.number,title:R.title,url:R.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:[`Error: ${C}`],projectHealth:{},vettingResult:{},grade:eC,listStatus:"error",errorMessage:C}}async function f(R,P){let C=Gi(L().getState().workClaims??[],R.url);if(C)return{issue:{repo:R.repo,number:R.number,title:R.title,url:R.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:C.reasonsToSkip,projectHealth:{},vettingResult:{},grade:eC,listStatus:"claimed",workClaim:C.workClaim};if(!P||P.verification===void 0){let G=P?.error;if(G instanceof j)return{...m(R,G),verifyError:Xk(G)};let X={verifyError:G===void 0?`not verified: ${R.url} is not a verifiable issue URL`:Xk(G)};try{let{vetResult:ve,skipReason:he}=await p(R);return{...ve,listStatus:LL(ve,he),...X}}catch(ve){return{...m(R,ve),...X}}}let E=P.verification,T=fK(E),M=ML(E.verdict);if(ba.has(E.verdict))return{...gK(E),listStatus:M,verification:T};try{let{vetResult:G}=await p(R,E);return{...G,listStatus:M,verification:T}}catch(G){return{...m(R,G),verification:T}}}let g=new Array(s.length),h=0;async function b(){for(;h<s.length;){let R=h++;g[R]=await f(s[R],c.get(R))}}let w=Array.from({length:Math.min(t,s.length)},()=>b());await Promise.all(w);let y=await _a(L(),d),S={total:g.length,stillAvailable:g.filter(R=>R.listStatus==="still_available").length,claimed:g.filter(R=>R.listStatus==="claimed").length,closed:g.filter(R=>R.listStatus==="closed").length,hasPR:g.filter(R=>R.listStatus==="has_pr").length,hasStalledPR:g.filter(R=>R.listStatus==="has_stalled_pr").length,atRisk:g.filter(R=>R.listStatus==="at_risk").length,ownOpenPr:g.filter(R=>R.listStatus==="own_open_pr").length,errors:g.filter(R=>R.listStatus==="error").length},k;if(e.prune&&r)try{let R=yg.readFileSync(r,"utf8"),{pruned:P,removedCount:C}=Pv(R);P!==R&&yg.writeFileSync(r,P,"utf8"),k={removedCount:C}}catch(R){let P=R instanceof Error?R.message:String(R);console.error(`Warning: Failed to prune ${r}: ${P}`),k={removedCount:0,error:P}}return{results:g,summary:S,pruneResult:k,...y}}var yg,eC,pK,NL=A(()=>{"use strict";yg=B(require("node:fs"),1);Ha();Po();sl();Rl();xa();ee();le();eC=Yk({avgResponseDays:null,mergeRate:null,daysSinceLastCommit:null}),pK=new Set(["issue_closed","has_linked_pr","claimed","score_too_low","anti_llm_policy","other"])});var WL={};re(WL,{runLedgerBackfill:()=>TK});function jL(e){let t=(e.firstComments?.nodes??[]).filter(n=>n!==null).map(n=>({user:UL(n.author),author_association:n.authorAssociation,created_at:n.createdAt})),r=(e.reviews?.nodes??[]).filter(n=>n!==null).map(n=>({user:UL(n.author),submitted_at:n.submittedAt}));return e.author?.login?Em(t,r,e.author.login):void 0}async function _K(e,t,r){return(await e.graphql(RK,{o:t.owner,r:t.repo,n:t.number,c:r.firstComments?.pageInfo?.endCursor??null,rc:r.reviews?.pageInfo?.endCursor??null})).repository?.pullRequest}async function vK(e,t,r,n){let s=q(t),o=jL(r);for(let i=1;!o&&s&&i<bK&&SK(r);i++){let a;try{a=await _K(e,s,r)}catch(c){if(de(c)||ua(c))throw c;return n.push(`response lookup for ${t} failed: ${I(c)}`),{isPending:!0}}if(!a)return{isPending:!0};r.firstComments=a.firstComments,r.reviews=a.reviews,o=jL(r)}return{at:o,isPending:!1}}async function kK(e,t,r,n){if(t)for(let[s,o]of t){let{at:i,isPending:a}=await vK(e,s,o,n);a||r.set(s,i)}}function CK(e){let t=0;for(let r of e.values())r&&t++;return t}async function PK(e,t,r){let n=[],s=[],o={};if(t.forEach((u,d)=>{let p=q(u);p&&(n.push(`$o${d}: String!, $r${d}: String!, $n${d}: Int!`),Object.assign(o,{[`o${d}`]:p.owner,[`r${d}`]:p.repo,[`n${d}`]:p.number}),s.push(`p${d}: repository(owner: $o${d}, name: $r${d}) { pullRequest(number: $n${d}) {${wK}} }`))}),s.length===0)return new Map;let i=`query ledgerBackfill(${n.join(", ")}) {
307
+ `,{mode:384})}catch(r){H(at,`Failed to write cache: ${Y(r)}`)}}},A4=2160*60*60*1e3});function tL(){return eL.join(Rs(),"state.json")}function pg(){let e=tL();try{let t=Mr.readFileSync(e,"utf-8");return dl(JSON.parse(t))}catch(t){if(t?.code==="ENOENT")return xn.parse({version:1});H(dg,`Failed to load state from ${e}: ${Y(t)}. Using defaults.`);try{let n=`${e}.corrupt.${Date.now()}`;Mr.copyFileSync(e,n),H(dg,`Corrupt state backed up to ${n}`)}catch(n){H(dg,`Failed to back up corrupt state: ${Y(n)}`)}return xn.parse({version:1})}}function rL(e){let t=tL(),r=`${t}.tmp.${process.pid}.${L4++}`,n=JSON.stringify(e,null,2)+`
308
+ `;Mr.writeFileSync(r,n,{mode:384});try{Mr.renameSync(r,t)}catch(s){try{Mr.unlinkSync(r)}catch{}throw s}se(dg,"State saved")}var Mr,eL,dg,L4,nL=A(()=>{Mr=B(require("fs"),1),eL=B(require("path"),1);Io();It();pt();ft();dg="local-state";L4=0});function M4(e){let t="Changes will only be saved locally.";switch(e){case"rate_limit":return`Gist sync unavailable \u2014 GitHub API rate limit exceeded. ${t} Try again after the rate limit resets.`;case"network":return`Gist sync unavailable \u2014 could not reach GitHub. ${t} Check your network connection.`;case"server":return`Gist sync unavailable \u2014 GitHub returned a server error. ${t} Try again later.`;case"unknown":case void 0:return`Gist sync unavailable \u2014 running in offline mode. ${t}`}}function F4(e){return{gists:{async get(t){let{data:r}=await e.gists.get(t);if(!r.id)throw new Error("Gist get returned no id");let n=r.files?Object.fromEntries(Object.entries(r.files).map(([s,o])=>[s,o?{content:o.content}:void 0])):null;return{data:{id:r.id,files:n}}},async create(t){let{data:r}=await e.gists.create(t);if(!r.id)throw new Error("Gist create returned no id");return{data:{id:r.id}}},async update(t){let{data:r}=await e.gists.update(t);if(!r.id)throw new Error("Gist update returned no id");return{data:{id:r.id}}},async list(t){let{data:r}=await e.gists.list(t);return{data:r.filter(n=>n.id).map(n=>({id:n.id,description:n.description??null}))}}}}}async function mg(e){e.logLevel!==void 0&&jf(e.logLevel);let t,r=null,n=!1;if(e.persistence==="provided")t=e.initialState;else if(e.persistence==="gist"){r=new lg(F4(In(e.githubToken)));let s=await r.bootstrap();s.degraded&&H("scout",M4(s.degradedReason));let o=pg();t=gl(o,s.state),e.gistId?t.gistId=e.gistId:s.gistId&&(t.gistId=s.gistId)}else t=pg(),n=!0;return new hl(e.githubToken,t,r,{persistLocal:n})}var hl,sL=A(()=>{Ik();tg();zk();Io();XD();Zf();nL();pt();It();ft();Dn();hl=class{githubToken;gistStore;state;dirty=!1;persistLocal;constructor(t,r,n=null,s={}){this.githubToken=t,this.gistStore=n,this.state=r,this.persistLocal=s.persistLocal??!1}evictStaleCacheEntries(){gt().evictStale()}async search(t){this.evictStaleCacheEntries(),this.cullExpiredSkips();let r=new Set((this.state.skippedIssues??[]).map(w=>w.url));if(t?.excludeRecentlySurfaced??!0){let w=t?.recentlySurfacedTtlDays??7,y=Date.now()-w*24*60*60*1e3;for(let S of this.state.savedResults??[]){let k=Date.parse(S.lastSeenAt);!Number.isNaN(k)&&k>=y&&r.add(S.issueUrl)}}let n=new xo(this.githubToken,this.state.preferences,this),s=this.state.preferences,o=s.preferLanguages??[],i=s.preferRepos??[],a=t?.preferLanguages??(o.length>0?o:void 0),c=t?.preferRepos??(i.length>0?i:void 0),u=s.avoidRepos??[],d=s.boostIssueTypes??[],p=t?.avoidRepos??(u.length>0?u:void 0),m=t?.boostIssueTypes??(d.length>0?d:void 0),f=t?.diversityRatio??s.diversityRatio??0,g=this.state.searchRotation??{languageOffset:0},h,b;try{({candidates:h,strategiesUsed:b}=await n.searchIssues({maxResults:t?.maxResults,strategies:t?.strategies,skippedUrls:r,preferLanguages:a,preferRepos:c,avoidRepos:p,boostIssueTypes:m,diversityRatio:f,interPhaseDelayMs:t?.interPhaseDelayMs,broadPhaseDelayMs:t?.broadPhaseDelayMs,languageRotationOffset:g.languageOffset,repoRotationOffsets:{merged:g.phase0Offset??0,starred:g.starredOffset??0,maintained:g.maintainedOffset??0},strategyRotationOffset:t?.full?void 0:g.strategyOffset??0}))}catch(w){throw w instanceof ot&&this.advanceRotation(g,w.strategiesUsed??[],t?.full),w}this.advanceRotation(g,b,t?.full);for(let w of h)this.updateRepoSignalsFromHealth(w.projectHealth);return this.state.lastSearchAt=new Date().toISOString(),this.dirty=!0,{candidates:h,excludedRepos:this.state.preferences.excludeRepos,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,rateLimitWarning:n.rateLimitWarning??void 0,strategiesUsed:b}}advanceRotation(t,r,n=!1){let s=o=>r.includes(o)?1:0;r.length!==0&&(this.state.searchRotation={...t,languageOffset:t.languageOffset+s("broad"),phase0Offset:(t.phase0Offset??0)+s("merged"),starredOffset:(t.starredOffset??0)+s("starred"),maintainedOffset:(t.maintainedOffset??0)+s("maintained"),strategyOffset:n?t.strategyOffset:Oo.indexOf(r[0])+1,lastRotatedAt:new Date().toISOString()},this.dirty=!0)}updateRepoSignalsFromHealth(t){t.checkFailed||this.updateRepoScore(t.repo,{signals:{hasActiveMaintainers:t.isActive}})}async vetIssue(t){return new xo(this.githubToken,this.state.preferences,this).vetIssue(t)}async features(t){this.evictStaleCacheEntries();let r=t?.count??10,n=In(this.githubToken),s=new Ss(n,this),o=t?.broad?await qD({octokit:n,vetter:s,count:r,languages:this.state.preferences.languages,excludeRepos:this.state.preferences.excludeRepos,excludeOrgs:this.state.preferences.excludeOrgs,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,splitRatio:t?.splitRatio??this.state.preferences.featuresSplitRatio}):await cg({octokit:n,vetter:s,repoScores:this.state.repoScores??{},count:r,excludeRepos:this.state.preferences.excludeRepos,excludeOrgs:this.state.preferences.excludeOrgs,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,anchorThreshold:t?.anchorThreshold??this.state.preferences.featuresAnchorThreshold,splitRatio:t?.splitRatio??this.state.preferences.featuresSplitRatio});return this.saveResults([...o.quickWins,...o.biggerBets]),this.state.lastSearchAt=new Date().toISOString(),this.dirty=!0,o}async vetList(t){this.evictStaleCacheEntries();let r=this.getSavedResults(),n=t?.concurrency??5,s=[],o=new Map,i=null;for(let m of r){if(i)break;let f=this.vetIssue(m.issueUrl).then(g=>{s.push({issueUrl:m.issueUrl,repo:m.repo,number:m.number,title:m.title,status:this.classifyVetResult(g),ok:!0,recommendation:g.recommendation,viabilityScore:g.viabilityScore})}).catch(g=>{if(Fe(g)===401||mt(g)){i??=g;return}let h=Fe(g),b=h===404||h===410;s.push({issueUrl:m.issueUrl,repo:m.repo,number:m.number,title:m.title,status:b?"closed":"error",ok:!1,errorMessage:Y(g)})}).finally(()=>{o.delete(m.issueUrl)});o.set(m.issueUrl,f),o.size>=n&&await Promise.race(o.values())}if(await Promise.allSettled(o.values()),i)throw s.length>0&&H("scout",`vetList aborted mid-batch after ${s.length} result(s) \u2014 discarding partial results due to auth/rate-limit failure`),i;let a={total:s.length,stillAvailable:s.filter(m=>m.status==="still_available").length,claimed:s.filter(m=>m.status==="claimed").length,closed:s.filter(m=>m.status==="closed").length,hasPR:s.filter(m=>m.status==="has_pr").length,errors:s.filter(m=>m.status==="error").length},c=new Map((this.state.savedResults??[]).map(m=>[m.issueUrl,m.lastStatus])),u=s.filter(m=>m.status!=="error").filter(m=>{let f=c.get(m.issueUrl);return f!==void 0&&f!==m.status}).map(m=>({issueUrl:m.issueUrl,repo:m.repo,number:m.number,from:c.get(m.issueUrl),to:m.status})),d=new Map(s.map(m=>[m.issueUrl,m.status]));for(let m of this.state.savedResults??[]){let f=d.get(m.issueUrl);f!==void 0&&f!=="error"&&(m.lastStatus=f)}s.length>0&&(this.dirty=!0);let p;if(t?.prune){let m=new Set(s.filter(g=>g.status!=="still_available").map(g=>g.issueUrl)),f=(this.state.savedResults??[]).length;this.state.savedResults=(this.state.savedResults??[]).filter(g=>!m.has(g.issueUrl)),p=f-(this.state.savedResults?.length??0),p>0&&this.addTombstones([...m]),this.dirty=!0}return{results:s,summary:a,prunedCount:p,transitions:u}}classifyVetResult(t){if(t.issueState==="closed")return"closed";let r=t.vettingResult.checks;return r.noExistingPR?r.notClaimed?"still_available":"claimed":"has_pr"}getReposWithMergedPRs(){let t=new Map;for(let r of this.state.mergedPRs??[]){let n=it(r.url);n&&t.set(n,(t.get(n)??0)+1)}return[...t.entries()].sort((r,n)=>n[1]-r[1]).map(([r])=>r)}getReposWithOpenPRs(){let t=new Map;for(let r of this.state.openPRs??[]){let n=it(r.url);n&&t.set(n,(t.get(n)??0)+1)}return[...t.entries()].sort((r,n)=>n[1]-r[1]).map(([r])=>r)}getStarredRepos(){return this.state.starredRepos}getProjectCategories(){return this.state.preferences.projectCategories}getGitHubUsername(){return this.state.preferences.githubUsername}getRepoScore(t){let r=this.state.repoScores[t];return r?r.score:null}getClosedWithoutMergeCount(t){let r=this.state.repoScores[t];return r?r.closedWithoutMergeCount:(this.state.closedPRs??[]).filter(n=>it(n.url)===t).length}getSLMTriageConfig(){let t=this.state.preferences.slmTriageModel??"";return t?{model:t,host:this.state.preferences.slmTriageHost??""}:null}getPreferences(){return this.state.preferences}getRepoScoreRecord(t){return this.state.repoScores[t]}recordMergedPR(t){let r=this.state.mergedPRs??[];r.some(n=>n.url===t.url)||(this.state.mergedPRs=[...r,{url:t.url,title:t.title,mergedAt:t.mergedAt}],this.updateRepoScoreFromPRs(t.repo),this.dirty=!0)}recordClosedPR(t){let r=this.state.closedPRs??[];r.some(n=>n.url===t.url)||(this.state.closedPRs=[...r,{url:t.url,title:t.title,closedAt:t.closedAt}],this.updateRepoScoreFromPRs(t.repo),this.dirty=!0)}recordOpenPR(t){let r=this.state.openPRs??[];r.some(n=>n.url===t.url)||(this.state.openPRs=[...r,{url:t.url,title:t.title,openedAt:t.openedAt}],this.dirty=!0)}async syncOpenPRs(){let t=In(this.githubToken),r=this.state.openPRs??[],n={checked:r.length,merged:0,closed:0,stillOpen:0,errors:0},s=[];for(let o of r){let i=Ao(o.url);if(!i||i.type!=="pull"){s.push(o),n.errors++;continue}let a=`${i.owner}/${i.repo}`;try{let{data:c}=await t.pulls.get({owner:i.owner,repo:i.repo,pull_number:i.number});c.merged?(this.recordMergedPR({url:o.url,title:o.title,mergedAt:c.merged_at??new Date().toISOString(),repo:a}),n.merged++):c.state==="closed"?(this.recordClosedPR({url:o.url,title:o.title,closedAt:c.closed_at??new Date().toISOString(),repo:a}),n.closed++):(s.push(o),n.stillOpen++)}catch(c){Be(c),H("scout",`sync: could not check ${o.url}: ${Y(c)}`),s.push(o),n.errors++}}return this.state.openPRs=s,this.dirty=!0,await this.checkpoint(),n}updateRepoScore(t,r){let s=this.state.repoScores[t]??{repo:t,score:5,mergedPRCount:0,closedWithoutMergeCount:0,avgResponseDays:null,lastEvaluatedAt:new Date().toISOString(),signals:{hasActiveMaintainers:!1,isResponsive:!1,hasHostileComments:!1}},o={...s,...r,repo:t,lastEvaluatedAt:new Date().toISOString(),signals:{...s.signals,...r.signals??{}}};o.score=this.calculateScore(o),this.state.repoScores[t]=o,this.dirty=!0}updatePreferences(t){this.state.preferences={...this.state.preferences,...t},this.state.preferencesUpdatedAt=new Date().toISOString(),this.dirty=!0}setStarredRepos(t){this.state.starredRepos=t,this.state.starredReposLastFetched=new Date().toISOString(),this.dirty=!0}saveResults(t){let r=new Date().toISOString(),n=new Map((this.state.savedResults??[]).map(s=>[s.issueUrl,s]));for(let s of t){if(s.recommendation==="skip"){n.delete(s.issue.url);let i=new Set(["Issue is closed","Linked PR already merged"]),a=s.reasonsToSkip.some(c=>i.has(c));this.skipIssue(s.issue.url,{repo:s.issue.repo,number:s.issue.number,title:s.issue.title,reason:s.reasonsToSkip.join("; ")||"vetter: skip",permanent:a});continue}let o=n.get(s.issue.url);n.set(s.issue.url,{issueUrl:s.issue.url,repo:s.issue.repo,number:s.issue.number,title:s.issue.title,labels:s.issue.labels,recommendation:s.recommendation,viabilityScore:s.viabilityScore,searchPriority:s.searchPriority,firstSeenAt:o?.firstSeenAt??r,lastSeenAt:r,lastScore:s.viabilityScore,horizon:"horizon"in s?s.horizon:void 0})}this.state.savedResults=[...n.values()],this.dirty=!0}getSavedResults(){return this.state.savedResults??[]}clearResults(){this.addTombstones((this.state.savedResults??[]).map(t=>t.issueUrl)),this.state.savedResults=[],this.dirty=!0}addTombstones(t){if(t.length===0)return;let r=new Date().toISOString(),n=this.state.tombstones??[],s=new Map(n.map(o=>[o.url,o]));for(let o of t)s.set(o,{url:o,removedAt:r});this.state.tombstones=[...s.values()]}skipIssue(t,r){let n=this.state.skippedIssues??[],s=n.find(i=>i.url===t);if(s){r?.permanent===!0&&s.permanent!==!0&&(s.permanent=!0,s.skippedAt=new Date().toISOString(),this.dirty=!0);return}let o=r?.permanent??!0;this.state.skippedIssues=[...n,{url:t,repo:r?.repo??"",number:r?.number??0,title:r?.title??"",skippedAt:new Date().toISOString(),permanent:o,...r?.reason?{reason:r.reason}:{}}],this.state.savedResults&&(this.state.savedResults=this.state.savedResults.filter(i=>i.issueUrl!==t)),this.dirty=!0}getSkippedIssues(){return this.state.skippedIssues??[]}unskipIssue(t){let r=(this.state.skippedIssues??[]).length;this.state.skippedIssues=(this.state.skippedIssues??[]).filter(n=>n.url!==t),this.state.skippedIssues.length<r&&this.addTombstones([t]),this.dirty=!0}clearSkippedIssues(){this.addTombstones((this.state.skippedIssues??[]).map(t=>t.url)),this.state.skippedIssues=[],this.dirty=!0}cullExpiredSkips(t=90){let r=new Date;r.setDate(r.getDate()-t);let n=[];return this.state.skippedIssues=(this.state.skippedIssues??[]).filter(s=>{if(s.permanent!==!1)return!0;let o=new Date(s.skippedAt);return isNaN(o.getTime())||o>=r?!0:(n.push(s.url),!1)}),n.length>0&&(this.addTombstones(n),this.dirty=!0),n.length}isDirty(){return this.dirty}async checkpoint(){if(!this.dirty)return!0;if(this.state.lastRunAt=new Date().toISOString(),this.gistStore&&!await this.gistStore.push(this.state))return!1;if(this.persistLocal)try{this.state=gl(this.state,pg()),rL(this.state)}catch{return!1}return this.dirty=!1,!0}getState(){return this.state}updateRepoScoreFromPRs(t){let r=(this.state.mergedPRs??[]).filter(s=>it(s.url)===t).length,n=(this.state.closedPRs??[]).filter(s=>it(s.url)===t).length;this.updateRepoScore(t,{mergedPRCount:r,closedWithoutMergeCount:n,lastMergedAt:r>0?(this.state.mergedPRs??[]).filter(s=>it(s.url)===t).sort((s,o)=>o.mergedAt.localeCompare(s.mergedAt))[0]?.mergedAt:void 0})}calculateScore(t){let r=5;return r+=Math.min(t.mergedPRCount,3),r-=Math.min(t.closedWithoutMergeCount,3),t.signals.hasActiveMaintainers&&(r+=1),t.signals.hasHostileComments&&(r-=2),Math.max(1,Math.min(10,r))}}});function oL(){let e=bl.filter(r=>!(r in yl));if(e.length>0)throw new Error(`FIELD_CONFIGS is missing entries for preference keys: ${e.join(", ")}`);let t=Object.keys(yl).filter(r=>!bl.includes(r));if(t.length>0)throw new Error(`FIELD_CONFIGS has entries for unknown preference keys: ${t.join(", ")}`)}function N4(e){let t=e.toLowerCase();if(t==="true"||t==="yes")return!0;if(t==="false"||t==="no")return!1;throw new ot(`Invalid boolean value: "${e}". Use true/false or yes/no.`)}function G4(e,t){let r=parseInt(e,10);if(isNaN(r))throw new ot(`Invalid number for "${t}": "${e}"`);return r}function U4(e,t){let r=Number.parseFloat(e);if(isNaN(r))throw new ot(`Invalid number for "${t}": "${e}"`);return r}function Vk(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function fg(e,t){if(t.startsWith("+")){let r=Vk(t.slice(1)),n=[...e];for(let s of r)n.includes(s)||n.push(s);return n}if(t.startsWith("-")){let r=new Set(Vk(t.slice(1)));return e.filter(n=>!r.has(n))}return Vk(t)}function iL(e,t,r){let n=yl[t];if(!n)throw new ot(`Unknown config key: "${t}". Valid keys: ${qk.join(", ")}`);let s={...e};switch(n.type){case"string":t==="slmTriageHost"&&SD(r),s[t]=r;break;case"boolean":s[t]=N4(r);break;case"number":s[t]=G4(r,t);break;case"float":s[t]=U4(r,t);break;case"array":{let o=s[t]??[];s[t]=fg(o,r);break}case"enum":{let o=n.validValues;if(!o.includes(r))throw new ot(`Invalid value for "${t}": "${r}". Valid: ${o.join(", ")}`);s[t]=r;break}case"enum-array":{let o=s[t]??[],i=fg(o,r),a=n.validValues,c=i.filter(u=>!a.includes(u));if(c.length>0)throw new ot(`Invalid value(s) for "${t}": ${c.join(", ")}. Valid: ${a.join(", ")}`);t==="scope"?s[t]=i.length>0?i:void 0:s[t]=i;break}}return To.parse(s)}var yl,bl,qk,aL=A(()=>{Io();ft();kk();yl={githubUsername:{type:"string"},languages:{type:"array"},labels:{type:"array"},scope:{type:"enum-array",validValues:ll.options},excludeRepos:{type:"array"},excludeOrgs:{type:"array"},preferredOrgs:{type:"array"},aiPolicyBlocklist:{type:"array"},projectCategories:{type:"enum-array",validValues:ul.options},minStars:{type:"number"},maxIssueAgeDays:{type:"number"},includeDocIssues:{type:"boolean"},minRepoScoreThreshold:{type:"number"},interPhaseDelayMs:{type:"number"},persistence:{type:"enum",validValues:uk.options},defaultStrategy:{type:"enum-array",validValues:$o.options},broadPhaseDelayMs:{type:"number"},skipBroadWhenSufficientResults:{type:"number"},preferLanguages:{type:"array"},preferRepos:{type:"array"},diversityRatio:{type:"float"},avoidRepos:{type:"array"},boostIssueTypes:{type:"array"},slmTriageModel:{type:"string"},slmTriageHost:{type:"string"},featuresAnchorThreshold:{type:"number"},featuresSplitRatio:{type:"float"}},bl=Object.keys(To.shape),qk=[...bl].sort()});async function cL(e,t,r=fr()){let n=e.getPreferences().githubUsername;if(!n)throw new Da("GitHub username not configured. Run `oss-scout setup` first.");let s=await qf(t);if(se(nn,`Rate limit: ${s.remaining}/${s.limit}, resets at ${s.resetAt}`),s.remaining<15)return se(nn,"Insufficient rate limit, skipping bootstrap"),{starredRepoCount:0,mergedPRCount:0,closedPRCount:0,openPRCount:0,reposScoredCount:0,skippedDueToRateLimit:!0,errors:[]};let o=In(t),i=[],a=[],c=0,u=new Set;try{let f=0;for await(let g of o.paginate.iterator(o.activity.listReposStarredByAuthenticatedUser,{per_page:Do,headers:{accept:"application/vnd.github.v3+json"}})){for(let h of g.data){let b=h;a.push(b.full_name)}if(f++,f>=j4)break}se(nn,`Fetched ${a.length} starred repos`),e.setStarredRepos(a),c=a.length}catch(f){Be(f),H(nn,`Failed to fetch starred repos: ${Y(f)}`),i.push("starred repos fetch failed")}let d=0;try{for(let f=1;f<=Zk;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:merged author:${n}`,per_page:Do,page:f})).data}finally{r.recordCall()}for(let h of g.items){let b=it(h.html_url);b&&(e.recordMergedPR({url:h.html_url,title:h.title,mergedAt:h.closed_at??new Date().toISOString(),repo:b}),u.add(b),d++)}if(g.items.length<Do)break}se(nn,`Imported ${d} merged PRs`)}catch(f){Be(f),H(nn,`Failed to fetch merged PRs: ${Y(f)}`),i.push("merged PR fetch failed")}let p=0;try{for(let f=1;f<=Zk;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:closed is:unmerged author:${n}`,per_page:Do,page:f})).data}finally{r.recordCall()}for(let h of g.items){let b=it(h.html_url);b&&(e.recordClosedPR({url:h.html_url,title:h.title,closedAt:h.closed_at??new Date().toISOString(),repo:b}),u.add(b),p++)}if(g.items.length<Do)break}se(nn,`Imported ${p} closed PRs`)}catch(f){Be(f),H(nn,`Failed to fetch closed PRs: ${Y(f)}`),i.push("closed PR fetch failed")}let m=0;try{for(let f=1;f<=Zk;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:open author:${n}`,per_page:Do,page:f})).data}finally{r.recordCall()}for(let h of g.items){let b=it(h.html_url);b&&(e.recordOpenPR({url:h.html_url,title:h.title,openedAt:h.created_at??new Date().toISOString(),repo:b}),m++)}if(g.items.length<Do)break}se(nn,`Imported ${m} open PRs`)}catch(f){Be(f),H(nn,`Failed to fetch open PRs: ${Y(f)}`),i.push("open PR fetch failed")}return{starredRepoCount:c,mergedPRCount:d,closedPRCount:p,openPRCount:m,reposScoredCount:u.size,skippedDueToRateLimit:!1,errors:i}}var nn,j4,Zk,Do,uL=A(()=>{Zf();pt();ft();It();Fa();nn="bootstrap",j4=5,Zk=3,Do=100});function dL(e,t=new Date,r=30){if(!e||e.state!=="open"||!e.updatedAt)return!1;let n=new Date(e.updatedAt);return Number.isNaN(n.getTime())?!1:(t.getTime()-n.getTime())/(1e3*60*60*24)>=r}var lL,pL=A(()=>{lL=30});function gL(e,t,r){if(!t.test(e))throw new ot(`Invalid ${r} URL: ${e}. Expected format: https://github.com/owner/repo/issues/123`)}function hL(e){if(e.length>mL)throw new ot(`URL exceeds maximum length of ${mL} characters`);return e}var fL,mL,yL=A(()=>{ft();fL=/^https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+$/,mL=2048});var bL={};re(bL,{ANCHOR_THRESHOLD:()=>Fk,ANTI_LLM_KEYWORDS:()=>bk,FEATURE_LABELS:()=>ag,FIELD_CONFIGS:()=>yl,HorizonSchema:()=>ck,ISSUE_URL_PATTERN:()=>fL,IssueDiscovery:()=>xo,IssueScopeSchema:()=>ll,IssueVetter:()=>Ss,NO_ANCHORS_MESSAGE:()=>Uk,NO_RESULTS_MESSAGE:()=>jk,OssScout:()=>hl,PREFERENCE_KEYS:()=>bl,ProjectCategorySchema:()=>ul,RepoScoreSchema:()=>ik,SORTED_PREFERENCE_KEYS:()=>qk,STALLED_PR_THRESHOLD_DAYS:()=>lL,ScoutPreferencesSchema:()=>To,ScoutStateSchema:()=>xn,SearchStrategySchema:()=>$o,SkippedIssueSchema:()=>ak,applyPreferenceField:()=>iL,assertFieldConfigsCover:()=>oL,bootstrapScout:()=>cL,classifyHorizon:()=>Gk,createScout:()=>mg,discoverFeatures:()=>cg,enableDebug:()=>D0,fetchRoadmapIssueRefs:()=>og,getGitHubToken:()=>Qv,getLogLevel:()=>x0,isLinkedPRStalled:()=>dL,parseRoadmapIssueRefs:()=>Dk,requireGitHubToken:()=>j0,resolveAnchorRepos:()=>Nk,scanForAntiLLMPolicy:()=>wk,setLogLevel:()=>jf,splitByHorizon:()=>ig,updateArray:()=>fg,validateGitHubUrl:()=>gL,validateUrl:()=>hL});var gg=A(()=>{sL();Io();aL();It();Ik();tg();Rk();uL();pt();zk();pL();Lk();yL()});function H4(e){let t=[],r=e.split(/\r?\n/);for(let n=0;n<r.length;n++){let s=n+1,o=r[n].trim();if(o===""||o.startsWith("#"))continue;let i=o.match(/^(\S+)\s+(\S+)(?:\s+#.*)?$/);if(!i){v("skip-file-parser",`Line ${s}: malformed (expected "<date> <url>"): ${o}`);continue}let[,a,c]=i;if(!z4.test(a)){v("skip-file-parser",`Line ${s}: invalid date format (expected YYYY-MM-DD): ${o}`);continue}let u=Date.parse(`${a}T00:00:00.000Z`);if(Number.isNaN(u)){v("skip-file-parser",`Line ${s}: unparseable date: ${o}`);continue}let d=new Date(u).toISOString().slice(0,10);if(d!==a){v("skip-file-parser",`Line ${s}: invalid calendar date ${a} (would be normalized to ${d}): ${o}`);continue}let p=c.match(B4);if(!p){v("skip-file-parser",`Line ${s}: non-GitHub-issue URL: ${o}`);continue}let[,m,f]=p,g=Number.parseInt(f,10);t.push({url:c,repo:m,number:g,title:"",skippedAt:new Date(u).toISOString(),permanent:!0})}return t}function Kk(e){if(!e)return{issues:[]};let t=wL.resolve(e);if(!hg.existsSync(t))return v("skip-file-parser",`Configured skipped-issues file not found at ${t} (cwd ${process.cwd()}); proceeding with an EMPTY skip list \u2014 previously skipped issues may resurface. Use an absolute skippedIssuesPath, or run from the directory that contains "${e}".`),{issues:[],notFound:!0,resolvedPath:t};let r;try{r=hg.readFileSync(t,"utf8")}catch(n){return v("skip-file-parser",`Failed to read skipped-issues file at ${t}: ${I(n)}`),{issues:[],readError:I(n),resolvedPath:t}}return{issues:H4(r),resolvedPath:t}}function RL(e){return Kk(e).issues}var hg,wL,z4,B4,Jk=A(()=>{"use strict";hg=B(require("node:fs"),1),wL=B(require("node:path"),1);ce();ee();z4=/^\d{4}-\d{2}-\d{2}$/,B4=/^https:\/\/github\.com\/([^/]+\/[^/]+)\/(?:issues|pull)\/(\d+)(?:[#/?].*)?$/});function Lo(e){if(!e)return null;let t={author:{login:e.author},state:e.merged?"merged":e.state};return e.updatedAt!==void 0&&(t.updatedAt=e.updatedAt),t}function _s(e){if(!e)return;let t=Lo(e);if(!t)return;let r={number:e.number,state:t.state,url:e.url,isStalled:Qm(t)};return e.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}function W4(e){let t=L().getState(),{config:r}=t,n=Kk(r.skippedIssuesPath);(n.readError!==void 0||n.notFound)&&e&&(e.skipListUnavailable=!0);let s=[...n.issues],o=new Set(s.map(d=>d.url));for(let[d,p]of Object.entries(r.dismissedIssues??{})){if(o.has(d)||!dr.test(d))continue;let m=q(d);o.add(d),s.push({url:d,repo:m?`${m.owner}/${m.repo}`:"",number:m?.number??0,title:"",skippedAt:p,reason:"dismissed",permanent:!0})}let i=cr(t.workClaims??[]);for(let d of i){if(d.kind!=="implementation"||o.has(d.url)||!dr.test(d.url))continue;let p=q(d.url);o.add(d.url),s.push({url:d.url,repo:p?`${p.owner}/${p.repo}`:"",number:p?.number??0,title:"",skippedAt:d.startedAt,reason:`implementation in progress (session ${d.session})`,permanent:!0})}let a=gs(t),c=Nf(t),u=new Set(c.map(d=>d.toLowerCase()));return{version:1,stateRevision:1,preferences:{githubUsername:r.githubUsername,languages:r.languages,labels:r.labels,scope:r.scope,excludeRepos:[...r.excludeRepos,...c],excludeOrgs:r.excludeOrgs??[],preferredOrgs:r.preferredOrgs??[],aiPolicyBlocklist:r.aiPolicyBlocklist,projectCategories:r.projectCategories??[],minStars:r.minStars,maxIssueAgeDays:r.maxIssueAgeDays,includeDocIssues:r.includeDocIssues,minRepoScoreThreshold:r.minRepoScoreThreshold,interPhaseDelayMs:0,broadPhaseDelayMs:0,skipBroadWhenSufficientResults:r.skipBroadWhenSufficientResults,persistence:r.persistence,slmTriageModel:r.slmTriageModel,slmTriageHost:r.slmTriageHost,featuresAnchorThreshold:3,featuresSplitRatio:.6,preferLanguages:a?.recommendations.languages??[],preferRepos:(a?.recommendations.repos??[]).filter(d=>!u.has(d.toLowerCase())),diversityRatio:wl,avoidRepos:r.avoidRepos??[],boostIssueTypes:r.boostIssueTypes??[]},repoScores:t.repoScores,tombstones:[],starredRepos:r.starredRepos,starredReposLastFetched:r.starredReposLastFetched,mergedPRs:(t.mergedPRs??[]).map(d=>({url:d.url,title:d.title,mergedAt:d.mergedAt})),closedPRs:(t.closedPRs??[]).map(d=>({url:d.url,title:d.title,closedAt:d.closedAt})),openPRs:(t.lastDigest?.openPRs??[]).map(d=>({url:d.url,title:d.title,openedAt:d.createdAt})),savedResults:(t.searchSeen??[]).map(d=>({issueUrl:d.url,repo:"",number:0,title:"",labels:[],recommendation:"skip",viabilityScore:0,searchPriority:"normal",firstSeenAt:d.lastSeenAt,lastSeenAt:d.lastSeenAt,lastScore:0})),skippedIssues:s,lastRunAt:t.lastRunAt,searchRotation:t.searchRotation??PS.parse({})}}async function vs(e){let t=ke();return mg({githubToken:t,persistence:"provided",initialState:W4(e)})}var wl,Ha=A(()=>{"use strict";xa();gg();le();gn();Ju();Jk();Ot();wl=.2});function ks(e,t){return e==="approve"&&t.score<4?"needs_review":e}function V4(e){return e.reduce((t,r)=>r.score<t.score?r:t)}function q4(e){let t=Mo.indexOf(e);return t===-1?Mo[Mo.length-1]:Mo[Math.min(t+1,Mo.length-1)]}function Mn(e,t,r){return typeof e!="number"||!Number.isFinite(e)||e<t||e>r?null:e}function Z4(e){return e<3?{score:10,detail:`~${Math.round(e)}-day avg response`}:e<14?{score:7,detail:`${Math.round(e)}-day avg response`}:e<=60?{score:4,detail:`${Math.round(e)}-day avg response`}:{score:1,detail:"unresponsive maintainers"}}function K4(e){let t=Math.round(e*100);return e>.7?{score:10,detail:`merges ${t}% of PRs`}:e>=.4?{score:7,detail:`merges ${t}% of PRs`}:e>=.1?{score:4,detail:`merges ${t}% of PRs`}:{score:1,detail:`merges ${t}% of PRs`}}function J4(e){return e<7?{score:10,detail:"commits in last week"}:e<30?{score:7,detail:"commits in last month"}:e<90?{score:4,detail:"commits in last 90 days"}:{score:1,detail:`no commits in ${e}+ days`}}function Y4(e){let{projectHealth:t,repoScore:r}=e,n=!t.checkFailed,s=Mn(r?.avgResponseDays,0,Number.MAX_SAFE_INTEGER)??(n?Mn(t.avgIssueResponseDays,.001,Number.MAX_SAFE_INTEGER):null),o=n?Mn(t.daysSinceLastCommit,0,Number.MAX_SAFE_INTEGER):null,i=n?Mn(t.recentMergeRate,0,1):null;if(i===null&&r){let a=Mn(r.mergedPRCount,0,Number.MAX_SAFE_INTEGER),c=Mn(r.closedWithoutMergeCount,0,Number.MAX_SAFE_INTEGER);if(a!==null&&c!==null){let u=a+c;i=u===0?null:a/u}}return{avgResponseDays:s,mergeRate:i,daysSinceLastCommit:o}}function Cs(e){let t=e.getRepoScore(e.repo),r=e.projectHealth,n=r.checkFailed?{avgIssueResponseDays:null,daysSinceLastCommit:null,checkFailed:!0}:{avgIssueResponseDays:r.avgIssueResponseDays,daysSinceLastCommit:r.daysSinceLastCommit,recentMergeRate:r.recentMergeRate??null,checkFailed:!1};return Yk(Y4({projectHealth:n,repoScore:t?{mergedPRCount:t.mergedPRCount,closedWithoutMergeCount:t.closedWithoutMergeCount,avgResponseDays:t.avgResponseDays}:null}))}function Yk(e){let t=[],r=[],n=Mn(e.avgResponseDays,0,Number.MAX_SAFE_INTEGER);n===null?r.push("maintainer responsiveness"):t.push(Z4(n));let s=Mn(e.mergeRate,0,1);s===null?r.push("merge rate"):t.push(K4(s));let o=Mn(e.daysSinceLastCommit,0,Number.MAX_SAFE_INTEGER);if(o===null?r.push("activity"):t.push(J4(o)),t.length===0)return{score:Mo[Mo.length-1],reason:`unknown ${r.join(", ")}`};let i=V4(t),a=r.length>0?q4(i.score):i.score,c=[i.detail];return r.length>0&&c.push(`unknown ${r.join(", ")}`),{score:a,reason:c.join(", ")}}var Mo,Rl=A(()=>{"use strict";Mo=[10,7,4,1]});async function eK(e){let t=[],r=0;for await(let n of e.paginate.iterator(e.activity.listReposStarredByAuthenticatedUser,{per_page:Q4,headers:{accept:"application/vnd.github.v3+json"}})){for(let s of n.data)s.full_name&&t.push(s.full_name);if(r+=1,r>=X4)break}return t}async function SL(e){if(!e.isStarredReposStale())return e.getStarredRepos().length;let t=ke(),r;try{r=await eK(be(t))}catch(n){return v(Qk,`Failed to refresh starred repos; continuing with cached list (${e.getStarredRepos().length}): ${n instanceof Error?n.message:String(n)}`),e.getStarredRepos().length}return r.length===0?(O(Qk,"Starred-repo fetch returned 0; keeping existing cache"),e.getStarredRepos().length):(e.setStarredRepos(r),O(Qk,`Refreshed starred repos from GitHub: ${r.length} cached`),r.length)}var Qk,Q4,X4,_L=A(()=>{"use strict";so();Lm();ce();Qk="starred-repos",Q4=100,X4=5});var CL={};re(CL,{DEFAULT_SEARCH_RESULTS:()=>rK,MAX_SEARCH_RESULTS:()=>tK,SEARCH_DIVERSITY_RATIO:()=>wl,SEARCH_SEEN_RETENTION_DAYS:()=>uu,parseSearchStrategies:()=>nK,recordSearchSeen:()=>kL,runSearch:()=>oK});function nK(e){if(e===void 0)return;let t=e.split(",").map(n=>n.trim()).filter(Boolean);if(t.length===0)return;let r=[];for(let n of t){let s=$o.safeParse(n);if(!s.success)throw new Error(`Unknown search strategy "${n}". Valid strategies: merged, orgs, starred, broad, maintained, all`);r.push(s.data)}return r}function sK(e){return typeof e!="number"||!Number.isFinite(e)||e<0||e>100?(v(Wa,`Ignoring out-of-contract viabilityScore from scout: ${JSON.stringify(e)}`),0):e}function vL(e){let t=process.env[e];if(t===void 0||t==="")return;let r=Number(t);if(!Number.isInteger(r)||r<0){v(Wa,`Ignoring invalid ${e}="${t}" (expected a non-negative integer); using scout's default delay`);return}return r}function kL(e,t){let r=Date.now(),n=new Date(r).toISOString(),s=r-uu*24*60*60*1e3,o=new Map(e.getSearchSeen().map(a=>[a.url,a]));for(let a of t)o.set(a,{url:a,lastSeenAt:n});let i=[...o.values()].filter(a=>{let c=Date.parse(a.lastSeenAt);return Number.isNaN(c)?!1:c>=s});e.setSearchSeen(i)}async function oK(e){let t={},r=L();await SL(r);let n=await vs(t),s=gs(r.getState()),o=s?.recommendations.languages??void 0,i=Nf(r.getState()),a=new Set(i.map(w=>w.toLowerCase())),c=s?.recommendations.repos?.filter(w=>!a.has(w.toLowerCase()));(o?.length||c?.length)&&O(Wa,`Applying strategy bias to search: preferLanguages=${JSON.stringify(o??[])}, preferRepos=${JSON.stringify(c??[])}`);let u=vL("OSS_AUTOPILOT_SCOUT_INTER_PHASE_DELAY_MS"),d=vL("OSS_AUTOPILOT_SCOUT_BROAD_PHASE_DELAY_MS"),p=await n.search({maxResults:e.maxResults,...e.strategies&&{strategies:e.strategies},...e.full&&{full:!0},preferLanguages:o,preferRepos:c,diversityRatio:wl,recentlySurfacedTtlDays:OS,...u!==void 0&&{interPhaseDelayMs:u},...d!==void 0&&{broadPhaseDelayMs:d}}),m=null;if(e.record!==!1){let w=()=>{kL(r,p.candidates.map(y=>y.issue.url)),r.setSearchRotation(n.getState().searchRotation)};w(),m=await we(r,Wa,w)}let f=r.getState().config?.githubUsername??"";f===""&&v(Wa,"githubUsername not configured \u2014 the own-PR filter (#1354) cannot run; hiddenOwnPRCount will be 0");let g=p.candidates.filter(w=>ms({linkedPR:Lo(w.vettingResult?.linkedPR),userLogin:f})!=="user_open"),h=p.candidates.length-g.length;h>0&&O(Wa,`Hid ${h} candidate(s) with the user's own open PR (#1354)`);let b={candidates:g.map(w=>{let y=r.getRepoScore(w.issue.repo),S=Cs({repo:w.issue.repo,projectHealth:w.projectHealth??{repo:w.issue.repo,checkFailed:!0,failureReason:"health not supplied by the caller"},getRepoScore:R=>{let P=r.getRepoScore(R);return P?{mergedPRCount:P.mergedPRCount,closedWithoutMergeCount:P.closedWithoutMergeCount,avgResponseDays:P.avgResponseDays??null}:void 0}}),k=_s(w.vettingResult?.linkedPR);return{issue:{repo:w.issue.repo,repoUrl:`https://github.com/${w.issue.repo}`,number:w.issue.number,title:w.issue.title,url:w.issue.url,labels:w.issue.labels},recommendation:ks(w.recommendation,S),reasonsToApprove:w.reasonsToApprove,reasonsToSkip:w.reasonsToSkip,searchPriority:w.searchPriority,viabilityScore:sK(w.viabilityScore),grade:S,repoScore:y?{score:y.score,mergedPRCount:y.mergedPRCount,closedWithoutMergeCount:y.closedWithoutMergeCount,isResponsive:y.signals?.isResponsive??!1,lastMergedAt:y.lastMergedAt}:void 0,...k&&{linkedPR:k},...w.personalization?.kind==="boosted"&&{boostScore:w.personalization.score},...w.personalization?.kind==="boosted"&&w.personalization.reasons.length>0&&{boostReasons:w.personalization.reasons},...w.personalization?.kind==="diversity"&&{diversitySlot:!0}}}),excludedRepos:p.excludedRepos,aiPolicyBlocklist:p.aiPolicyBlocklist,hiddenOwnPRCount:h,reposAtCap:i};return m&&(b.gistSyncWarning=m),p.rateLimitWarning&&(b.rateLimitWarning=p.rateLimitWarning),t.skipListUnavailable&&(b.skipListUnavailable=!0),b}var Wa,tK,rK,PL=A(()=>{"use strict";Ha();gg();le();Rl();Ju();_L();ce();xa();Ui();Ha();Ui();Wa="search",tK=100,rK=15});var AL={};re(AL,{MAX_FEATURES_RESULTS:()=>aK,runFeatures:()=>uK});function cK(e){return typeof e!="number"||!Number.isFinite(e)||e<0||e>100?(v(iK,`Ignoring out-of-contract viabilityScore from scout: ${JSON.stringify(e)}`),0):e}function EL(e,t){let r=t.getRepoScore(e.issue.repo),n=Cs({repo:e.issue.repo,projectHealth:e.projectHealth??{repo:e.issue.repo,checkFailed:!0,failureReason:"health not supplied by the caller"},getRepoScore:o=>{let i=t.getRepoScore(o);return i?{mergedPRCount:i.mergedPRCount,closedWithoutMergeCount:i.closedWithoutMergeCount,avgResponseDays:i.avgResponseDays??null}:void 0}}),s=_s(e.vettingResult?.linkedPR);return{issue:{repo:e.issue.repo,repoUrl:`https://github.com/${e.issue.repo}`,number:e.issue.number,title:e.issue.title,url:e.issue.url,labels:e.issue.labels},recommendation:ks(e.recommendation,n),reasonsToApprove:e.reasonsToApprove,reasonsToSkip:e.reasonsToSkip,searchPriority:e.searchPriority,viabilityScore:cK(e.viabilityScore),grade:n,repoScore:r?{score:r.score,mergedPRCount:r.mergedPRCount,closedWithoutMergeCount:r.closedWithoutMergeCount,isResponsive:r.signals?.isResponsive??!1,lastMergedAt:r.lastMergedAt}:void 0,...s&&{linkedPR:s},horizon:e.horizon}}async function uK(e){let r=await(await vs()).features({count:e.maxResults,anchorThreshold:e.anchorThreshold,splitRatio:e.splitRatio}),n=L();return{quickWins:r.quickWins.map(o=>EL(o,n)),biggerBets:r.biggerBets.map(o=>EL(o,n)),anchorRepos:r.anchorRepos,message:r.message}}var iK,aK,TL=A(()=>{"use strict";Ha();le();Rl();ce();iK="features",aK=100});var $L={};re($L,{runVet:()=>lK});async function lK(e){Ze(e.issueUrl),Qe(e.issueUrl,dr,"issue");let r=await(await vs()).vetIssue(e.issueUrl),n=Cs({repo:r.issue.repo,projectHealth:r.projectHealth,getRepoScore:d=>L().getRepoScore(d)}),s=L().getState().config.githubUsername,o=ms({linkedPR:Lo(r.vettingResult.linkedPR),userLogin:s}),i=_s(r.vettingResult.linkedPR),a={issue:{repo:r.issue.repo,number:r.issue.number,title:r.issue.title,url:r.issue.url,labels:r.issue.labels},recommendation:ks(r.recommendation,n),reasonsToApprove:r.reasonsToApprove,reasonsToSkip:r.reasonsToSkip,projectHealth:r.projectHealth,vettingResult:r.vettingResult,antiLLMPolicy:r.antiLLMPolicy,linkedPRClassification:o,...i&&{linkedPR:i},slmTriage:r.slmTriage??null,grade:n,...Gf(L().getState(),r.issue.repo)},c=Gi(L().getState().workClaims??[],e.issueUrl);if(c)return{...a,...c,reasonsToSkip:[...a.reasonsToSkip,...c.reasonsToSkip]};let u=await dK(a);return{...a,...await _a(L(),u?[u]:[])}}async function dK(e){if(e.linkedPRClassification?.startsWith("user_"))return;let{repo:t,number:r,url:n}=e.issue,[s,o]=t.split("/",2),i;try{i=await yo(be(ke()),{repo:o,owner:s,number:r})}catch(a){v("vet",`Could not verify ${n} for pick traits: ${I(a)}`)}if(!(i&&ba.has(i.verdict)))return wa(e,"vet",{...i&&Ra(i),firstInRepo:Sa(t,L().getRepoScore(t),L().getState().mergedPRs)})}var OL=A(()=>{"use strict";Ha();Ot();Rl();xa();le()});var IL={};re(IL,{runVerifyIssue:()=>pK});async function pK(e){Ze(e.issueUrl),Qe(e.issueUrl,dr,"issue");let t=q(e.issueUrl);if(!t||t.type!=="issues")throw new j(`Not a parseable GitHub issue URL: ${e.issueUrl}`);let r=be(ke());return yo(r,{owner:t.owner,repo:t.repo,number:t.number})}var xL=A(()=>{"use strict";le();ee();Ot()});var FL={};re(FL,{classifyListStatus:()=>LL,extractSkipReason:()=>DL,listStatusFromVerdict:()=>ML,runVetList:()=>yK});function fK(e,t){switch(e){case"issue_closed":return"closed";case"claimed":return"claimed";case"has_linked_pr":return t.linkedPR?.state==="open"&&t.linkedPR.isStalled?"has_stalled_pr":"has_pr";case"score_too_low":case"anti_llm_policy":case"other":return null}}function DL(e){if(typeof e!="object"||e===null)return;let t=e.skipReason;if(typeof t=="string")return mK.has(t)?t:void 0}function LL(e,t){if(t){let r=fK(t,e);if(r)return r}else{let r=e.reasonsToSkip.map(n=>n.toLowerCase());if(r.some(n=>n.includes("closed")))return"closed";if(r.some(n=>n.includes("claimed")||n.includes("assigned")))return"claimed";if(r.some(n=>n.includes("existing pr")||n.includes("linked pr")||n.includes("pull request")))return e.linkedPR?.state==="open"&&e.linkedPR.isStalled?"has_stalled_pr":"has_pr"}return e.recommendation==="approve"||e.recommendation==="needs_review","still_available"}function ML(e){switch(e){case"closed":return"closed";case"own-open-pr":return"own_open_pr";case"taken":return"claimed";case"at-risk":return"at_risk";case"available":return"still_available"}}function gK(e){return{verdict:e.verdict,verdictReason:e.verdictReason,state:e.state,stateReason:e.stateReason,assignees:e.assignees,linkedPRs:e.linkedPRs}}function hK(e){return{issue:{repo:`${e.owner}/${e.repo}`,number:e.number,title:e.title,url:e.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:[e.verdictReason],projectHealth:{},vettingResult:{},grade:eC}}function Xk(e){return e instanceof Error?e.message:String(e)}async function yK(e={}){let t=e.concurrency??5,r=e.issueListPath;if(!r){let R=Eo();if(!R)throw new Error("No issue list found. Provide a path with --path or configure issueListPath in settings.");r=R.path}let n=await Ev({filePath:r}),s=[...n.available,...n.blocked];if(s.length===0)return{results:[],summary:{total:0,stillAvailable:0,claimed:0,closed:0,hasPR:0,hasStalledPR:0,atRisk:0,ownOpenPr:0,errors:0}};let o=be(ke()),i=[];s.forEach((R,P)=>{let C=q(R.url);C&&C.type==="issues"&&i.push({index:P,params:{owner:C.owner,repo:C.repo,number:C.number}})});let a=await Xm(o,i.map(R=>R.params),{concurrency:t}),c=new Map;i.forEach((R,P)=>c.set(R.index,a[P]));let u=await vs(),d=[];async function p(R,P){let C=await u.vetIssue(R.url),E=Cs({repo:C.issue.repo,projectHealth:C.projectHealth,getRepoScore:ve=>L().getRepoScore(ve)}),T=L().getState().config.githubUsername,M=ms({linkedPR:Lo(C.vettingResult.linkedPR),userLogin:T}),G=_s(C.vettingResult.linkedPR),X={issue:{repo:C.issue.repo,number:C.issue.number,title:C.issue.title,url:C.issue.url,labels:C.issue.labels},recommendation:ks(C.recommendation,E),reasonsToApprove:C.reasonsToApprove,reasonsToSkip:C.reasonsToSkip,projectHealth:C.projectHealth,vettingResult:C.vettingResult,antiLLMPolicy:C.antiLLMPolicy,linkedPRClassification:M,...G&&{linkedPR:G},slmTriage:C.slmTriage??null,grade:E,...Gf(L().getState(),C.issue.repo)};if(P){let ve=wa(X,"vet-list",{...Ra(P),firstInRepo:Sa(C.issue.repo,L().getRepoScore(C.issue.repo),L().getState().mergedPRs)});ve&&d.push(ve)}return{vetResult:X,skipReason:DL(C)}}function m(R,P){let C=Xk(P);return{issue:{repo:R.repo,number:R.number,title:R.title,url:R.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:[`Error: ${C}`],projectHealth:{},vettingResult:{},grade:eC,listStatus:"error",errorMessage:C}}async function f(R,P){let C=Gi(L().getState().workClaims??[],R.url);if(C)return{issue:{repo:R.repo,number:R.number,title:R.title,url:R.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:C.reasonsToSkip,projectHealth:{},vettingResult:{},grade:eC,listStatus:"claimed",workClaim:C.workClaim};if(!P||P.verification===void 0){let G=P?.error;if(G instanceof j)return{...m(R,G),verifyError:Xk(G)};let X={verifyError:G===void 0?`not verified: ${R.url} is not a verifiable issue URL`:Xk(G)};try{let{vetResult:ve,skipReason:he}=await p(R);return{...ve,listStatus:LL(ve,he),...X}}catch(ve){return{...m(R,ve),...X}}}let E=P.verification,T=gK(E),M=ML(E.verdict);if(ba.has(E.verdict))return{...hK(E),listStatus:M,verification:T};try{let{vetResult:G}=await p(R,E);return{...G,listStatus:M,verification:T}}catch(G){return{...m(R,G),verification:T}}}let g=new Array(s.length),h=0;async function b(){for(;h<s.length;){let R=h++;g[R]=await f(s[R],c.get(R))}}let w=Array.from({length:Math.min(t,s.length)},()=>b());await Promise.all(w);let y=await _a(L(),d),S={total:g.length,stillAvailable:g.filter(R=>R.listStatus==="still_available").length,claimed:g.filter(R=>R.listStatus==="claimed").length,closed:g.filter(R=>R.listStatus==="closed").length,hasPR:g.filter(R=>R.listStatus==="has_pr").length,hasStalledPR:g.filter(R=>R.listStatus==="has_stalled_pr").length,atRisk:g.filter(R=>R.listStatus==="at_risk").length,ownOpenPr:g.filter(R=>R.listStatus==="own_open_pr").length,errors:g.filter(R=>R.listStatus==="error").length},k;if(e.prune&&r)try{let R=yg.readFileSync(r,"utf8"),{pruned:P,removedCount:C}=Pv(R);P!==R&&yg.writeFileSync(r,P,"utf8"),k={removedCount:C}}catch(R){let P=R instanceof Error?R.message:String(R);console.error(`Warning: Failed to prune ${r}: ${P}`),k={removedCount:0,error:P}}return{results:g,summary:S,pruneResult:k,...y}}var yg,eC,mK,NL=A(()=>{"use strict";yg=B(require("node:fs"),1);Ha();Po();sl();Rl();xa();ee();le();eC=Yk({avgResponseDays:null,mergeRate:null,daysSinceLastCommit:null}),mK=new Set(["issue_closed","has_linked_pr","claimed","score_too_low","anti_llm_policy","other"])});var WL={};re(WL,{runLedgerBackfill:()=>$K});function jL(e){let t=(e.firstComments?.nodes??[]).filter(n=>n!==null).map(n=>({user:UL(n.author),author_association:n.authorAssociation,created_at:n.createdAt})),r=(e.reviews?.nodes??[]).filter(n=>n!==null).map(n=>({user:UL(n.author),submitted_at:n.submittedAt}));return e.author?.login?Em(t,r,e.author.login):void 0}async function vK(e,t,r){return(await e.graphql(SK,{o:t.owner,r:t.repo,n:t.number,c:r.firstComments?.pageInfo?.endCursor??null,rc:r.reviews?.pageInfo?.endCursor??null})).repository?.pullRequest}async function kK(e,t,r,n){let s=q(t),o=jL(r);for(let i=1;!o&&s&&i<wK&&_K(r);i++){let a;try{a=await vK(e,s,r)}catch(c){if(de(c)||ua(c))throw c;return n.push(`response lookup for ${t} failed: ${I(c)}`),{isPending:!0}}if(!a)return{isPending:!0};r.firstComments=a.firstComments,r.reviews=a.reviews,o=jL(r)}return{at:o,isPending:!1}}async function CK(e,t,r,n){if(t)for(let[s,o]of t){let{at:i,isPending:a}=await kK(e,s,o,n);a||r.set(s,i)}}function PK(e){let t=0;for(let r of e.values())r&&t++;return t}async function EK(e,t,r){let n=[],s=[],o={};if(t.forEach((u,d)=>{let p=q(u);p&&(n.push(`$o${d}: String!, $r${d}: String!, $n${d}: Int!`),Object.assign(o,{[`o${d}`]:p.owner,[`r${d}`]:p.repo,[`n${d}`]:p.number}),s.push(`p${d}: repository(owner: $o${d}, name: $r${d}) { pullRequest(number: $n${d}) {${RK}} }`))}),s.length===0)return new Map;let i=`query ledgerBackfill(${n.join(", ")}) {
309
309
  ${s.join(`
310
310
  `)}
311
- }`,a;try{a=await e.graphql(i,o)}catch(u){if(de(u)||ua(u))throw u;let d=u.data;if(!d)return r.push(`batch of ${t.length} PRs failed: ${I(u)}`),null;let p=new Map;for(let m of u.errors??[]){let f=m.type??"ERROR";p.set(f,(p.get(f)??0)+1)}r.push(`PRs GitHub did not return: ${[...p].map(([m,f])=>`${m} x${f}`).join(", ")||"unknown"}`),a=d}let c=new Map;return t.forEach((u,d)=>{let p=a[`p${d}`]?.pullRequest;p&&c.set(u,p)}),c}function EK(e,t){let r=qa.dirname(e),n=qa.basename(e,".md");return Va.readdirSync(r).filter(s=>s.startsWith(n)&&s.endsWith(".md")).sort().flatMap(s=>{let o=qa.join(r,s);try{return[{file:o,content:Va.readFileSync(o,"utf8")}]}catch(i){return t.push(`skipped list file ${o}: ${I(i)}`),[]}})}function AK(e,t){for(let{content:r}of e){let n=wv(r,t);if(!n?.includes("/issues/"))continue;let s=tn(r),o=[...s.available,...s.completed,...s.blocked].find(i=>i.url===n&&i.score!==void 0);if(o?.score!==void 0){let i=o.score>=yK?"approve":"skip";return{issueUrl:n,grade:o.score,recommendation:i,source:"list"}}}}function BL(e){return{openedAt:e.filter(t=>t.openedAt).length,issueUrl:e.filter(t=>t.issueUrl).length,closeReason:e.filter(t=>"closeReason"in t&&t.closeReason).length,pick:e.filter(t=>t.pick).length}}async function TK(e={}){let t=L(),r=[];if(e.issueListPath&&!Va.existsSync(e.issueListPath))throw new Error(`Issue list not found: ${e.issueListPath}`);let n=e.issueListPath??hs()?.path;n||r.push("no curated issue list found; list vet scores were not imported");let s=n?EK(n,r):[],o=[...t.getMergedPRs().filter(y=>!y.backfilledAt||zL(y)),...t.getClosedPRs().filter(y=>!y.backfilledAt||zL(y)||y.closeReason==="self-closed"&&!y.selfCloseReason)].map(y=>y.url),i=new Map,a=new Map,c;if(o.length>0){let y=be(ke()),S=0;for(let k=0;k<o.length;k+=tC)try{let R=await PK(y,o.slice(k,k+tC),r);R||S++;for(let[P,C]of R??[])i.set(P,C);await kK(y,R,a,r)}catch(R){c=R;break}if(!c&&S===Math.ceil(o.length/tC))throw new Error(`Every GitHub batch failed: ${r.join("; ")}`)}t.reloadIfChanged();let u=t.getMergedPRs(),d=t.getClosedPRs(),p=BL([...u,...d]),m=y=>y&&t.getPickSnapshots().some(S=>S.issueUrl.toLowerCase()===y.toLowerCase()),f=new Date().toISOString(),g=y=>{let S=i.get(y.url),k=y.pick?void 0:AK(s,y.url),R=S?.closingIssuesReferences?.nodes[0]?.url??y.pick?.issueUrl??k?.issueUrl,P=k&&k.issueUrl===R&&!m(R)?k:void 0;return{openedAt:S?.createdAt,issueUrl:R,pick:P,...S&&{backfilledAt:f}}},h=()=>{t.addMergedPRs(u.map(y=>({url:y.url,title:y.title,mergedAt:y.mergedAt,...g(y)}))),t.addClosedPRs(d.map(y=>{let S=i.get(y.url),k=S?.timelineItems?.nodes.at(-1),R=k?{author:S?.author?.login,closer:k.actor?.login,closerIsBot:k.actor?.__typename==="Bot",comments:(S?.comments?.nodes??[]).flatMap(E=>E?[{author:E.author?.login,isBot:E.author?.__typename==="Bot",body:E.body}]:[])}:void 0,P=R&&CA(R),C=R&&(y.closeReason??P)==="self-closed"?kA(R):void 0;return{url:y.url,title:y.title,closedAt:y.closedAt,...g(y),closeReason:P,selfCloseReason:C}}));for(let[y,S]of a)t.setLedgerResponse(y,S,Eu)};t.batch(h);let b=BL([...t.getMergedPRs(),...t.getClosedPRs()]),w=await we(t,"ledger-backfill",()=>t.batch(h));if(c)throw c;return{queried:o.length,filled:{openedAt:b.openedAt-p.openedAt,issueUrl:b.issueUrl-p.issueUrl,closeReason:b.closeReason-p.closeReason,pick:b.pick-p.pick,firstMaintainerResponseAt:CK(a)},listFiles:s.map(y=>y.file),unresolved:o.length-i.size,warnings:r,...w&&{gistSyncWarning:w}}}var Va,qa,tC,yK,GL,bK,HL,wK,RK,UL,SK,zL,VL=A(()=>{"use strict";Va=B(require("node:fs"),1),qa=B(require("node:path"),1);wS();ee();le();Am();Au();os();Ea();Rv();Po();tC=40,yK=6,GL=10,bK=5,HL=e=>`
311
+ }`,a;try{a=await e.graphql(i,o)}catch(u){if(de(u)||ua(u))throw u;let d=u.data;if(!d)return r.push(`batch of ${t.length} PRs failed: ${I(u)}`),null;let p=new Map;for(let m of u.errors??[]){let f=m.type??"ERROR";p.set(f,(p.get(f)??0)+1)}r.push(`PRs GitHub did not return: ${[...p].map(([m,f])=>`${m} x${f}`).join(", ")||"unknown"}`),a=d}let c=new Map;return t.forEach((u,d)=>{let p=a[`p${d}`]?.pullRequest;p&&c.set(u,p)}),c}function AK(e,t){let r=qa.dirname(e),n=qa.basename(e,".md");return Va.readdirSync(r).filter(s=>s.startsWith(n)&&s.endsWith(".md")).sort().flatMap(s=>{let o=qa.join(r,s);try{return[{file:o,content:Va.readFileSync(o,"utf8")}]}catch(i){return t.push(`skipped list file ${o}: ${I(i)}`),[]}})}function TK(e,t){for(let{content:r}of e){let n=wv(r,t);if(!n?.includes("/issues/"))continue;let s=tn(r),o=[...s.available,...s.completed,...s.blocked].find(i=>i.url===n&&i.score!==void 0);if(o?.score!==void 0){let i=o.score>=bK?"approve":"skip";return{issueUrl:n,grade:o.score,recommendation:i,source:"list"}}}}function BL(e){return{openedAt:e.filter(t=>t.openedAt).length,issueUrl:e.filter(t=>t.issueUrl).length,closeReason:e.filter(t=>"closeReason"in t&&t.closeReason).length,pick:e.filter(t=>t.pick).length}}async function $K(e={}){let t=L(),r=[];if(e.issueListPath&&!Va.existsSync(e.issueListPath))throw new Error(`Issue list not found: ${e.issueListPath}`);let n=e.issueListPath??hs()?.path;n||r.push("no curated issue list found; list vet scores were not imported");let s=n?AK(n,r):[],o=[...t.getMergedPRs().filter(y=>!y.backfilledAt||zL(y)),...t.getClosedPRs().filter(y=>!y.backfilledAt||zL(y)||y.closeReason==="self-closed"&&!y.selfCloseReason)].map(y=>y.url),i=new Map,a=new Map,c;if(o.length>0){let y=be(ke()),S=0;for(let k=0;k<o.length;k+=tC)try{let R=await EK(y,o.slice(k,k+tC),r);R||S++;for(let[P,C]of R??[])i.set(P,C);await CK(y,R,a,r)}catch(R){c=R;break}if(!c&&S===Math.ceil(o.length/tC))throw new Error(`Every GitHub batch failed: ${r.join("; ")}`)}t.reloadIfChanged();let u=t.getMergedPRs(),d=t.getClosedPRs(),p=BL([...u,...d]),m=y=>y&&t.getPickSnapshots().some(S=>S.issueUrl.toLowerCase()===y.toLowerCase()),f=new Date().toISOString(),g=y=>{let S=i.get(y.url),k=y.pick?void 0:TK(s,y.url),R=S?.closingIssuesReferences?.nodes[0]?.url??y.pick?.issueUrl??k?.issueUrl,P=k&&k.issueUrl===R&&!m(R)?k:void 0;return{openedAt:S?.createdAt,issueUrl:R,pick:P,...S&&{backfilledAt:f}}},h=()=>{t.addMergedPRs(u.map(y=>({url:y.url,title:y.title,mergedAt:y.mergedAt,...g(y)}))),t.addClosedPRs(d.map(y=>{let S=i.get(y.url),k=S?.timelineItems?.nodes.at(-1),R=k?{author:S?.author?.login,closer:k.actor?.login,closerIsBot:k.actor?.__typename==="Bot",comments:(S?.comments?.nodes??[]).flatMap(E=>E?[{author:E.author?.login,isBot:E.author?.__typename==="Bot",body:E.body}]:[])}:void 0,P=R&&CA(R),C=R&&(y.closeReason??P)==="self-closed"?kA(R):void 0;return{url:y.url,title:y.title,closedAt:y.closedAt,...g(y),closeReason:P,selfCloseReason:C}}));for(let[y,S]of a)t.setLedgerResponse(y,S,Eu)};t.batch(h);let b=BL([...t.getMergedPRs(),...t.getClosedPRs()]),w=await we(t,"ledger-backfill",()=>t.batch(h));if(c)throw c;return{queried:o.length,filled:{openedAt:b.openedAt-p.openedAt,issueUrl:b.issueUrl-p.issueUrl,closeReason:b.closeReason-p.closeReason,pick:b.pick-p.pick,firstMaintainerResponseAt:PK(a)},listFiles:s.map(y=>y.file),unresolved:o.length-i.size,warnings:r,...w&&{gistSyncWarning:w}}}var Va,qa,tC,bK,GL,wK,HL,RK,SK,UL,_K,zL,VL=A(()=>{"use strict";Va=B(require("node:fs"),1),qa=B(require("node:path"),1);wS();ee();le();Am();Au();os();Ea();Rv();Po();tC=40,bK=6,GL=10,wK=5,HL=e=>`
312
312
  firstComments: comments(first: ${GL}${e?", after: $c":""}) {
313
313
  pageInfo { hasNextPage endCursor } nodes { author { __typename login } authorAssociation createdAt } }
314
314
  reviews(first: ${GL}${e?", after: $rc":""}) {
315
- pageInfo { hasNextPage endCursor } nodes { author { __typename login } submittedAt } }`,wK=`
315
+ pageInfo { hasNextPage endCursor } nodes { author { __typename login } submittedAt } }`,RK=`
316
316
  createdAt
317
317
  author { __typename login }
318
318
  closingIssuesReferences(first: 1) { nodes { url } }
319
319
  timelineItems(itemTypes: [CLOSED_EVENT], last: 1) { nodes { ... on ClosedEvent { actor { __typename login } } } }
320
- comments(last: 5) { nodes { author { __typename login } body } }${HL(!1)}`,RK=`query($o: String!, $r: String!, $n: Int!, $c: String, $rc: String) {
321
- repository(owner: $o, name: $r) { pullRequest(number: $n) {${HL(!0)}} } }`,UL=e=>e?{login:e.login,type:e.__typename}:null;SK=e=>!!(e.firstComments?.pageInfo?.hasNextPage||e.reviews?.pageInfo?.hasNextPage);zL=e=>e.responseRule!==Eu});function qL(e){return e.split("/").slice(3,5).join("/")}function ZL(e,t){if(!e||!t)return;let r=Date.parse(t)-Date.parse(e);return Number.isFinite(r)&&r>=0?r/36e5:void 0}function KL(e){if(e.length===0)return null;let t=[...e].sort((s,o)=>s-o),r=Math.floor(t.length/2),n=t.length%2?t[r]:(t[r-1]+t[r])/2;return Math.round(n*10)/10}function _l(e,t){return t===0?null:Math.round(e/t*100)/100}function bg(e,t){let r=s=>t.filter(o=>o.outcome===s).length,n=r("merged");return{key:e,n:t.length,merged:n,closed:r("closed"),dormant:r("dormant"),mergeRate:_l(n,t.length),medianHoursToMerge:KL(t.flatMap(s=>s.hoursToMerge===void 0?[]:[s.hoursToMerge])),medianHoursToFirstResponse:KL(t.flatMap(s=>s.hoursToFirstResponse===void 0?[]:[s.hoursToFirstResponse]))}}function Za(e,t,r=[]){let n=new Map(r.map(s=>[s,[]]));for(let s of e){let o=t(s);n.has(o)||n.set(o,[]),n.get(o).push(s)}return[...n].filter(([,s])=>s.length>0).map(([s,o])=>bg(s,o))}function $K(e){return e===void 0?"none":e<=4?"1-4":e<=6?"5-6":e<=8?"7-8":"9-10"}function OK(e){return e===void 0?"unknown":e<100?"<100":e<1e3?"100-1k":e<1e4?"1k-10k":"10k+"}function DK(e){if(e.issueAuthorIsBot)return"bot";let t=e.issueAuthorAssociation;return t===void 0?wg:IK.has(t)?"maintainer":t==="CONTRIBUTOR"?"contributor":xK.has(t)?"outsider":"unknown"}function LK(e){let t=e.map(n=>n.toLowerCase()),r=YL.filter(([,n])=>t.some(s=>n.test(s))).map(([n])=>n);return r.length>0?r:[QL]}function MK(e){let t=u=>e.repoScores[u]?.stargazersCount,r=new Map,n=e.mergedPRs??[];for(let u of n){let d=qL(u.url).toLowerCase();r.set(d,[...r.get(d)??[],Date.parse(u.mergedAt)])}let s=(u,d)=>(r.get(u.toLowerCase())??[]).every(p=>p>=d),o=(u,d)=>{let p=qL(u.url);return{url:u.url,repo:p,issueUrl:u.issueUrl,firstInRepo:u.pick?.firstInRepo??s(p,Date.parse(u.openedAt??d)),pick:u.pick,grade:u.pick?.grade,gradeSource:u.pick?u.pick.source==="list"?"list":"vet":void 0,stars:u.pick?.stargazersCount??t(p),hoursToFirstResponse:ZL(u.openedAt,u.firstMaintainerResponseAt),changesRequested:u.lastReviewDecision?u.lastReviewDecision==="changes_requested":void 0,ciFailing:u.lastCiStatus?u.lastCiStatus==="failing":void 0}},i=(e.mergedPRs??[]).map(u=>({...o(u,u.mergedAt),outcome:"merged",month:u.mergedAt.slice(0,7),hoursToMerge:ZL(u.openedAt,u.mergedAt)})),a=(e.closedPRs??[]).map(u=>({...o(u,u.closedAt),outcome:"closed",month:u.closedAt.slice(0,7),closeReason:u.closeReason,selfCloseReason:u.selfCloseReason})),c=(e.lastDigest?.openPRs??[]).filter(u=>u.stalenessTier==="dormant").map(u=>({url:u.url,repo:u.repo,outcome:"dormant",stars:t(u.repo),firstInRepo:s(u.repo,Date.parse(u.createdAt))}));return[...i,...a,...c]}function XL(e,t=new Date){let r=MK(e),n=r.filter(y=>y.gradeSource==="vet"&&y.outcome!=="dormant"),s=n.filter(y=>y.grade>=7),o=n.filter(y=>y.grade<=5),i=y=>y.filter(S=>S.outcome==="merged").length/y.length,c=s.length>=5&&o.length>=5?Math.round((i(s)-i(o))*100)/100:null,u=r.filter(y=>y.outcome==="closed"),d={},p={};for(let y of u){let S=y.selfCloseReason?`self-closed: ${y.selfCloseReason}`:y.closeReason??"unclassified";d[S]=(d[S]??0)+1,(y.closeReason==="ai-policy"||y.closeReason==="rejected")&&y.month&&(p[y.month]=(p[y.month]??0)+1)}let m=r.filter(y=>y.pick),f=r.filter(y=>y.issueUrl&&y.outcome!=="dormant"),g=r.filter(y=>y.changesRequested!==void 0),h=r.filter(y=>y.ciFailing!==void 0),b=Za(r,y=>y.gradeSource?`${y.gradeSource} ${$K(y.grade)}`:"no prediction",["vet 9-10","vet 7-8","vet 5-6","vet 1-4","list 9-10","list 7-8","list 5-6","list 1-4","no prediction"]),w=b.filter(y=>/(?:9-10|7-8)$/.test(y.key)&&y.n>=5&&(y.mergeRate??1)<.6).map(y=>`${y.key}: high-grade picks merge at ${Math.round(y.mergeRate*100)}% (n=${y.n})`);return c!==null&&c<=0&&w.push(`vet grades do not separate outcomes: grade>=7 merges at ${No(_l(s.filter(y=>y.outcome==="merged").length,s.length))} (n=${s.length}), grade<=5 at ${No(_l(o.filter(y=>y.outcome==="merged").length,o.length))} (n=${o.length})`),{generatedAt:t.toISOString(),totals:bg("all",r),headlines:{mergeRate1kStars:bg(">=1k stars",r.filter(y=>(y.stars??0)>=1e3)),calibration:{gap:c,highN:s.length,lowN:o.length},vetCoverage:{graded:f.filter(y=>y.gradeSource==="vet").length,of:f.length},approachClosuresByMonth:p},byGrade:b,byStars:Za(r,y=>OK(y.stars),["10k+","1k-10k","100-1k","<100","unknown"]),byMonth:Za(r.filter(y=>y.month),y=>y.month).sort((y,S)=>S.key.localeCompare(y.key)),byFirstInRepo:Za(r,y=>y.firstInRepo?"first in repo":"returning",["first in repo","returning"]),byIssueAuthorRole:Za(m,y=>DK(y.pick),["maintainer","contributor","outsider","bot","unknown",wg]),byCompetingPRs:Za(m,y=>{let S=y.pick.competingPRs;return S===void 0?wg:S===0?"0":"1+"},["0","1+",wg]),byLabel:[...YL.map(([y])=>y),QL].map(y=>bg(y,m.filter(S=>S.pick.labels&&LK(S.pick.labels).includes(y)))).filter(y=>y.n>0),closeReasons:d,quality:{withReviewState:g.length,changesRequestedShare:_l(g.filter(y=>y.changesRequested).length,g.length),ciFailingShare:_l(h.filter(y=>y.ciFailing).length,h.length)},calibrationPairs:n.length,flags:w}}function Fo(e,t){return[`## ${e}`,"","| Bucket | n | Merged | Closed | Dormant | Merge rate | Median to merge | Median to first response |","|---|---|---|---|---|---|---|---|",...t.map(r=>`| ${r.key} | ${r.n} | ${r.merged} | ${r.closed} | ${r.dormant} | ${No(r.mergeRate)} | ${JL(r.medianHoursToMerge)} | ${JL(r.medianHoursToFirstResponse)} |`),""]}function eM(e){let t=e.headlines,r=Object.keys(t.approachClosuresByMonth).sort().reverse().slice(0,6);return[`# oss-autopilot eval (${e.generatedAt.slice(0,10)})`,"","## Headlines","",`- Merge rate on repos with 1k+ stars: **${No(t.mergeRate1kStars.mergeRate)}** (n=${t.mergeRate1kStars.n})`,`- Calibration gap, vet grades (grade>=7 minus grade<=5 merge rate): **${t.calibration.gap??"n/a"}** (n=${t.calibration.highN} vs ${t.calibration.lowN}; needs 5 each)`,`- Vet grade recorded at pick: **${t.vetCoverage.graded} of ${t.vetCoverage.of}** merged or closed PRs that close an issue`,`- Approach or AI-policy closures by month: ${r.length?r.map(n=>`${n}: ${t.approachClosuresByMonth[n]}`).join(", "):"none"}`,`- Overall: ${e.totals.n} outcomes, merge rate ${No(e.totals.mergeRate)} (dormant counted as not merged)`,"",...e.flags.length?["## Flags","",...e.flags.map(n=>`- ${n}`),""]:[],...Fo("By grade at pick time",e.byGrade),...Fo("By repo stars",e.byStars),...Fo("By month",e.byMonth.slice(0,12)),...Fo("First PR in repo vs returning",e.byFirstInRepo),...Fo("By issue author (picks)",e.byIssueAuthorRole),...Fo("By competing PRs at pick time (picks)",e.byCompetingPRs),...Fo("By issue label (picks; one pick can match several)",e.byLabel),"## Close reasons","",...Object.entries(e.closeReasons).sort((n,s)=>s[1]-n[1]).map(([n,s])=>`- ${n}: ${s}`),"","## Review quality","",`- PRs with a recorded review state: ${e.quality.withReviewState}`,`- Changes requested before the outcome: ${No(e.quality.changesRequestedShare)}`,`- CI failing at last sight: ${No(e.quality.ciFailingShare)}`,""].join(`
322
- `)}var Sl,YL,IK,xK,QL,wg,No,JL,tM=A(()=>{"use strict";Sl=e=>new RegExp(`(?:^|[^a-z])(?:${e})(?![a-z])`),YL=[["good first issue",Sl("good[ _-]?first|beginners?|easy|first.?timers?|starter(?![_-][a-z])")],["help wanted",Sl("help[ _-]?wanted")],["bug",Sl("bugs?")],["enhancement",Sl("enhancements?|features?")],["documentation",Sl("docs?|documentation")]],IK=new Set(["OWNER","MEMBER","COLLABORATOR"]),xK=new Set(["NONE","FIRST_TIMER","FIRST_TIME_CONTRIBUTOR","MANNEQUIN"]);QL="none of these",wg="not recorded";No=e=>e===null?"n/a":`${Math.round(e*100)}%`,JL=e=>e===null?"n/a":`${e}h`});var rM={};re(rM,{runEval:()=>FK});async function FK(){let e=XL(L().getState());return{report:e,markdown:eM(e)}}var nM=A(()=>{"use strict";tM();le()});var sM={};re(sM,{runSkipAdd:()=>jK});function UK(e){return e.toISOString().slice(0,10)}function jK(e){let t=e.skipFilePath??L().getState().config.skippedIssuesPath;if(!t)throw new Error("No skipped-issues path configured. Set one via `oss-autopilot setup --set skippedIssuesPath=<path>` or pass --path.");if(!NK.test(e.issueUrl))throw new Error(`Invalid GitHub issue or PR URL: ${e.issueUrl}`);if(RL(t).some(s=>s.url===e.issueUrl))return{added:!1,alreadyPresent:!0,url:e.issueUrl,path:t};Ka.existsSync(t)||Ka.writeFileSync(t,GK);let n=UK(e.now??new Date);return Ka.appendFileSync(t,`${n} ${e.issueUrl}
323
- `),{added:!0,alreadyPresent:!1,url:e.issueUrl,path:t,date:n}}var Ka,NK,GK,oM=A(()=>{"use strict";Ka=B(require("node:fs"),1);Jk();le();NK=/^https:\/\/github\.com\/([^/]+\/[^/]+)\/(?:issues|pull)\/(\d+)(?:[#/?].*)?$/,GK=`# Skipped Issues \u2014 permanent
320
+ comments(last: 5) { nodes { author { __typename login } body } }${HL(!1)}`,SK=`query($o: String!, $r: String!, $n: Int!, $c: String, $rc: String) {
321
+ repository(owner: $o, name: $r) { pullRequest(number: $n) {${HL(!0)}} } }`,UL=e=>e?{login:e.login,type:e.__typename}:null;_K=e=>!!(e.firstComments?.pageInfo?.hasNextPage||e.reviews?.pageInfo?.hasNextPage);zL=e=>e.responseRule!==Eu});function qL(e){return e.split("/").slice(3,5).join("/")}function ZL(e,t){if(!e||!t)return;let r=Date.parse(t)-Date.parse(e);return Number.isFinite(r)&&r>=0?r/36e5:void 0}function KL(e){if(e.length===0)return null;let t=[...e].sort((s,o)=>s-o),r=Math.floor(t.length/2),n=t.length%2?t[r]:(t[r-1]+t[r])/2;return Math.round(n*10)/10}function _l(e,t){return t===0?null:Math.round(e/t*100)/100}function bg(e,t){let r=s=>t.filter(o=>o.outcome===s).length,n=r("merged");return{key:e,n:t.length,merged:n,closed:r("closed"),dormant:r("dormant"),mergeRate:_l(n,t.length),medianHoursToMerge:KL(t.flatMap(s=>s.hoursToMerge===void 0?[]:[s.hoursToMerge])),medianHoursToFirstResponse:KL(t.flatMap(s=>s.hoursToFirstResponse===void 0?[]:[s.hoursToFirstResponse]))}}function Za(e,t,r=[]){let n=new Map(r.map(s=>[s,[]]));for(let s of e){let o=t(s);n.has(o)||n.set(o,[]),n.get(o).push(s)}return[...n].filter(([,s])=>s.length>0).map(([s,o])=>bg(s,o))}function OK(e){return e===void 0?"none":e<=4?"1-4":e<=6?"5-6":e<=8?"7-8":"9-10"}function IK(e){return e===void 0?"unknown":e<100?"<100":e<1e3?"100-1k":e<1e4?"1k-10k":"10k+"}function LK(e){if(e.issueAuthorIsBot)return"bot";let t=e.issueAuthorAssociation;return t===void 0?wg:xK.has(t)?"maintainer":t==="CONTRIBUTOR"?"contributor":DK.has(t)?"outsider":"unknown"}function MK(e){let t=e.map(n=>n.toLowerCase()),r=YL.filter(([,n])=>t.some(s=>n.test(s))).map(([n])=>n);return r.length>0?r:[QL]}function FK(e){let t=u=>e.repoScores[u]?.stargazersCount,r=new Map,n=e.mergedPRs??[];for(let u of n){let d=qL(u.url).toLowerCase();r.set(d,[...r.get(d)??[],Date.parse(u.mergedAt)])}let s=(u,d)=>(r.get(u.toLowerCase())??[]).every(p=>p>=d),o=(u,d)=>{let p=qL(u.url);return{url:u.url,repo:p,issueUrl:u.issueUrl,firstInRepo:u.pick?.firstInRepo??s(p,Date.parse(u.openedAt??d)),pick:u.pick,grade:u.pick?.grade,gradeSource:u.pick?u.pick.source==="list"?"list":"vet":void 0,stars:u.pick?.stargazersCount??t(p),hoursToFirstResponse:ZL(u.openedAt,u.firstMaintainerResponseAt),changesRequested:u.lastReviewDecision?u.lastReviewDecision==="changes_requested":void 0,ciFailing:u.lastCiStatus?u.lastCiStatus==="failing":void 0}},i=(e.mergedPRs??[]).map(u=>({...o(u,u.mergedAt),outcome:"merged",month:u.mergedAt.slice(0,7),hoursToMerge:ZL(u.openedAt,u.mergedAt)})),a=(e.closedPRs??[]).map(u=>({...o(u,u.closedAt),outcome:"closed",month:u.closedAt.slice(0,7),closeReason:u.closeReason,selfCloseReason:u.selfCloseReason})),c=(e.lastDigest?.openPRs??[]).filter(u=>u.stalenessTier==="dormant").map(u=>({url:u.url,repo:u.repo,outcome:"dormant",stars:t(u.repo),firstInRepo:s(u.repo,Date.parse(u.createdAt))}));return[...i,...a,...c]}function XL(e,t=new Date){let r=FK(e),n=r.filter(y=>y.gradeSource==="vet"&&y.outcome!=="dormant"),s=n.filter(y=>y.grade>=7),o=n.filter(y=>y.grade<=5),i=y=>y.filter(S=>S.outcome==="merged").length/y.length,c=s.length>=5&&o.length>=5?Math.round((i(s)-i(o))*100)/100:null,u=r.filter(y=>y.outcome==="closed"),d={},p={};for(let y of u){let S=y.selfCloseReason?`self-closed: ${y.selfCloseReason}`:y.closeReason??"unclassified";d[S]=(d[S]??0)+1,(y.closeReason==="ai-policy"||y.closeReason==="rejected")&&y.month&&(p[y.month]=(p[y.month]??0)+1)}let m=r.filter(y=>y.pick),f=r.filter(y=>y.issueUrl&&y.outcome!=="dormant"),g=r.filter(y=>y.changesRequested!==void 0),h=r.filter(y=>y.ciFailing!==void 0),b=Za(r,y=>y.gradeSource?`${y.gradeSource} ${OK(y.grade)}`:"no prediction",["vet 9-10","vet 7-8","vet 5-6","vet 1-4","list 9-10","list 7-8","list 5-6","list 1-4","no prediction"]),w=b.filter(y=>/(?:9-10|7-8)$/.test(y.key)&&y.n>=5&&(y.mergeRate??1)<.6).map(y=>`${y.key}: high-grade picks merge at ${Math.round(y.mergeRate*100)}% (n=${y.n})`);return c!==null&&c<=0&&w.push(`vet grades do not separate outcomes: grade>=7 merges at ${No(_l(s.filter(y=>y.outcome==="merged").length,s.length))} (n=${s.length}), grade<=5 at ${No(_l(o.filter(y=>y.outcome==="merged").length,o.length))} (n=${o.length})`),{generatedAt:t.toISOString(),totals:bg("all",r),headlines:{mergeRate1kStars:bg(">=1k stars",r.filter(y=>(y.stars??0)>=1e3)),calibration:{gap:c,highN:s.length,lowN:o.length},vetCoverage:{graded:f.filter(y=>y.gradeSource==="vet").length,of:f.length},approachClosuresByMonth:p},byGrade:b,byStars:Za(r,y=>IK(y.stars),["10k+","1k-10k","100-1k","<100","unknown"]),byMonth:Za(r.filter(y=>y.month),y=>y.month).sort((y,S)=>S.key.localeCompare(y.key)),byFirstInRepo:Za(r,y=>y.firstInRepo?"first in repo":"returning",["first in repo","returning"]),byIssueAuthorRole:Za(m,y=>LK(y.pick),["maintainer","contributor","outsider","bot","unknown",wg]),byCompetingPRs:Za(m,y=>{let S=y.pick.competingPRs;return S===void 0?wg:S===0?"0":"1+"},["0","1+",wg]),byLabel:[...YL.map(([y])=>y),QL].map(y=>bg(y,m.filter(S=>S.pick.labels&&MK(S.pick.labels).includes(y)))).filter(y=>y.n>0),closeReasons:d,quality:{withReviewState:g.length,changesRequestedShare:_l(g.filter(y=>y.changesRequested).length,g.length),ciFailingShare:_l(h.filter(y=>y.ciFailing).length,h.length)},calibrationPairs:n.length,flags:w}}function Fo(e,t){return[`## ${e}`,"","| Bucket | n | Merged | Closed | Dormant | Merge rate | Median to merge | Median to first response |","|---|---|---|---|---|---|---|---|",...t.map(r=>`| ${r.key} | ${r.n} | ${r.merged} | ${r.closed} | ${r.dormant} | ${No(r.mergeRate)} | ${JL(r.medianHoursToMerge)} | ${JL(r.medianHoursToFirstResponse)} |`),""]}function eM(e){let t=e.headlines,r=Object.keys(t.approachClosuresByMonth).sort().reverse().slice(0,6);return[`# oss-autopilot eval (${e.generatedAt.slice(0,10)})`,"","## Headlines","",`- Merge rate on repos with 1k+ stars: **${No(t.mergeRate1kStars.mergeRate)}** (n=${t.mergeRate1kStars.n})`,`- Calibration gap, vet grades (grade>=7 minus grade<=5 merge rate): **${t.calibration.gap??"n/a"}** (n=${t.calibration.highN} vs ${t.calibration.lowN}; needs 5 each)`,`- Vet grade recorded at pick: **${t.vetCoverage.graded} of ${t.vetCoverage.of}** merged or closed PRs that close an issue`,`- Approach or AI-policy closures by month: ${r.length?r.map(n=>`${n}: ${t.approachClosuresByMonth[n]}`).join(", "):"none"}`,`- Overall: ${e.totals.n} outcomes, merge rate ${No(e.totals.mergeRate)} (dormant counted as not merged)`,"",...e.flags.length?["## Flags","",...e.flags.map(n=>`- ${n}`),""]:[],...Fo("By grade at pick time",e.byGrade),...Fo("By repo stars",e.byStars),...Fo("By month",e.byMonth.slice(0,12)),...Fo("First PR in repo vs returning",e.byFirstInRepo),...Fo("By issue author (picks)",e.byIssueAuthorRole),...Fo("By competing PRs at pick time (picks)",e.byCompetingPRs),...Fo("By issue label (picks; one pick can match several)",e.byLabel),"## Close reasons","",...Object.entries(e.closeReasons).sort((n,s)=>s[1]-n[1]).map(([n,s])=>`- ${n}: ${s}`),"","## Review quality","",`- PRs with a recorded review state: ${e.quality.withReviewState}`,`- Changes requested before the outcome: ${No(e.quality.changesRequestedShare)}`,`- CI failing at last sight: ${No(e.quality.ciFailingShare)}`,""].join(`
322
+ `)}var Sl,YL,xK,DK,QL,wg,No,JL,tM=A(()=>{"use strict";Sl=e=>new RegExp(`(?:^|[^a-z])(?:${e})(?![a-z])`),YL=[["good first issue",Sl("good[ _-]?first|beginners?|easy|first.?timers?|starter(?![_-][a-z])")],["help wanted",Sl("help[ _-]?wanted")],["bug",Sl("bugs?")],["enhancement",Sl("enhancements?|features?")],["documentation",Sl("docs?|documentation")]],xK=new Set(["OWNER","MEMBER","COLLABORATOR"]),DK=new Set(["NONE","FIRST_TIMER","FIRST_TIME_CONTRIBUTOR","MANNEQUIN"]);QL="none of these",wg="not recorded";No=e=>e===null?"n/a":`${Math.round(e*100)}%`,JL=e=>e===null?"n/a":`${e}h`});var rM={};re(rM,{runEval:()=>NK});async function NK(){let e=XL(L().getState());return{report:e,markdown:eM(e)}}var nM=A(()=>{"use strict";tM();le()});var sM={};re(sM,{runSkipAdd:()=>zK});function jK(e){return e.toISOString().slice(0,10)}function zK(e){let t=e.skipFilePath??L().getState().config.skippedIssuesPath;if(!t)throw new Error("No skipped-issues path configured. Set one via `oss-autopilot setup --set skippedIssuesPath=<path>` or pass --path.");if(!GK.test(e.issueUrl))throw new Error(`Invalid GitHub issue or PR URL: ${e.issueUrl}`);if(RL(t).some(s=>s.url===e.issueUrl))return{added:!1,alreadyPresent:!0,url:e.issueUrl,path:t};Ka.existsSync(t)||Ka.writeFileSync(t,UK);let n=jK(e.now??new Date);return Ka.appendFileSync(t,`${n} ${e.issueUrl}
323
+ `),{added:!0,alreadyPresent:!1,url:e.issueUrl,path:t,date:n}}var Ka,GK,UK,oM=A(()=>{"use strict";Ka=B(require("node:fs"),1);Jk();le();GK=/^https:\/\/github\.com\/([^/]+\/[^/]+)\/(?:issues|pull)\/(\d+)(?:[#/?].*)?$/,UK=`# Skipped Issues \u2014 permanent
324
324
  # Format: YYYY-MM-DD URL
325
325
 
326
- `});var lM={};re(lM,{moveIssueToTier:()=>uM,runListMoveTier:()=>VK});function cM(e){if(e.startsWith("## "))return e.slice(3).trim()}function zK(e,t){for(let r=t-1;r>=0;r--){let n=cM(e[r]);if(n!==void 0)return n;if(e[r].startsWith("# "))return}}function BK(e,t){let r=[];for(let n=0;n<e.length;n++){let s=e[n];if(!So.test(s)||!_o(s,t))continue;let o=n+1;for(;o<e.length&&/^\s{2,}/.test(e[o]);)o++;r.push({start:n,end:o,tier:zK(e,n)}),n=o-1}return r}function HK(e,t){let r=aM[t].toLowerCase();for(let n=0;n<e.length;n++){let s=cM(e[n]);if(s!==void 0&&`## ${s}`.toLowerCase()===r)return n}}function WK(e,t){for(let r=t+1;r<e.length;r++)if(/^#{1,2}\s+/.test(e[r]))return r;return e.length}function uM(e,t,r){let n=e.endsWith(`
326
+ `});var lM={};re(lM,{moveIssueToTier:()=>uM,runListMoveTier:()=>qK});function cM(e){if(e.startsWith("## "))return e.slice(3).trim()}function BK(e,t){for(let r=t-1;r>=0;r--){let n=cM(e[r]);if(n!==void 0)return n;if(e[r].startsWith("# "))return}}function HK(e,t){let r=[];for(let n=0;n<e.length;n++){let s=e[n];if(!So.test(s)||!_o(s,t))continue;let o=n+1;for(;o<e.length&&/^\s{2,}/.test(e[o]);)o++;r.push({start:n,end:o,tier:BK(e,n)}),n=o-1}return r}function WK(e,t){let r=aM[t].toLowerCase();for(let n=0;n<e.length;n++){let s=cM(e[n]);if(s!==void 0&&`## ${s}`.toLowerCase()===r)return n}}function VK(e,t){for(let r=t+1;r<e.length;r++)if(/^#{1,2}\s+/.test(e[r]))return r;return e.length}function uM(e,t,r){let n=e.endsWith(`
327
327
  `),s=(n?e.slice(0,-1):e).split(`
328
- `),o=BK(s,t);if(o.length===0)return{content:e,moved:!1,count:0,reason:"issue URL not found in the list",reasonCode:"not-found"};let i=aM[r];if(o.every(g=>g.tier!==void 0&&`## ${g.tier}`.toLowerCase()===i.toLowerCase()))return{content:e,moved:!1,fromTier:o[0].tier,count:o.length,reason:"already in target tier",reasonCode:"already-in-target"};let a=[...o].sort((g,h)=>h.start-g.start),c=[];for(let g of a)c.push({tier:g.tier,lines:s.slice(g.start,g.end)}),s.splice(g.start,g.end-g.start);c.reverse();let u=HK(s,r);u===void 0&&(s.length>0&&s[s.length-1].trim()!==""&&s.push(""),s.push(i),u=s.length-1,s.push(""));let d=u+1;d<s.length&&s[d].trim()===""&&(d+=1);let p=WK(s,u);d>p&&(d=p);let m=[];for(let g of c)m.push(...g.lines);s.splice(d,0,...m);let f=s.join(`
328
+ `),o=HK(s,t);if(o.length===0)return{content:e,moved:!1,count:0,reason:"issue URL not found in the list",reasonCode:"not-found"};let i=aM[r];if(o.every(g=>g.tier!==void 0&&`## ${g.tier}`.toLowerCase()===i.toLowerCase()))return{content:e,moved:!1,fromTier:o[0].tier,count:o.length,reason:"already in target tier",reasonCode:"already-in-target"};let a=[...o].sort((g,h)=>h.start-g.start),c=[];for(let g of a)c.push({tier:g.tier,lines:s.slice(g.start,g.end)}),s.splice(g.start,g.end-g.start);c.reverse();let u=WK(s,r);u===void 0&&(s.length>0&&s[s.length-1].trim()!==""&&s.push(""),s.push(i),u=s.length-1,s.push(""));let d=u+1;d<s.length&&s[d].trim()===""&&(d+=1);let p=VK(s,u);d>p&&(d=p);let m=[];for(let g of c)m.push(...g.lines);s.splice(d,0,...m);let f=s.join(`
329
329
  `);return n&&(f+=`
330
- `),{content:f,moved:!0,fromTier:c[0].tier,count:c.length}}async function VK(e){let t=iM.resolve(e.listPath);if(!sn.existsSync(t))throw new Error(`File not found: ${t}`);let r;try{r=sn.readFileSync(t,"utf8")}catch(s){throw new Error(`Failed to read file: ${I(s)}`,{cause:s})}let n=uM(r,e.issueUrl,e.tier);if(n.reasonCode==="not-found")throw new j(`Issue URL not found in the list: ${e.issueUrl} (${t}). Add the entry to the list first, then re-run list-move-tier.`);if(n.moved){let s=`${t}.tmp-${process.pid}-${Date.now()}`;try{sn.writeFileSync(s,n.content,"utf8"),sn.renameSync(s,t)}catch(o){try{sn.unlinkSync(s)}catch{}throw new Error(`Failed to write file: ${I(o)}`,{cause:o})}}return{moved:n.moved,filePath:t,url:e.issueUrl,toTier:e.tier,fromTier:n.fromTier,count:n.count,reason:n.reason}}var sn,iM,aM,dM=A(()=>{"use strict";sn=B(require("node:fs"),1),iM=B(require("node:path"),1);ee();gf();aM={pursue:"## Pursue",maybe:"## Maybe",skip:"## Skip"}});var pM={};re(pM,{runTrack:()=>qK});async function qK(e){Ze(e.prUrl),Qe(e.prUrl,tr,"PR");let t=ke(),r=be(t),n=q(e.prUrl);if(!n||n.type!=="pull")throw new j(`Invalid PR URL: ${e.prUrl}`);let{owner:s,repo:o,number:i}=n,{data:a}=await r.pulls.get({owner:s,repo:o,pull_number:i});return{pr:{repo:`${s}/${o}`,number:i,title:a.title,url:e.prUrl}}}var mM=A(()=>{"use strict";le();ee();Ot();nt()});var Rg,Sg,Uoe,rC=A(()=>{"use strict";Rg={passFiles:10,passLines:400,warnFiles:20,warnLines:800},Sg=72,Uoe=[{id:"issueReference",label:"Issue Reference",description:"PR links to issue (`Closes #X` or `Fixes #X`)",tier:"required",weight:25},{id:"description",label:"Description Quality",description:"Explains what changed and why",tier:"required",weight:25},{id:"title",label:"Title Quality",description:"Descriptive, properly formatted (e.g., `fix: resolve login timeout`)",tier:"required",weight:10},{id:"focusedChanges",label:"Focused Changes",description:`One logical change per PR (< ${Rg.passFiles} files, < ${Rg.passLines} lines ideal)`,tier:"required",weight:20},{id:"minimalDiff",label:"Minimal Diff",description:"No unrelated formatting changes (whitespace, quotes, imports, trailing commas)",tier:"required",weight:null},{id:"tests",label:"Tests Included",description:"Only when the change has behavior to guard (bug fix, new logic); never filler",tier:"conditional",weight:15},{id:"docs",label:"Docs Updated",description:"If behavior changed, update docs",tier:"conditional",weight:null},{id:"branch",label:"Branch Naming",description:"Follows convention (`feature/`, `fix/`, `docs/`)",tier:"optional",weight:5},{id:"screenshots",label:"Screenshots",description:"Only for visible changes when the template or a maintainer asks",tier:"optional",weight:null}]});function XK(e,t){if(t.length===0)return null;let r=t.find(a=>a.state==="not_found");if(r){let a=r.crossRepo?`${r.repo}#${r.number}`:`#${r.number}`;return{status:"fail",weight:e,detail:`linked issue ${a} does not exist \u2014 typo or wrong repo?`}}let n=t.filter(a=>a.state!=="unverifiable");if(n.length===0)return{status:"warn",weight:e,detail:`linked issue${t.length>1?"s":""} could not be verified (rate limit or network) \u2014 confirm manually`};let s=n.find(a=>a.state==="closed"&&(a.closedDaysAgo??0)>ZK);if(s)return{status:"fail",weight:e,detail:`linked issue #${s.number} has been closed for ${s.closedDaysAgo} days \u2014 reference is probably stale`};let o=n.find(a=>a.state==="closed");if(o)return{status:"warn",weight:e,detail:`linked issue #${o.number} was closed ${o.closedDaysAgo??"?"} days ago \u2014 confirm this PR is still relevant`};let i=n.find(a=>a.crossRepo);return i?{status:"warn",weight:e,detail:`cross-repo reference ${i.repo}#${i.number} \u2014 verify the linked issue applies to changes in this repo`}:{status:"pass",weight:e,detail:`linked issue${n.length>1?"s":""} verified open`}}function e6(e,t){let r=Ja.issueReference,n=JK.test(e.body);if(!(n||YK.test(e.body)||QK.test(e.body)||(t?.linkedIssues?.length??0)>0))return{status:"fail",weight:r,detail:"no issue reference"};let o=t?.linkedIssues?XK(r,t.linkedIssues):null;return o||(n?{status:"pass",weight:r,detail:"closing keyword present"}:{status:"warn",weight:r,detail:"issue referenced without a closing keyword"})}function s6(e){let t=[],r,n=0;for(let s of e.split(`
331
- `)){let o=/^ {0,3}(`{3,})/.exec(s)?.[1].length??0;o>0&&!r?r={start:n,len:o}:o>0&&r&&o>=r.len&&(t.push([r.start,n+s.length]),r=void 0),n+=s.length+1}return t}function o6(e,t,r){let n=[...e.slice(t,r).matchAll(/`+/g)].map(c=>({start:t+c.index,len:c[0].length})),s=new Map,o=new Map;for(let c=n.length-1;c>=0;c--){let u=o.get(n[c].len);u!==void 0&&s.set(c,u),o.set(n[c].len,c)}let i=[],a=0;for(;a<n.length;){let c=s.get(a);c===void 0?a+=1:(i.push([n[a].start,n[c].start+n[c].len]),a=c+1)}return i}function i6(e){let t=new Uint8Array(e.length),r=s6(e),n=[],s=0;for(let[i,a]of r)n.push([s,i]),s=a;n.push([s,e.length]);let o=n.flatMap(([i,a])=>o6(e,i,a));for(let[i,a]of[...r,...o])t.fill(1,i,a);return t}function a6(e){let t=i6(e),r="",n=!0,s=0;for(;s<e.length;){let o=n&&t[s]===0&&e.startsWith("<!--",s)?e.indexOf("-->",s+4):-1;o===-1?(t[s]===0&&e.startsWith("<!--",s)&&(n=!1),r+=e[s],s+=1):s=o+3}return r.replaceAll(/^ {0,3}#{1,6}[ \t]+[^\n]{0,60}$/gm,o=>/[.!?。]\s*$/.test(o)?o:"").replaceAll(n6,"").trim()}function c6(e){let t=Ja.description;if(e.body.trim().length===0)return{status:"fail",weight:t,detail:"description is empty"};let n=a6(e.body),s=t6.test(e.body)||r6.test(e.body);return n.length>=80||s&&new RegExp("\\p{L}","u").test(n)?{status:"pass",weight:t,detail:"describes the change"}:{status:"warn",weight:t,detail:"short description; say what changed and why"}}function u6(e){let t=Ja.focusedChanges,r=e.additions+e.deletions,n=`${e.filesChangedCount} files, ${r} lines`;return e.filesChangedCount<_g.passFiles&&r<_g.passLines?{status:"pass",weight:t,detail:n}:e.filesChangedCount>_g.warnFiles||r>_g.warnLines?{status:"fail",weight:t,detail:`${n} \u2014 needs splitting`}:{status:"warn",weight:t,detail:n}}function d6(e,t){let r=Ja.tests;return e.files.some(s=>l6.test(s))?{status:"pass",weight:r,detail:"test file(s) touched"}:t?.hasTestInfrastructure===!1?{status:"warn",weight:r,detail:"no tests, but project has no visible test infrastructure"}:{status:"warn",weight:r,detail:"no test files; fine if nothing testable changed, a bug fix needs a regression test"}}function h6(e){let t=e.trim();return!!(m6.has(t.toLowerCase())||f6.test(t)||g6.test(t))}function y6(e){let t=Ja.title,r=e.title.length;return h6(e.title)?{status:"fail",weight:t,detail:"vague or placeholder title"}:r>Sg?{status:"warn",weight:t,detail:`title is ${r} chars (budget: ${Sg})`}:p6.test(e.title)?{status:"pass",weight:t,detail:"descriptive, conventional, within budget"}:{status:"warn",weight:t,detail:"descriptive but not conventional commit format"}}function R6(e){let t=Ja.branch;return w6.test(e.branch)||b6.test(e.branch)?{status:"fail",weight:t,detail:`non-descriptive branch name "${e.branch}"`}:/[/_-]/.test(e.branch)?{status:"pass",weight:t,detail:e.branch}:{status:"warn",weight:t,detail:`branch "${e.branch}" lacks a clear separator`}}function S6(e){return e>=nC.ready?{rating:"ready",emoji:"\u{1F31F}"}:e>=nC.minor?{rating:"minor",emoji:"\u2705"}:e>=nC.fixFirst?{rating:"fix_first",emoji:"\u26A0\uFE0F"}:{rating:"significant_work",emoji:"\u274C"}}function fM(e,t){let r={issueReference:e6(e,t),description:c6(e),focusedChanges:u6(e),tests:d6(e,t),title:y6(e),branch:R6(e)},n=Object.values(r).reduce((a,c)=>a+KK[c.status]*c.weight,0),s=Math.round(n),{rating:o,emoji:i}=S6(s);return{score:s,rating:o,emoji:i,checks:r}}var ZK,Ja,KK,_g,nC,JK,YK,QK,t6,r6,n6,l6,p6,m6,f6,g6,b6,w6,gM=A(()=>{"use strict";rC();rC();ZK=30,Ja={issueReference:25,description:25,focusedChanges:20,tests:15,title:10,branch:5},KK={pass:1,warn:.5,fail:0},_g=Rg,nC={ready:90,minor:75,fixFirst:60},JK=/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#\d+/i,YK=/\b(?:relates?\s+to|see|refs?|references?)\s+#\d+/i,QK=/https?:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+/i;t6=/(?:^|\n)#{1,3}\s*(?:summary|overview|what(?:\s+changed)?)\b/i,r6=/(?:^|\n)#{1,3}\s*(?:why|motivation|context|background|rationale)\b/i,n6=/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+(?:[\w.-]+\/[\w.-]+)?#\d+/gi;l6=/(?:^|\/)(?:tests?|__tests__|spec)\/|\.(?:test|spec)\.[cm]?[jt]sx?$|\.test_|_test\.(?:go|py|rb)$|(?:^|\/)test_[^/]+\.py$|_spec\.rb$/i;p6=/^(?:feat|fix|chore|docs|refactor|test|perf|build|ci|style|revert)(?:\([^)]+\))?!?:\s+\S/i,m6=new Set(["wip","test","hello","tmp","temp","untitled"]),f6=/^[asdfqwer]+$/i,g6=/^update\s+\S+\s*$/i;b6=/^patch-\d+$/i,w6=/^(?:main|master)$/i});var hM={};re(hM,{runComplianceScore:()=>P6});async function v6(e,t,r){try{let{data:n}=await e.repos.getContent({owner:t,repo:r,path:""});if(!Array.isArray(n))return;let s=/^(?:tests?|__tests__|spec)$/i;return n.some(o=>o.type==="dir"&&s.test(o.name))}catch(n){if(de(n))throw n;v(_6,`test-infrastructure probe for ${t}/${r} failed: ${I(n)}`);return}}function k6(e,t,r){let n=new Map,s=(c,u,d)=>{let p=`${c}/${u}#${d}`;n.has(p)||n.set(p,{owner:c,repo:u,number:d})},o=/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?|relates?\s+to|refs?|references?|see)\s+#(\d+)/gi;for(let c of e.matchAll(o))s(t,r,Number.parseInt(c[1],10));let i=/\b([\w.-]+)\/([\w.-]+)#(\d+)/g;for(let c of e.matchAll(i))s(c[1],c[2],Number.parseInt(c[3],10));let a=/https?:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/gi;for(let c of e.matchAll(a))s(c[1],c[2],Number.parseInt(c[3],10));return[...n.values()]}async function C6(e,t,r,n=new Date){return Promise.all(r.map(async({owner:s,repo:o,number:i})=>{let a=s!==t.owner||o!==t.repo,c=`${s}/${o}`;try{let{data:u}=await e.issues.get({owner:s,repo:o,issue_number:i});if(u.state==="open")return{number:i,repo:c,crossRepo:a,state:"open"};let d=u.closed_at?new Date(u.closed_at):null,p=d?Math.floor((n.getTime()-d.getTime())/864e5):void 0;return{number:i,repo:c,crossRepo:a,state:"closed",closedDaysAgo:p}}catch(u){return u.status===404?{number:i,repo:c,crossRepo:a,state:"not_found"}:{number:i,repo:c,crossRepo:a,state:"unverifiable"}}}))}async function P6(e){Ze(e.prUrl),Qe(e.prUrl,tr,"PR");let t=ke(),r=be(t),n=q(e.prUrl);if(!n||n.type!=="pull")throw new j(`Invalid PR URL: ${e.prUrl}`);let{owner:s,repo:o,number:i}=n,[{data:a},c,u]=await Promise.all([r.pulls.get({owner:s,repo:o,pull_number:i}),r.pulls.listFiles({owner:s,repo:o,pull_number:i,per_page:100}),v6(r,s,o)]),d={title:a.title,body:a.body??"",branch:a.head.ref,filesChangedCount:a.changed_files,additions:a.additions,deletions:a.deletions,files:c.data.map(h=>h.filename)},p=k6(d.body,s,o),m=p.length>0?await C6(r,{owner:s,repo:o},p):void 0,g=fM(d,{hasTestInfrastructure:u,linkedIssues:m});return{pr:{repo:`${s}/${o}`,number:i,title:a.title,url:e.prUrl},score:g.score,rating:g.rating,emoji:g.emoji,checks:g.checks}}var _6,yM=A(()=>{"use strict";le();ee();ce();Ot();nt();gM();_6="compliance-score"});var vg={};re(vg,{runClaim:()=>T6,runComments:()=>E6,runPost:()=>A6});async function E6(e){Ze(e.prUrl),Qe(e.prUrl,tr,"PR");let t=ke(),r=L(),n=be(t),s=q(e.prUrl);if(!s||s.type!=="pull")throw new j("Invalid PR URL format");let{owner:o,repo:i,number:a}=s,{data:c}=await n.pulls.get({owner:o,repo:i,pull_number:a}),[u,d,p]=await Promise.all([je(T=>n.pulls.listReviewComments({owner:o,repo:i,pull_number:a,per_page:100,page:T})),je(T=>n.issues.listComments({owner:o,repo:i,issue_number:a,per_page:100,page:T})),je(T=>n.pulls.listReviews({owner:o,repo:i,pull_number:a,per_page:100,page:T}))]),{items:m}=u,{items:f}=d,{items:g}=p,h=[...p.truncated?["reviews"]:[],...u.truncated?["inline review comments"]:[],...d.truncated?["discussion comments"]:[]],b=r.getState().config.githubUsername,w=T=>!(!T.user||T.user.login?.toLowerCase()===b?.toLowerCase()||T.user.type==="Bot"&&!e.showBots),y=m.filter(w).sort((T,M)=>new Date(M.created_at).getTime()-new Date(T.created_at).getTime()),S=f.filter(w).sort((T,M)=>new Date(M.created_at).getTime()-new Date(T.created_at).getTime()),k=g.filter(T=>w(T)&&T.body&&T.body.trim()).sort((T,M)=>new Date(M.submitted_at||0).getTime()-new Date(T.submitted_at||0).getTime()),R=`${o}/${i}#${a}`,P=(T,M,G,X)=>st(T,R,{author:G,association:X,source:M}),C=r.getStateStaleness(),E=[];return h.length>0&&E.push({phase:"fetch",operation:"fetch PR comments (truncated)",message:`Pagination cap reached fetching ${h.join(", ")} for ${o}/${i}#${a}; the newest entries in those streams may be missing.`}),C&&E.push(An(C)),{pr:{title:c.title,state:c.state,mergeable:c.mergeable,head:c.head.ref,base:c.base.ref,url:c.html_url},reviews:k.map(T=>({user:T.user?.login,state:T.state,body:T.body==null?null:P(T.body,"pr-review",T.user?.login,T.author_association),submittedAt:T.submitted_at??null})),reviewComments:y.map(T=>({user:T.user?.login,body:P(T.body,"pr-review-comment",T.user?.login,T.author_association),path:T.path,createdAt:T.created_at})),issueComments:S.map(T=>({user:T.user?.login,body:T.body==null?T.body:P(T.body,"pr-issue-comment",T.user?.login,T.author_association),createdAt:T.created_at})),summary:{reviewCount:k.length,inlineCommentCount:y.length,discussionCommentCount:S.length},...E.length>0&&{warnings:E}}}async function A6(e){if(du("post a comment"),Ze(e.url),Qe(e.url,Ku,"issue or PR"),!e.message.trim())throw new j("No message provided");cv(e.message);let t=ke(),r=q(e.url);if(!r)throw new j("Invalid GitHub URL format");let{owner:n,repo:s,number:o}=r,i=be(t),{data:a}=await i.issues.createComment({owner:n,repo:s,issue_number:o,body:e.message});return{commentUrl:a.html_url,url:e.url}}async function T6(e){du("claim an issue"),Ze(e.issueUrl),Qe(e.issueUrl,dr,"issue");let t=ke(),r=e.message||"Hi! I'd like to work on this issue. Could you assign it to me?";cv(r);let n=q(e.issueUrl);if(!n||n.type!=="issues")throw new j("Invalid issue URL format (must be an issue, not a PR)");let{owner:s,repo:o,number:i}=n,a=be(t),c="(claimed)",u=[],d=new Date().toISOString();try{let{data:g}=await a.issues.get({owner:s,repo:o,issue_number:i});g.title&&(c=g.title),u=(g.labels??[]).map(h=>typeof h=="string"?h:h.name??"").filter(h=>!!h),g.created_at&&(d=g.created_at)}catch(g){if(de(g))throw g;v(sC,`Failed to enrich issue metadata (title/labels) for ${e.issueUrl}; claiming with placeholder: ${g instanceof Error?g.message:g}`)}let{data:p}=await a.issues.createComment({owner:s,repo:o,issue_number:i,body:r}),m=null,f;try{let g=L(),h={id:i,url:e.issueUrl,repo:`${s}/${o}`,number:i,title:c,status:"claimed",labels:u,createdAt:d,updatedAt:new Date().toISOString(),vetted:!1};g.addIssue(h),m=await we(g,sC,()=>g.addIssue(h))}catch(g){f=`Comment posted on ${e.issueUrl} but failed to save to local state: ${g instanceof Error?g.message:g}`,v(sC,f)}return{commentUrl:p.html_url,issueUrl:e.issueUrl,...m&&{gistSyncWarning:m},...f&&{stateSaveWarning:f}}}var sC,kg=A(()=>{"use strict";le();Cn();ee();ce();io();me();Ot();sC="comments"});var wM={};re(wM,{runConfig:()=>O6});function bM(e){if(!eo.includes(e))throw new Error(`Invalid scope "${e}". Valid scopes: ${eo.join(", ")}`);return e}async function O6(e){if(e.listKeys){if(e.key||e.value)throw new j("`--list-keys` cannot be combined with a key/value. Run `config --list-keys` on its own.");return{keys:bo}}let t=L();if(!e.key)return{config:t.getState().config};if(!e.value)throw new Error("Value required");let{key:r,value:n}=e,s=()=>I6(t,r,n);s();let o=await we(t,$6,s);return{success:!0,key:r,value:n,...o&&{gistSyncWarning:o}}}function I6(e,t,r){let n=e.getState().config;switch(t){case"username":{e.updateConfig({githubUsername:Pa(r)});break}case"add-language":{n.languages.includes(r)||e.updateConfig({languages:[...n.languages,r]});break}case"add-label":{n.labels.includes(r)||e.updateConfig({labels:[...n.labels,r]});break}case"remove-label":{if(!n.labels.includes(r))throw new Error(`Label "${r}" is not currently configured. Current labels: ${n.labels.join(", ")}`);e.updateConfig({labels:n.labels.filter(s=>s!==r)});break}case"add-scope":{let s=bM(r),o=n.scope??[];o.includes(s)||e.updateConfig({scope:[...o,s]});break}case"remove-scope":{let s=bM(r),o=n.scope??[];if(!o.includes(s))throw new Error(`Scope "${r}" is not currently set`);let i=o.filter(a=>a!==s);if(i.length===0)throw new Error("Cannot remove the last scope. Use setup to clear scopes entirely.");e.updateConfig({scope:i});break}case"exclude-repo":{let s=r.split("/");if(s.length!==2||!s[0]||!s[1])throw new Error(`Invalid repo format "${r}". Use "owner/repo" format. To exclude an entire org, use: config exclude-org ${r}`);let o=r.toLowerCase();n.excludeRepos.some(i=>i.toLowerCase()===o)||e.batch(()=>{e.updateConfig({excludeRepos:[...n.excludeRepos,r]}),e.cleanupExcludedData([r],[])});break}case"exclude-org":{if(r.includes("/"))throw new Error(`Invalid org name "${r}". Use just the org name (e.g., "facebook"), not "owner/repo" format. To exclude a specific repo, use: config exclude-repo ${r}`);let s=n.excludeOrgs??[];s.some(o=>o.toLowerCase()===r.toLowerCase())||e.batch(()=>{e.updateConfig({excludeOrgs:[...s,r]}),e.cleanupExcludedData([],[r])});break}case"add-avoid-repo":{let s=r.split("/");if(s.length!==2||!s[0]||!s[1])throw new Error(`Invalid repo format "${r}". Use "owner/repo" format.`);let o=n.avoidRepos??[],i=r.toLowerCase();o.some(a=>a.toLowerCase()===i)||e.updateConfig({avoidRepos:[...o,r]});break}case"remove-avoid-repo":{let s=n.avoidRepos??[],o=r.toLowerCase();if(!s.some(i=>i.toLowerCase()===o))throw new Error(`Repo "${r}" is not on the avoid list. Current avoid list: ${s.join(", ")||"(empty)"}`);e.updateConfig({avoidRepos:s.filter(i=>i.toLowerCase()!==o)});break}case"add-boost-issue-type":{let s=n.boostIssueTypes??[],o=r.toLowerCase();s.some(i=>i.toLowerCase()===o)||e.updateConfig({boostIssueTypes:[...s,r]});break}case"remove-boost-issue-type":{let s=n.boostIssueTypes??[],o=r.toLowerCase();if(!s.some(i=>i.toLowerCase()===o))throw new Error(`Issue type "${r}" is not on the boost list. Current boost list: ${s.join(", ")||"(empty)"}`);e.updateConfig({boostIssueTypes:s.filter(i=>i.toLowerCase()!==o)});break}case"issueListPath":{e.updateConfig({issueListPath:r||void 0});break}case"diffTool":{if(!to.includes(r))throw new Error(`Invalid diffTool "${r}". Valid options: ${to.join(", ")}`);e.updateConfig({diffTool:r});break}case"diffToolCustomCommand":{e.updateConfig({diffToolCustomCommand:r||void 0});break}default:throw new j(wo(t,"config"))}}var $6,RM=A(()=>{"use strict";le();ee();ts();Ot();$6="config"});var SM={};re(SM,{runInit:()=>D6});async function D6(e){Pa(e.username);let t=L(),r=()=>t.updateConfig({githubUsername:e.username});r();let n=await we(t,x6,r);return{username:e.username,message:"Username saved. Run `daily` to fetch your open PRs from GitHub.",...n&&{gistSyncWarning:n}}}var x6,_M=A(()=>{"use strict";le();Ot();x6="init"});var oC={};re(oC,{runCheckSetup:()=>F6,runSetup:()=>M6});function vl(e,t){let r=Number(e);if(!Number.isInteger(r)||r<1)throw new j(`Invalid value for ${t}: "${e}". Must be a positive integer.`);return r}function vM(e,t){let r=Number(e);if(!Number.isInteger(r)||r<0)throw new j(`Invalid value for ${t}: "${e}". Must be a non-negative integer.`);return r}async function M6(e){let t=L(),r=t.getState().config;if(e.set&&e.set.length>0){let n={},s=[],o=new Set(zu());for(let c of e.set){let[u]=c.split("=",1);if(!o.has(u))throw new j(wo(u,"setup"))}let i=()=>{s.length=0;for(let c of e.set){let[u,...d]=c.split("="),p=d.join("=");switch(u){case"username":{Pa(p),t.updateConfig({githubUsername:p}),n[u]=p;break}case"maxActivePRs":case"maxOpenPRsPerRepo":case"maxOpenPRsColdRepo":case"maxConcurrentImplementations":{let m=vM(p,u);t.updateConfig({[u]:m}),n[u]=String(m);break}case"dormantDays":{let m=vl(p,"dormantDays");t.updateConfig({dormantThresholdDays:m}),n[u]=String(m);break}case"approachingDays":{let m=vl(p,"approachingDays");t.updateConfig({approachingDormantDays:m}),n[u]=String(m);break}case"languages":{t.updateConfig({languages:p.split(",").map(m=>m.trim())}),n[u]=p;break}case"labels":{t.updateConfig({labels:p.split(",").map(m=>m.trim())}),n[u]=p;break}case"squashByDefault":{p==="ask"?(t.updateConfig({squashByDefault:"ask"}),n[u]="ask"):(t.updateConfig({squashByDefault:p!=="false"}),n[u]=p==="false"?"false":"true");break}case"minStars":{let m=Number(p);if(!Number.isInteger(m)||m<0)throw new j(`Invalid value for minStars: "${p}". Must be a non-negative integer.`);t.updateConfig({minStars:m}),n[u]=String(m);break}case"maxIssueAgeDays":{let m=vl(p,"maxIssueAgeDays");t.updateConfig({maxIssueAgeDays:m}),n[u]=String(m);break}case"minRepoScoreThreshold":{let m=Number(p);if(!Number.isInteger(m)||m<0)throw new j(`Invalid value for minRepoScoreThreshold: "${p}". Must be a non-negative integer.`);t.updateConfig({minRepoScoreThreshold:m}),n[u]=String(m);break}case"skippedIssuesPath":{t.updateConfig({skippedIssuesPath:p||void 0}),n[u]=p||"(cleared)";break}case"autoExtractLearnings":{if(p!=="true"&&p!=="false")throw new j(`Invalid value for autoExtractLearnings: "${p}". Must be "true" or "false".`);let m=p==="true";t.updateConfig({autoExtractLearnings:m}),n[u]=String(m);break}case"autoFormatBeforePush":{if(p!=="true"&&p!=="false")throw new j(`Invalid value for autoFormatBeforePush: "${p}". Must be "true" or "false".`);let m=p==="true";t.updateConfig({autoFormatBeforePush:m}),n[u]=String(m);break}case"trustOwnRepoWrites":{if(p!=="true"&&p!=="false")throw new j(`Invalid value for trustOwnRepoWrites: "${p}". Must be "true" or "false".`);let m=p==="true";t.updateConfig({trustOwnRepoWrites:m}),n[u]=String(m);break}case"includeDocIssues":{t.updateConfig({includeDocIssues:p==="true"}),n[u]=p==="true"?"true":"false";break}case"aiPolicyBlocklist":{let m=p.split(",").map(h=>h.trim()).filter(Boolean),f=[],g=[];for(let h of m){let b=h.replaceAll(/\s+/g,"");/^[\w.-]+\/[\w.-]+$/.test(b)?f.push(b):g.push(h)}if(g.length>0&&(s.push(`Warning: Skipping invalid entries (expected "owner/repo" format): ${g.join(", ")}`),n.aiPolicyBlocklist_invalidEntries=g.join(", ")),f.length===0&&m.length>0){s.push("Warning: All entries were invalid. Blocklist not updated."),n[u]="(all entries invalid)";break}t.updateConfig({aiPolicyBlocklist:f}),n[u]=f.length>0?f.join(", "):"(empty)";break}case"avoidRepos":{let m=p.split(",").map(b=>b.trim()).filter(Boolean),f=[],g=[];for(let b of m){let w=b.replaceAll(/\s+/g,"");/^[\w.-]+\/[\w.-]+$/.test(w)?f.push(w):g.push(b)}if(g.length>0&&s.push(`Warning: Skipping invalid entries (expected "owner/repo" format): ${g.join(", ")}`),f.length===0&&m.length>0){s.push("Warning: All entries were invalid. avoidRepos not updated."),n[u]="(all entries invalid)";break}let h=[...new Set(f)];t.updateConfig({avoidRepos:h}),n[u]=h.length>0?h.join(", "):"(empty)";break}case"boostIssueTypes":{let m=[...new Set(p.split(",").map(f=>f.trim()).filter(Boolean))];t.updateConfig({boostIssueTypes:m}),n[u]=m.length>0?m.join(", "):"(empty)";break}case"projectCategories":{let m=p.split(",").map(b=>b.trim()).filter(Boolean),f=[],g=[];for(let b of m)um.includes(b)?f.push(b):g.push(b);g.length>0&&s.push(`Unknown project categories: ${g.join(", ")}. Valid: ${um.join(", ")}`);let h=[...new Set(f)];t.updateConfig({projectCategories:h}),n[u]=h.length>0?h.join(", "):"(empty)";break}case"preferredOrgs":case"untrackedOrgs":{let m=p.split(",").map(h=>h.trim()).filter(Boolean),f=[];for(let h of m)h.includes("/")?s.push(`"${h}" looks like a repo path. Use org name only (e.g., "vercel" not "vercel/next.js").`):/^[\da-z](?:[\da-z-]*[\da-z])?$/i.test(h)?f.push(h.toLowerCase()):s.push(`"${h}" is not a valid GitHub organization name. Skipping.`);let g=[...new Set(f)];t.updateConfig({[u]:g}),n[u]=g.length>0?g.join(", "):"(empty)";break}case"scope":{let m=p.split(",").map(b=>b.trim()).filter(Boolean),f=[],g=[];for(let b of m)eo.includes(b)?f.push(b):g.push(b);g.length>0&&s.push(`Unknown issue scopes: ${g.join(", ")}. Valid: ${eo.join(", ")}`);let h=[...new Set(f)];t.updateConfig({scope:h.length>0?h:void 0}),n[u]=h.length>0?h.join(", "):"(empty \u2014 using labels only)";break}case"persistence":{if(p!=="local"&&p!=="gist")throw new j(`Invalid value for persistence: "${p}". Must be "local" or "gist".`);t.updateConfig({persistence:p}),n[u]=p;break}case"issueListPath":{t.updateConfig({issueListPath:p||void 0}),n[u]=p||"(cleared)";break}case"diffTool":{if(!to.includes(p)){s.push(`Invalid diffTool "${p}". Valid: ${to.join(", ")}`);break}t.updateConfig({diffTool:p}),n[u]=p;break}case"diffToolCustomCommand":{t.updateConfig({diffToolCustomCommand:p||void 0}),n[u]=p||"(cleared)";break}case"skipBroadWhenSufficientResults":{let m=vM(p,"skipBroadWhenSufficientResults");t.updateConfig({skipBroadWhenSufficientResults:m}),n[u]=String(m);break}case"healthCheckFreshnessMinutes":{let m=vl(p,"healthCheckFreshnessMinutes");t.updateConfig({healthCheckFreshnessMinutes:m}),n[u]=String(m);break}case"reviewMaxPasses":{let m=vl(p,"reviewMaxPasses");t.updateConfig({reviewMaxPasses:m}),n[u]=String(m);break}case"complete":{p==="true"&&(t.markSetupComplete(),n[u]="true");break}default:throw new j(wo(u,"setup"))}}};t.batch(i);let a=await we(t,L6,()=>t.batch(i));return{success:!0,settings:n,warnings:s.length>0?s:void 0,...a&&{gistSyncWarning:a}}}return r.setupComplete&&!e.reset?{setupComplete:!0,config:{githubUsername:r.githubUsername,maxActivePRs:r.maxActivePRs,dormantThresholdDays:r.dormantThresholdDays,approachingDormantDays:r.approachingDormantDays,languages:r.languages,labels:r.labels,projectCategories:r.projectCategories??[],preferredOrgs:r.preferredOrgs??[],scope:r.scope??[],persistence:r.persistence??"local"}}:{setupRequired:!0,prompts:[{setting:"username",prompt:"What is your GitHub username?",current:r.githubUsername||null,required:!0,type:"string"},{setting:"maxActivePRs",prompt:"How many PRs do you want to work on at once?",current:r.maxActivePRs,default:10,type:"number"},{setting:"dormantDays",prompt:"After how many days of inactivity should a PR be considered dormant?",current:r.dormantThresholdDays,default:30,type:"number"},{setting:"approachingDays",prompt:"At how many days should we warn about approaching dormancy?",current:r.approachingDormantDays,default:25,type:"number"},{setting:"languages",prompt:"What programming languages do you want to contribute to?",current:r.languages,default:["typescript","javascript"],type:"list"},{setting:"labels",prompt:"What issue labels should we search for?",current:r.labels,default:["good first issue","help wanted"],type:"list"},{setting:"scope",prompt:"What scope of issues do you want to discover? (beginner, intermediate, advanced \u2014 leave empty for default labels only)",current:r.scope??[],default:[],type:"list"},{setting:"aiPolicyBlocklist",prompt:"Repos with anti-AI contribution policies to block (owner/repo, comma-separated)?",current:r.aiPolicyBlocklist??xS.aiPolicyBlocklist??null,default:["matplotlib/matplotlib"],type:"list"},{setting:"projectCategories",prompt:"What types of projects interest you? (nonprofit, devtools, infrastructure, web-frameworks, data-ml, education)",current:r.projectCategories??[],default:[],type:"list"},{setting:"preferredOrgs",prompt:"Any GitHub organizations to prioritize? (org names, comma-separated)",current:r.preferredOrgs??[],default:[],type:"list"},{setting:"persistence",prompt:'Where should state be stored? "local" for file only, "gist" for GitHub Gist (survives device loss)',current:r.persistence??"local",default:"local",type:"string"}]}}async function F6(){let e=L();return{setupComplete:e.isSetupComplete(),username:e.getState().config.githubUsername}}var L6,iC=A(()=>{"use strict";le();ee();Ot();ts();L6="setup"});var kM={};re(kM,{runCheckIntegration:()=>z6});function U6(e){let t=hr.extname(e),r=hr.basename(e,t);return r==="index"?hr.basename(hr.dirname(e)):r}function j6(e,t){let r=hr.dirname(e),n=[];for(let o of[".ts",".tsx",".js",".jsx"]){let i=hr.join(r,`index${o}`);t.includes(i)&&n.push(i)}let s=hr.dirname(r);for(let o of[".ts",".tsx",".js",".jsx"]){let i=hr.join(s,`index${o}`);t.includes(i)&&n.push(i)}return[...new Set(n)]}async function z6(e){let t=e.base,r;try{let a=(0,Cg.execFileSync)("git",["diff","--name-only","--diff-filter=A",`${t}...HEAD`],{encoding:"utf8",timeout:1e4}).trim();r=a?a.split(`
332
- `).filter(Boolean):[]}catch(a){let c=I(a);throw new Error(`Failed to run git diff: ${c}`,{cause:a})}let n=r.filter(a=>{let c=hr.extname(a);return N6.has(c)?!G6.some(u=>u.test(a)):!1});if(n.length===0)return{newFiles:[],unreferencedCount:0};let s;try{s=(0,Cg.execFileSync)("git",["ls-files"],{encoding:"utf8",timeout:1e4}).trim().split(`
333
- `).filter(Boolean)}catch(a){O("check-integration","git ls-files failed, reference checking will be skipped",a),s=[]}let o=[];for(let a of n){let c=U6(a),u=a.replace(/\.[^.]+$/,""),d=[],p=[c];u.includes("/")&&p.push(u);for(let g of p)try{let h=(0,Cg.execFileSync)("git",["grep","-l","--",g],{encoding:"utf8",timeout:1e4}).trim();if(h){let b=h.split(`
334
- `).filter(w=>w!==a);d.push(...b)}}catch(h){let b=h&&typeof h=="object"&&"status"in h?h.status:void 0;if(b!==void 0&&b!==1){let w=I(h);O("check-integration",`git grep failed for "${g}": ${w}`)}}d=[...new Set(d)];let m=d.length>0,f={path:a,referencedBy:d,isIntegrated:m};m||(f.suggestedEntryPoints=j6(a,s)),o.push(f)}let i=o.filter(a=>!a.isIntegrated).length;return{newFiles:o,unreferencedCount:i}}var hr,Cg,N6,G6,CM=A(()=>{"use strict";hr=B(require("node:path"),1),Cg=require("node:child_process");le();ee();N6=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".vue",".svelte"]),G6=[/^\./,/\.(test|spec|e2e)\.[^.]+$/,/\.(config|rc)\.[^.]+$/,/__tests__\//,/\.d\.ts$/,/\.md$/,/\.json$/,/\.ya?ml$/]});var NM={};re(NM,{checkBundleUpToDate:()=>DM,checkGhAuth:()=>IM,checkGhCli:()=>OM,checkGitHubRateLimit:()=>FM,checkGitHubToken:()=>xM,checkScoutResolvable:()=>MM,checkStateFile:()=>LM,runDoctor:()=>W6});function aC(e){if(e&&typeof e=="object"&&"code"in e){let t=e.code;if(typeof t=="string")return t}}async function OM(){try{let{stdout:e}=await TM("gh",["--version"],{timeout:$M});return{name:"gh CLI installed",status:"ok",message:e.split(`
335
- `,1)[0]?.trim()||"gh present"}}catch(e){return aC(e)==="ENOENT"?{name:"gh CLI installed",status:"warning",message:"gh CLI not found on PATH",remediation:"Install the GitHub CLI from https://cli.github.com/"}:{name:"gh CLI installed",status:"warning",message:`gh CLI present but failed to run: ${I(e)}`,remediation:"Check that `gh --version` works in your shell; a timeout or permission error may indicate a broken install"}}}async function IM(){try{return await TM("gh",["auth","status"],{timeout:$M}),{name:"gh CLI authenticated",status:"ok",message:"Signed in to github.com"}}catch(e){return{name:"gh CLI authenticated",status:"warning",message:`gh auth status failed: ${I(e)}`,remediation:"Run `gh auth login` to authenticate, or check network/proxy connectivity if the error looks network-related"}}}async function xM(e){let t=e===void 0?await xr():e;if(!t)return{name:"GitHub token resolvable",status:"warning",message:"No GitHub token available via $GITHUB_TOKEN or `gh auth token`",remediation:"Set $GITHUB_TOKEN or run `gh auth login`"};try{let r=be(t),{data:n}=await r.users.getAuthenticated();return{name:"GitHub token resolvable",status:"ok",message:`Authenticated as @${n.login}`}}catch(r){return{name:"GitHub token resolvable",status:"error",message:`Token present but API auth failed: ${I(r)}`,remediation:"Token may be expired or revoked \u2014 run `gh auth refresh` or set a fresh $GITHUB_TOKEN"}}}function B6(){let e=kl.resolve(__dirname,"../../dist/cli.bundle.cjs"),t=kl.resolve(__dirname,"cli.bundle.cjs"),r=kl.resolve(__dirname,"../cli.ts"),n=kl.resolve(__dirname,"../src/cli.ts"),s=on.existsSync(e)?e:on.existsSync(t)?t:e,o=on.existsSync(r)?r:on.existsSync(n)?n:r;return{bundlePath:s,sourcePath:o}}function PM(e){try{return{stat:on.statSync(e)}}catch(t){return aC(t)==="ENOENT"?{stat:null}:{stat:null,error:t}}}function DM(e){let t=B6(),r=e?.bundlePath??t.bundlePath,n=e?.sourcePath??t.sourcePath,s=PM(r),o=PM(n);if(s.error||o.error){let c=s.error??o.error;return{name:"CLI bundle",status:"error",message:`Bundle freshness check failed: ${I(c)}`,remediation:"Check filesystem permissions on packages/core/dist/"}}let i=s.stat,a=o.stat;return!i&&!a?{name:"CLI bundle",status:"warning",message:"Neither cli.ts nor cli.bundle.cjs could be located",remediation:"Reinstall the package or check your install location"}:i?a&&a.mtimeMs>i.mtimeMs?{name:"CLI bundle",status:"warning",message:"Source files are newer than dist/cli.bundle.cjs",remediation:"Run `pnpm run bundle` to rebuild"}:{name:"CLI bundle",status:"ok",message:"Bundle present and up-to-date"}:{name:"CLI bundle",status:"warning",message:"dist/cli.bundle.cjs not built yet",remediation:"Run `pnpm run bundle` to build the CLI bundle"}}function LM(e){let t=e?.statePathOverride??jt();if(!on.existsSync(t))return{name:"state.json valid",status:"ok",message:"No state.json yet (first run \u2014 nothing to validate)"};try{let r=on.readFileSync(t,"utf8"),n=JSON.parse(r),s=Gt.safeParse(n);return s.success?{name:"state.json valid",status:"ok",message:`state v${typeof n?.version=="number"?n.version:"?"} parses and validates`}:{name:"state.json valid",status:"error",message:`state.json failed schema validation \u2014 ${s.error.issues.slice(0,3).map(a=>`${a.path.join(".")||"<root>"}: ${a.message}`).join("; ")}`,remediation:"Restore from a backup in `~/.oss-autopilot/backups/` or re-run `oss-autopilot init`"}}catch(r){return{name:"state.json valid",status:"error",message:`Failed to read/parse state.json: ${I(r)}`,remediation:"Restore from a backup in `~/.oss-autopilot/backups/`"}}}async function MM(e=H6){try{return await e(),{name:"@oss-scout/core resolvable",status:"ok",message:"Found on module path"}}catch(t){let r=aC(t),n=r==="ERR_MODULE_NOT_FOUND"||r==="MODULE_NOT_FOUND",s=r==="ERR_PACKAGE_PATH_NOT_EXPORTED"||r==="ERR_PACKAGE_IMPORT_NOT_DEFINED"||r==="ERR_INVALID_PACKAGE_CONFIG"||t instanceof SyntaxError,o=n||s;return{name:"@oss-scout/core resolvable",status:"error",message:o?`@oss-scout/core cannot be loaded (install issue): ${I(t)}`:`@oss-scout/core failed to load: ${I(t)}`,remediation:o?"Reinstall dependencies (`pnpm install` or `npm install`)":"Scout loaded but threw during initialization \u2014 report this as a bug in oss-scout with the error above"}}}async function FM(e){let t=e===void 0?await xr():e;if(!t)return{name:"GitHub rate limit",status:"warning",message:"Cannot check \u2014 no token available",remediation:"Set $GITHUB_TOKEN or run `gh auth login` to enable API-backed checks"};try{let r=be(t),{data:n}=await r.rateLimit.get(),s=n.resources.core,o=new Date(s.reset*1e3).toISOString();return s.remaining<100?{name:"GitHub rate limit",status:"warning",message:`Only ${s.remaining}/${s.limit} core requests remaining (resets at ${o})`,remediation:"Wait for the window to reset or use a token with a higher limit"}:{name:"GitHub rate limit",status:"ok",message:`${s.remaining}/${s.limit} core requests remaining`}}catch(r){return{name:"GitHub rate limit",status:"error",message:`Failed to check rate limit: ${I(r)}`}}}async function Go(e,t){try{return await t()}catch(r){return{name:e,status:"error",message:`Check crashed unexpectedly: ${I(r)}`,remediation:"This is a bug in the doctor command \u2014 please report it with the error above"}}}async function W6(){let e=null;try{e=await xr()}catch{e=null}let t=await Promise.all([Go("gh CLI installed",()=>OM()),Go("gh CLI authenticated",()=>IM()),Go("GitHub token resolvable",()=>xM(e)),Go("GitHub rate limit",()=>FM(e)),Go("@oss-scout/core resolvable",()=>MM()),Go("CLI bundle",()=>DM()),Go("state.json valid",()=>LM())]),r={ok:t.filter(n=>n.status==="ok").length,warnings:t.filter(n=>n.status==="warning").length,errors:t.filter(n=>n.status==="error").length};return{checks:t,summary:r}}var on,kl,EM,AM,TM,$M,H6,GM=A(()=>{"use strict";on=B(require("node:fs"),1),kl=B(require("node:path"),1),EM=require("node:child_process"),AM=require("node:util");le();gn();ee();TM=(0,AM.promisify)(EM.execFile),$M=3e3;H6=()=>Promise.resolve().then(()=>(gg(),bL))});var zM={};re(zM,{runLocalRepos:()=>Q6,scanForRepos:()=>jM});function Z6(e,t,r,n,s){for(let o of e){if(!o.isDirectory())continue;let i=an.default.join(t,o.name),a=r+1;o.name===".git"?s.push(i):a<q6&&n.push({directory:i,depth:a})}}function K6(e){let t=[],r=[{directory:e,depth:0}],n=Date.now()+UM;for(;r.length>0;){if(Date.now()>n){O("local-repos",`Scan of ${e} exceeded ${UM}ms; returning partial results`);break}let{directory:s,depth:o}=r.pop(),i;try{i=Cl.readdirSync(s,{withFileTypes:!0})}catch(a){O("local-repos",`Failed to read directory ${s}`,a);continue}Z6(i,s,o,r,t)}return t}function J6(e){try{let t=(0,cC.execFileSync)("git",["-C",e,"remote","get-url","origin"],{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim(),r=t.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);if(r)return r[1];let n=t.match(/github\.com[/:]([^/]+\/[^/]+?)(?:\.git)?$/);return n?n[1]:null}catch(t){return O("local-repos",`Failed to get GitHub remote for ${e}`,t),null}}function Y6(e){try{return(0,cC.execFileSync)("git",["-C",e,"branch","--show-current"],{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim()||null}catch(t){return O("local-repos",`Failed to get current branch for ${e}`,t),null}}function jM(e){let t={};for(let r of e){if(!Cl.existsSync(r))continue;let n=K6(r);for(let s of n){let o=an.default.dirname(s),i=J6(o);if(!i)continue;let a=Y6(o);t[i]={path:o,exists:!0,currentBranch:a}}}return t}async function Q6(e){let t=L(),r=t.getState(),n=e.paths?.map(i=>an.default.resolve(i))??r.config.localRepoScanPaths??V6.filter(i=>Cl.existsSync(i));if(!e.scan&&r.localRepoCache){let i=r.localRepoCache;return{repos:i.repos,scanPaths:i.scanPaths,cachedAt:i.cachedAt,fromCache:!0}}let s=jM(n),o=new Date().toISOString();try{t.setLocalRepoCache({repos:s,scanPaths:n,cachedAt:o})}catch(i){let a=I(i);console.error(`Warning: Failed to cache scan results to disk: ${a}`)}return{repos:s,scanPaths:n,cachedAt:o,fromCache:!1}}var Cl,an,Uo,cC,V6,q6,UM,BM=A(()=>{"use strict";Cl=B(require("node:fs"),1),an=B(require("node:path"),1),Uo=B(require("node:os"),1),cC=require("node:child_process");le();ee();V6=[an.default.join(Uo.homedir(),"Documents","oss"),an.default.join(Uo.homedir(),"dev"),an.default.join(Uo.homedir(),"projects"),an.default.join(Uo.homedir(),"src"),an.default.join(Uo.homedir(),"code"),an.default.join(Uo.homedir(),"repos")],q6=4,UM=3e4});var Pl={};re(Pl,{claimWork:()=>ZM,finishWork:()=>KM,listWork:()=>YM,releaseWork:()=>JM,runWorkClaim:()=>u3,runWorkFinish:()=>l3,runWorkList:()=>p3,runWorkRelease:()=>d3});function Pg(e){return new Date(e).toISOString()}function Ya(e,t){if(t===void 0)return;let r=t.trim();if(r.length===0)throw new j(`--${e} must not be empty`);if(r.length>HM)throw new j(`--${e} is longer than ${HM} characters`);if(X6.test(r))throw new j(`--${e} must not contain control characters`);return r}function qM(e){if(e==="implementation"||e==="pr")return e;throw new j(`--kind must be "implementation" or "pr", got "${e}"`)}function e3(e){if(e!==void 0){if(!Number.isFinite(e)||e<=0||e>iu)throw new j(`--ttl must be a number of hours between 0 and ${iu}`);return e}}function t3(e,t){Ze(e),t==="pr"?Qe(e,tr,"PR"):Qe(e,dr,"issue")}function r3(){return VM.default.hostname().split(".",1)[0]}function n3(e){let t=Ya("worktree",e);return t===void 0?{}:{worktree:Ni(t),host:r3(),machineId:cf()}}function s3(e){let t=qM(e.kind);t3(e.url,t);let r=Ya("session",e.session);if(r===void 0)throw new j("--session is required");let n=Ya("branch",e.branch),s=Ya("run-id",e.runId),o=n3(e.worktree);if(t==="implementation"&&s===void 0&&o.worktree===void 0)throw new j("An implementation claim needs --worktree (local checkout) or --run-id (remote worker run)");let i=e3(e.ttlHours),a=e.takeover===!0;return{kind:t,session:r,branch:n,...o,runId:s,ttlHours:i,url:e.url,takeover:a}}function WM(e,t,r){let n=e.getWorkClaims(),s=qp(n,t.url,t.session,r);if(s&&!t.takeover)return`${t.url} is already claimed: ${cu(s,r)}. Pass --takeover (takeover: true) to replace that claim.`;if(t.kind==="implementation"){let o=e.getState().config.maxConcurrentImplementations,i=Jp(n,t,o,r);if(i)return i.message}return null}function o3(e,t,r){let n=a3(e,t)?t:void 0,s=e.ttlHours??(n?au:Vp[e.kind]);return{kind:e.kind,url:e.url,session:e.session,startedAt:Pg(r),expiresAt:Pg(r+s*36e5),status:n?"finished":"running",...i3(e),...n?.finishedAt!==void 0&&{finishedAt:n.finishedAt}}}function i3(e){let{branch:t,worktree:r,host:n,machineId:s,runId:o}=e;return{...t!==void 0&&{branch:t},...r!==void 0&&{worktree:r},...n!==void 0&&{host:n},...s!==void 0&&{machineId:s},...o!==void 0&&{runId:o}}}function a3(e,t){return t!==void 0&&t.session===e.session&&t.kind===e.kind&&t.status==="finished"}function c3(e,t){return e===void 0?"claimed":e.session===t?"renewed":"took-over"}async function u3(e){return ZM(L(),e)}async function ZM(e,t){let r=s3(t),n=Date.now(),s=WM(e,r,n);if(s)throw new j(s);let o=Js(e.getWorkClaims(),r.url,n),i=o3(r,o,n),a=c3(o,r.session),c={message:null},u=()=>{c.message=WM(e,r,n),c.message===null&&e.upsertWorkClaim(i,n)};u();let d=await we(e,uC,u);if(c.message!==null)throw new j(`${c.message} (recorded on another machine first; this claim was not saved)`);let p=d===null&&e.getGistHealth().degraded===null;return{claim:i,outcome:a,synced:p,...d&&{gistSyncWarning:d}}}async function l3(e){return KM(L(),e)}async function KM(e,t){Ze(t.url);let r=Ya("session",t.session),n=Date.now(),s=Pg(n),o=()=>{let d=Js(e.getWorkClaims(),t.url,n);return d===void 0||r===void 0||d.session===r?null:`The claim on ${t.url} belongs to session ${d.session}, not ${r}; it was not marked finished.`},i={message:o()};if(i.message!==null)throw new j(i.message);let a={claim:null},c=()=>{i.message=o(),i.message===null&&(a.claim=e.finishWorkClaim(t.url,s,n)??null)};c();let u=a.claim?await we(e,uC,c):null;if(i.message!==null)throw new j(i.message);return{url:t.url,claim:a.claim,...u&&{gistSyncWarning:u}}}async function d3(e){return JM(L(),e)}async function JM(e,t){let r=Ya("session",t.session),n=t.kind===void 0?void 0:qM(t.kind);if(t.url!==void 0&&Ze(t.url),r===void 0&&t.url===void 0)throw new j("work release needs a URL or --session <name>");let s={url:t.url,session:r,kind:n},o=e.releaseWorkClaims(s),i=o.length>0?await we(e,uC,()=>e.releaseWorkClaims(s)):null;return{released:o,...i&&{gistSyncWarning:i}}}async function p3(){return YM(L())}async function YM(e){e.isGistMode()?await e.refreshFromGist():e.reloadIfChanged();let t=Date.now(),r=e.getWorkClaims(),n=e.getActiveWorkClaims(t),s=e.getStateStaleness();return{claims:n,expiredCount:r.length-n.length,now:Pg(t),...s&&{warnings:[An(s)]}}}var VM,uC,HM,X6,El=A(()=>{"use strict";VM=B(require("node:os"),1);le();ee();me();Ot();uC="work",HM=500,X6=new RegExp("\\p{Cc}","u")});var QM={};re(QM,{runPRTemplate:()=>m3});async function m3(e){let{owner:t,repo:r}=Ks(e.repo),n=ke(),s=be(n);return Ym(s,t,r)}var XM=A(()=>{"use strict";so();Lm();nt();z_()});var eF={};re(eF,{runRepoCap:()=>f3});async function f3(e){let t=mf(e.repo),r=L().getState(),n=r.config.githubUsername;if(!n)throw new Te("githubUsername is not configured; run setup first.");let{data:s}=await be(ke()).search.issuesAndPullRequests({q:`is:pr is:open author:${n} repo:${t}`,per_page:1});return Ff(r,t,{openPRCount:s.total_count})}var tF=A(()=>{"use strict";le();ee();xa();Ot()});function h3(e){if(e.length===0)return 0;let t=[...e].sort((n,s)=>n-s),r=Math.floor(t.length/2);return t.length%2===0?(t[r-1]+t[r])/2:t[r]}function y3(e){return e.isArchived?0:Math.min(1,e.commitsLast30Days/30)}function b3(e){if(e.prMergeTimesDays.length===0)return 0;let t=e.prMergeTimesDays.reduce((r,n)=>r+n,0)/e.prMergeTimesDays.length;return t<=0?1:t>=14?0:Math.max(0,Math.min(1,(14-t)/14))}function w3(e){if(e.openedCount90Days===0)return 0;let t=e.mergedCount90Days/e.openedCount90Days;return Math.max(0,Math.min(1,t))}function R3(e){let t=0;return e.hasContributing&&(t+=.4),e.hasIssueTemplates&&(t+=.25),e.hasPRTemplate&&(t+=.25),e.hasCodeOfConduct&&(t+=.1),Math.min(1,t)}function S3(e){if(e.isArchived)return 0;let t=.5;if(e.lastReleaseISO){let r=Date.now()-new Date(e.lastReleaseISO).getTime(),n=1e3*60*60*24*30*6;r<=n&&(t+=.5)}return t}function _3(e){if(e.isArchived)return!0;if(e.lastCommitISO){let t=Date.now()-new Date(e.lastCommitISO).getTime(),r=1440*60*60*1e3;if(t>r)return!0}return e.openedCount90Days>0&&e.mergedCount90Days===0}function v3(e,t){return t?"avoid":e>=rF.recommended?"recommended":e>=rF.cautious?"proceed_with_caution":"avoid"}function nF(e){let t={activity:y3(e),prSpeed:b3(e),mergeRate:w3(e),guidelines:R3(e),stability:S3(e)},r=t.activity*cn.activity+t.prSpeed*cn.prSpeed+t.mergeRate*cn.mergeRate+t.guidelines*cn.guidelines+t.stability*cn.stability,n=Math.round(r/g3*100)/10,s=e.prMergeTimesDays.length,o=s===0?null:e.prMergeTimesDays.reduce((u,d)=>u+d,0)/s,i=s===0?null:h3(e.prMergeTimesDays),a=e.openedCount90Days===0?null:Math.min(100,e.mergedCount90Days/e.openedCount90Days*100),c=v3(n,_3(e));return{repo:{stars:e.stars,forks:e.forks,openIssues:e.openIssues,watchers:e.watchers,isArchived:e.isArchived,lastPushed:e.lastPushed,createdAt:e.createdAt},prMergeTime:{avgDays:o,medianDays:i,sampleSize:s,sourceWindowDays:90},mergeRate:{merged:e.mergedCount90Days,opened:e.openedCount90Days,percent:a,windowDays:90},maintainerActivity:{lastCommitISO:e.lastCommitISO,contributorsLast90d:e.contributorsLast90d,lastReleaseISO:e.lastReleaseISO},communityHealth:{contributing:e.hasContributing,issueTemplates:e.hasIssueTemplates,prTemplate:e.hasPRTemplate,codeOfConduct:e.hasCodeOfConduct},rubricScore:n,rubricVerdict:c}}var cn,g3,rF,sF=A(()=>{"use strict";cn={activity:.25,prSpeed:.25,mergeRate:.2,guidelines:.1,stability:.05},g3=cn.activity+cn.prSpeed+cn.mergeRate+cn.guidelines+cn.stability,rF={recommended:7.5,cautious:5}});var oF={};re(oF,{runRepoVet:()=>$3});async function C3(e,t,r,n){try{return await e.repos.getContent({owner:t,repo:r,path:n}),!0}catch(s){if(s.status===404)return!1;throw s}}async function P3(e,t,r){let n={hasContributing:!1,hasIssueTemplates:!1,hasPRTemplate:!1,hasCodeOfConduct:!1},s=!1;return await Promise.all(k3.map(async({key:o,candidates:i})=>{let a=!1;for(let c of i)try{if(await C3(e,t,r,c)){n[o]=!0;return}}catch(u){v(lC,`community-health probe for ${t}/${r}/${c} failed: ${I(u)}`),a=!0;continue}a&&(s=!0)})),{hasContributing:n.hasContributing,hasIssueTemplates:n.hasIssueTemplates,hasPRTemplate:n.hasPRTemplate,hasCodeOfConduct:n.hasCodeOfConduct,incomplete:s}}function E3(e){try{let t=L(),r=t.getRepoScore(e);if(r)return r.score;let n=e.toLowerCase();return Object.values(t.getState().repoScores).find(o=>o.repo.toLowerCase()===n)?.score}catch(t){v(lC,`History-score lookup skipped (state unavailable): ${I(t)}`);return}}function A3(e,t,r){let n=r.getTime()-t*Eg,s=[],o=0,i=0;for(let a of e){let c=new Date(a.created_at).getTime();if(c>=n&&(i+=1),a.merged_at){let u=new Date(a.merged_at).getTime();if(u>=n){o+=1;let d=(u-c)/Eg;Number.isFinite(d)&&d>=0&&s.push(d)}}}return{prMergeTimesDays:s,mergedCount:o,openedCount:i}}function T3(e,t){let r=t.getTime()-30*Eg,n=t.getTime()-90*Eg,s=new Set,o=0,i=null;for(let a of e){let c=a.commit.author?.date;if(!c)continue;let u=new Date(c).getTime();Number.isNaN(u)||((i===null||u>i)&&(i=u),u>=r&&(o+=1),u>=n&&a.author?.login&&s.add(a.author.login))}return{commitsLast30Days:o,contributorsLast90d:s.size,lastCommitISO:i?new Date(i).toISOString():null}}async function $3(e){mf(e.repo);let[t,r]=e.repo.split("/",2),n=ke(),s=be(n),o=new Date,i=!1,[a,c,u,d,p]=await Promise.all([s.repos.get({owner:t,repo:r}),s.pulls.list({owner:t,repo:r,state:"closed",sort:"updated",direction:"desc",per_page:100}),s.repos.listCommits({owner:t,repo:r,per_page:100}),s.repos.listReleases({owner:t,repo:r,per_page:1}).catch(M=>{if(de(M))throw M;let G={data:[]};return Ue(M)===404||(i=!0,v(lC,`release listing for ${t}/${r} failed: ${I(M)} \u2014 release-recency signal is incomplete`)),G}),P3(s,t,r)]),m=c.data.map(M=>({created_at:M.created_at,merged_at:M.merged_at,updated_at:M.updated_at})),{prMergeTimesDays:f,mergedCount:g,openedCount:h}=A3(m,90,o),b=T3(u.data,o),w=d.data,y=w.length>0?w[0].published_at??w[0].created_at??null:null,S={stars:a.data.stargazers_count??0,forks:a.data.forks_count??0,openIssues:a.data.open_issues_count??0,watchers:a.data.subscribers_count??0,isArchived:a.data.archived??!1,lastPushed:a.data.pushed_at??new Date(0).toISOString(),createdAt:a.data.created_at??new Date(0).toISOString(),commitsLast30Days:b.commitsLast30Days,prMergeTimesDays:f,mergedCount90Days:g,openedCount90Days:h,lastCommitISO:b.lastCommitISO,contributorsLast90d:b.contributorsLast90d,lastReleaseISO:y,hasContributing:p.hasContributing,hasIssueTemplates:p.hasIssueTemplates,hasPRTemplate:p.hasPRTemplate,hasCodeOfConduct:p.hasCodeOfConduct},k=nF(S),{repo:R,communityHealth:P,maintainerActivity:C,...E}=k,T=E3(e.repo);return{repoSlug:e.repo,fetchedAt:o.toISOString(),repoMeta:R,communityHealth:{...P,incomplete:p.incomplete},maintainerActivity:{...C,releasesIncomplete:i},...E,...T!==void 0&&{historyScore:T}}}var lC,Eg,k3,iF=A(()=>{"use strict";le();ee();ce();Ot();sF();lC="repo-vet",Eg=864e5,k3=[{key:"hasContributing",candidates:["CONTRIBUTING.md",".github/CONTRIBUTING.md"]},{key:"hasIssueTemplates",candidates:[".github/ISSUE_TEMPLATE"]},{key:"hasPRTemplate",candidates:[".github/pull_request_template.md","pull_request_template.md","PULL_REQUEST_TEMPLATE.md"]},{key:"hasCodeOfConduct",candidates:["CODE_OF_CONDUCT.md",".github/CODE_OF_CONDUCT.md"]}]});var cF={};re(cF,{runDetectFormatters:()=>O3});async function O3(e){let t=dC.resolve(e.repoPath??process.cwd()),r={...ju(t)};if(e.ciLog){let n;try{n=aF.readFileSync(dC.resolve(e.ciLog),"utf8")}catch(s){throw new Error(`Failed to read CI log file: ${I(s)}`,{cause:s})}r.ciDiagnosis=nf(n,t)}return r}var aF,dC,uF=A(()=>{"use strict";aF=B(require("node:fs"),1),dC=B(require("node:path"),1);W_();ee()});var RF={};re(RF,{PREP_REF_PREFIX:()=>Al,PrepNamespaceError:()=>Qa,buildPrepRef:()=>yF,compareUrlFor:()=>bF,parseRemoteOwner:()=>fF,parseRemotesOutput:()=>gF,prepBranchName:()=>pC,resolvePushRemote:()=>hF,runOvernightPushPrep:()=>L3});function fF(e){let t=e.trim().match(I3);return t?{owner:t[1],repo:t[2]}:null}function gF(e){let t=[];for(let r of e.split(`
336
- `)){let n=r.match(/^(\S+)\s+(\S+)\s+\(push\)$/);n&&t.push({name:n[1],url:n[2]})}return t}function hF(e,t){let r=new Map;for(let n of e)r.set(n.name,(r.get(n.name)??0)+1);for(let n of e){if(n.name.startsWith("-")||r.get(n.name)!==1)continue;let s=fF(n.url);if(s&&s.owner.toLowerCase()===t.toLowerCase())return{remote:n.name,...s}}return null}function mC(e){if(!e.startsWith(Al)||e.length===Al.length)throw new Qa(e)}function yF(e){if(e.length===0||e.startsWith("/")||e.endsWith("/")||e.endsWith(".lock")||e.includes("//")||e.includes("..")||e.includes("@{")||/[\s~^:?*[\\]/.test(e)||[...e].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===127))throw new Error(`Refusing to build a prep ref from branch "${e}": not a valid ref name`);let t=`${Al}${e}`;return mC(t),t}function pC(e){return mC(e),e.slice(11)}function bF(e,t,r){return`https://github.com/${e.owner}/${e.repo}/compare/${t}...${r}`}function lF(e,t){return(0,dF.execFileSync)("git",["-C",e,...t],{encoding:"utf8",timeout:mF,stdio:["ignore","pipe","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}function wF(e){let t=e?.stderr;return typeof t=="string"?t.trim():""}function x3(e){return/non-fast-forward|fetch first/.test(wF(e))}function D3(e){let t=e?.code==="ETIMEDOUT",r=wF(e).split(`
337
- `).slice(-3).join(" | ");return`push failed: ${t?`timed out after ${mF/1e3}s (the ref may still have landed; the next run re-checks)`:I(e)}${r?` [git: ${r}]`:""}`}function Tg(e,t,r,n,s){return v(Ag,`${e==="failed"?"Failed":"Skipping"} ${t.branch} for ${t.url}: ${r}`),{url:t.url,branch:t.branch,status:e,...n?{remote:n.remote,repo:`${n.owner}/${n.repo}`}:{},...s?{ref:s}:{},reason:r}}function jo(e,t,r,n){return Tg("skipped",e,t,r,n)}async function L3(e){du("push prepared branches");let t=L(),r=Ta(),n=r?Wx(r):null,s=n?{...n.record,reportPath:pF.join(ji(),`overnight-${tl(new Date(n.record.runAt))}.md`)}:t.getLastOvernight();if(!s)throw new Error("No overnight run recorded yet; run `overnight` first.");let o=s;n?.report!=null&&!e.dryRun&&$g.writeFileSync(o.reportPath,n.report,{mode:384});let i=be(ke()),{data:a}=await i.users.getAuthenticated(),c=a.login?.trim();if(!c)throw new Error("Could not read the authenticated login from the token; refusing to push anywhere.");let u=t.getState().config.githubUsername;if(u&&u.toLowerCase()!==c.toLowerCase())throw new Error(`Configured githubUsername "${u}" does not match the token's login "${c}"; refusing to push anywhere.`);let d=new Map;async function p(C,E){let T=`${C.owner}/${C.repo}|${E??""}`.toLowerCase(),M=d.get(T);if(M!==void 0)return M;let G;try{let{data:X}=await i.repos.get({owner:C.owner,repo:C.repo});X.fork?X.owner.login.toLowerCase()!==c.toLowerCase()?G=`${C.owner}/${C.repo} resolved to ${X.full_name}, not owned by ${c}`:E&&X.parent?.full_name?.toLowerCase()!==E.toLowerCase()?G=`${X.full_name} is not a fork of ${E}`:G=null:G=`${C.owner}/${C.repo} is not a fork`}catch(X){if(zt(X))throw X;G=`could not read ${C.owner}/${C.repo}: ${I(X)}`}return d.set(T,G),G}let m=new Map;function f(C){let E=q(C);if(!E||E.type!=="pull")return Promise.resolve(void 0);let T=m.get(C);return T||(T=i.pulls.get({owner:E.owner,repo:E.repo,pull_number:E.number}).then(({data:M})=>M.head).catch(M=>{if(zt(M))throw M;v(Ag,`Could not read the head of ${C}: ${I(M)}`)}),m.set(C,T)),T}async function g(C){let E=q(C);if(!E)return`${C} is not a GitHub PR or issue URL`;let T=`${E.owner}/${E.repo}`,M=c,G=E.repo;if(E.type==="pull"){let X=(await f(C))?.repo;if(!X)return`could not read the head repository of ${C}`;if(X.owner.login.toLowerCase()!==c.toLowerCase())return`the head of ${C} is ${X.full_name}, not a repo owned by ${c}`;M=X.owner.login,G=X.name}return{target:{owner:M,repo:G,remote:`https://github.com/${M}/${G}.git`},upstream:T}}async function h(C){let E,T;if(r){let Z=await g(C.url);if(typeof Z=="string")return jo(C,Z);({target:E,upstream:T}=Z)}else{if(!C.worktree)return jo(C,"no worktree recorded");if(!$g.existsSync(C.worktree))return jo(C,`worktree ${C.worktree} does not exist`);let Z=hF(gF(lF(C.worktree,["remote","-v"])),c);if(!Z)return jo(C,`no remote in ${C.worktree} is owned by ${c}`);E=Z}let M=await p(E,T);if(M)return jo(C,M,E);let G;try{G=yF(C.branch)}catch(Z){if(Z instanceof Qa)throw Z;return jo(C,I(Z),E)}let X=pC(G),ve=(await f(C.url))?.ref,he={url:C.url,branch:C.branch,remote:E.remote,repo:`${E.owner}/${E.repo}`,ref:G,...ve?{compareUrl:bF(E,ve,X)}:{}};if(e.dryRun)return{...he,status:"planned"};mC(G);let oe;try{oe=r?Vx(r,C.branch):{repo:C.worktree,cleanup:()=>{}}}catch(Z){return Tg("failed",C,`bundle import failed: ${I(Z)}`,E,G)}try{lF(oe.repo,["push","--no-follow-tags","--",E.remote,`refs/heads/${C.branch}:${G}`])}catch(Z){return x3(Z)?jo(C,`non-fast-forward: ${X} on ${E.remote} has commits this worktree lacks; not forced`,E,G):Tg("failed",C,D3(Z),E,G)}finally{oe.cleanup()}return{...he,status:"pushed"}}let b=[],w=[...s.prepared],y=!1,S=null,k=null;async function R(){if(e.dryRun)return;let C=()=>t.setLastOvernight({...t.getLastOvernight()??o,prepared:w});C();try{y=_f(o.reportPath,w).reportRecreated}catch(E){S=`could not rewrite ${o.reportPath}: ${I(E)}`,v(Ag,S)}S||rl(t,o.reportPath),k=await we(t,Ag,C)}try{for(let[C,E]of s.prepared.entries()){let T;try{T=await h(E)}catch(M){if(M instanceof Qa||zt(M))throw M;T=Tg("failed",E,I(M))}if(b.push(T),T.status==="pushed"&&T.ref){let{pushProblem:M,...G}=E;w[C]={...G,pushedRef:pC(T.ref),pushedAt:new Date().toISOString(),...T.compareUrl?{compareUrl:T.compareUrl}:{}}}else T.status!=="planned"&&T.reason&&(w[C]={...E,pushProblem:T.reason})}}finally{await R()}let P=C=>b.filter(E=>E.status===C).length;return{dryRun:e.dryRun,login:c,reportPath:s.reportPath,results:b,pushed:P("pushed"),planned:P("planned"),skipped:P("skipped"),failed:P("failed"),...y?{reportRecreated:!0}:{},...S?{reportWarning:S}:{},...k?{gistSyncWarning:k}:{}}}var dF,$g,pF,Ag,Al,mF,Qa,I3,SF=A(()=>{"use strict";dF=require("node:child_process"),$g=B(require("node:fs"),1),pF=B(require("node:path"),1);le();ee();ce();Vr();Ov();bs();Ag="overnight-push-prep",Al="refs/heads/prep/",mF=6e4,Qa=class extends Error{constructor(t){super(`Internal error: refusing to push ref "${t}" outside ${Al}`),this.name="PrepNamespaceError"}},I3=/^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com(?::\d+)?\/)([\w-]+)\/([\w.-]+?)(?:\.git)?\/?$/i});var _F={};re(_F,{formatStatsBadge:()=>G3,formatStatsMarkdown:()=>F3,runStats:()=>M3});async function M3(){let t=L().getState(),r=t.lastDigest?.summary?.totalActivePRs??0,n=Gm({repoScores:t.repoScores??{},activePRCount:r});return{...n,mergeRateFormatted:`${(n.mergeRate*100).toFixed(1)}%`,username:t.config.githubUsername}}function F3(e){let t=[`# OSS Contribution Stats for @${e.username}`,"","| Metric | Value |","|--------|-------|",`| Merged PRs | ${e.totalMerged} |`,`| Merge Rate | ${e.mergeRateFormatted} |`,`| Active PRs | ${e.activePRs} |`,`| Repos Contributed | ${e.reposContributed} |`,""];if(e.topRepos.length>0){t.push("## Top Repos","","| Repo | Merged PRs |","|------|-----------|");for(let r of e.topRepos)t.push(`| ${r.repo} | ${r.mergedCount} |`);t.push("")}return t.push("---","*Generated by [OSS Autopilot](https://github.com/costajohnt/oss-autopilot)*"),t.join(`
338
- `)}function N3(e){return e.totalMerged===0?"blue":e.mergeRate>=.8?"brightgreen":e.mergeRate>=.6?"green":e.mergeRate>=.4?"yellow":"orange"}function G3(e){return{schemaVersion:1,label:"OSS Contributions",message:e.totalMerged>0?`${e.mergeRateFormatted} merge rate | ${e.totalMerged} merged`:"Getting Started",color:N3(e)}}var vF=A(()=>{"use strict";le();N_()});var zo={};re(zo,{runFetchCorpus:()=>Z3,runGuidelinesList:()=>H3,runGuidelinesReset:()=>q3,runGuidelinesStore:()=>W3,runGuidelinesView:()=>B3,runMarkExtracted:()=>V3});function $l(e){if(!U3.test(e))throw new Error(`Invalid repo identifier "${e}". Expected "owner/repo" format.`)}async function B3(e){$l(e.repo);let t=L(),r=t.getGuidelines(e.repo);return{repo:e.repo,content:r,agentContent:r===null?null:Du(r),byteSize:r===null?0:Buffer.byteLength(r,"utf8"),exists:r!==null,storageMode:t.isGuidelinesAvailable()?"gist":"local-unavailable"}}async function H3(){let e=L(),t=e.listGuidelinesRepos();return{repos:t,count:t.length,storageMode:e.isGuidelinesAvailable()?"gist":"local-unavailable"}}async function W3(e){if($l(e.repo),!e.content||e.content.length===0)throw new Error("Cannot store empty content. Use `guidelines reset` to delete a guidelines file.");let t=L();t.setGuidelines(e.repo,e.content);let r=await we(t,Tl,()=>t.setGuidelines(e.repo,e.content));return{repo:e.repo,byteSize:Buffer.byteLength(e.content,"utf8"),stored:!0,...r&&{gistSyncWarning:r}}}async function V3(e){$l(e.repo);let t=L(),r=`https://github.com/${e.repo}/`,n=new Date().toISOString(),s=()=>{let a=0;for(let c of[...t.getMergedPRs()??[],...t.getClosedPRs()??[]])!c.url.startsWith(r)||!c.commentsFetchedAt||c.learningsExtractedAt||(t.markPRLearningsExtracted(c.url,n),a++);return a},o=s(),i=o>0?await we(t,Tl,s):null;return{repo:e.repo,marked:o,...i&&{gistSyncWarning:i}}}async function q3(e){$l(e.repo);let t=L();if(!t.isGuidelinesAvailable())throw new rs;let r=t.getGuidelines(e.repo)!==null,n=null;return r&&(t.deleteGuidelines(e.repo),n=await we(t,Tl,()=>t.deleteGuidelines(e.repo))),{repo:e.repo,deleted:r,...n&&{gistSyncWarning:n}}}async function Z3(e){$l(e.repo);let t=K3(e.limit),r=L(),n=r.getMergedPRs()??[],s=r.getClosedPRs()??[],o=Date.now()-z3,i=[...n.map(k=>({url:k.url,timestamp:k.mergedAt,alreadyFetched:!!k.commentsFetchedAt})),...s.map(k=>({url:k.url,timestamp:k.closedAt,alreadyFetched:!!k.commentsFetchedAt}))],a=`https://github.com/${e.repo}/`,c=i.filter(k=>{if(!k.url.startsWith(a))return!1;let R=Date.parse(k.timestamp||"");return!(!Number.isFinite(R)||R<o)}),u=e.forceRefetch?0:c.filter(k=>k.alreadyFetched).length,d=(e.forceRefetch?c:c.filter(k=>!k.alreadyFetched)).sort((k,R)=>Date.parse(R.timestamp||"")-Date.parse(k.timestamp||"")).slice(0,t);if(d.length===0)return{repo:e.repo,bundles:[],prCount:0,skipped:u,failures:[]};let p=ke(),m=be(p),f=r.getState().config.githubUsername;f||v(Tl,"githubUsername is not set; bot/own-comment filtering will be incomplete");let{bundles:g,failures:h}=await sf(m,d.map(k=>k.url),f),b=new Date().toISOString(),w=()=>{for(let k of g)r.markPRCommentsFetched(k.prUrl,b)};w();let y=null;g.length>0&&(y=await we(r,Tl,w));let S=g.filter(k=>k.truncated).map(k=>`${k.prUrl}: comment streams hit the pagination cap; newest comments are missing from the corpus`);return{repo:e.repo,bundles:g,prCount:g.length,skipped:u,failures:h,...y&&{gistSyncWarning:y},...S.length>0&&{warnings:S}}}function K3(e){return e===void 0||!Number.isFinite(e)||e<1?kF:Math.min(e,j3)}var Tl,U3,kF,j3,z3,Bo=A(()=>{"use strict";le();Q_();ce();Tl="guidelines",U3=/^[^/]+\/[^/]+$/,kF=5,j3=10,z3=365*24*60*60*1e3});var Nn=class extends Error{constructor(t,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=t,this.nestedError=void 0}},As=class extends Nn{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var tc=class{constructor(t,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,r){return r===this.defaultValue||!Array.isArray(r)?[t]:(r.push(t),r)}default(t,r){return this.defaultValue=t,this.defaultValueDescription=r,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new As(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Ol(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}var vC=require("node:events"),xl=B(require("node:child_process"),1),Gr=B(require("node:path"),1),nc=B(require("node:fs"),1),Ae=B(require("node:process"),1),kC=require("node:util");var wC=require("node:util"),rc=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let r=t.commands.filter(s=>!s._hidden),n=t._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,o)=>s.name().localeCompare(o.name())),r}compareOptions(t,r){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(t).localeCompare(n(r))}visibleOptions(t){let r=t.options.filter(s=>!s.hidden),n=t._getHelpOption();if(n&&!n.hidden){let s=n.short&&t._findOption(n.short),o=n.long&&t._findOption(n.long);!s&&!o?r.push(n):n.long&&!o?r.push(t.createOption(n.long,n.description)):n.short&&!s&&r.push(t.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let r=[];for(let n=t.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(r=>{r.description=r.description||t._argsDescription[r.name()]||""}),t.registeredArguments.find(r=>r.description)?t.registeredArguments:[]}subcommandTerm(t){let r=t.registeredArguments.map(n=>Ol(n)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,r){return r.visibleCommands(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(s)))),0)}longestOptionTermLength(t,r){return r.visibleOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestGlobalOptionTermLength(t,r){return r.visibleGlobalOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestArgumentTermLength(t,r){return r.visibleArguments(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(s)))),0)}commandUsage(t){let r=t._name;t._aliases[0]&&(r=r+"|"+t._aliases[0]);let n="";for(let s=t.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&r.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&r.push(`env: ${t.envVar}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}argumentDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatItemList(t,r,n){return r.length===0?[]:[n.styleTitle(t),...r,""]}groupItems(t,r,n){let s=new Map;return t.forEach(o=>{let i=n(o);s.has(i)||s.set(i,[])}),r.forEach(o=>{let i=n(o);s.has(i)||s.set(i,[]),s.get(i).push(o)}),s}formatHelp(t,r){let n=r.padWidth(t,r),s=r.helpWidth??80;function o(p,m){return r.formatItem(p,n,m,r)}let i=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(t))}`,""],a=r.commandDescription(t);a.length>0&&(i=i.concat([r.boxWrap(r.styleCommandDescription(a),s),""]));let c=r.visibleArguments(t).map(p=>o(r.styleArgumentTerm(r.argumentTerm(p)),r.styleArgumentDescription(r.argumentDescription(p))));if(i=i.concat(this.formatItemList("Arguments:",c,r)),this.groupItems(t.options,r.visibleOptions(t),p=>p.helpGroupHeading??"Options:").forEach((p,m)=>{let f=p.map(g=>o(r.styleOptionTerm(r.optionTerm(g)),r.styleOptionDescription(r.optionDescription(g))));i=i.concat(this.formatItemList(m,f,r))}),r.showGlobalOptions){let p=r.visibleGlobalOptions(t).map(m=>o(r.styleOptionTerm(r.optionTerm(m)),r.styleOptionDescription(r.optionDescription(m))));i=i.concat(this.formatItemList("Global Options:",p,r))}return this.groupItems(t.commands,r.visibleCommands(t),p=>p.helpGroup()||"Commands:").forEach((p,m)=>{let f=p.map(g=>o(r.styleSubcommandTerm(r.subcommandTerm(g)),r.styleSubcommandDescription(r.subcommandDescription(g))));i=i.concat(this.formatItemList(m,f,r))}),i.join(`
330
+ `),{content:f,moved:!0,fromTier:c[0].tier,count:c.length}}async function qK(e){let t=iM.resolve(e.listPath);if(!sn.existsSync(t))throw new Error(`File not found: ${t}`);let r;try{r=sn.readFileSync(t,"utf8")}catch(s){throw new Error(`Failed to read file: ${I(s)}`,{cause:s})}let n=uM(r,e.issueUrl,e.tier);if(n.reasonCode==="not-found")throw new j(`Issue URL not found in the list: ${e.issueUrl} (${t}). Add the entry to the list first, then re-run list-move-tier.`);if(n.moved){let s=`${t}.tmp-${process.pid}-${Date.now()}`;try{sn.writeFileSync(s,n.content,"utf8"),sn.renameSync(s,t)}catch(o){try{sn.unlinkSync(s)}catch{}throw new Error(`Failed to write file: ${I(o)}`,{cause:o})}}return{moved:n.moved,filePath:t,url:e.issueUrl,toTier:e.tier,fromTier:n.fromTier,count:n.count,reason:n.reason}}var sn,iM,aM,dM=A(()=>{"use strict";sn=B(require("node:fs"),1),iM=B(require("node:path"),1);ee();gf();aM={pursue:"## Pursue",maybe:"## Maybe",skip:"## Skip"}});var pM={};re(pM,{runTrack:()=>ZK});async function ZK(e){Ze(e.prUrl),Qe(e.prUrl,tr,"PR");let t=ke(),r=be(t),n=q(e.prUrl);if(!n||n.type!=="pull")throw new j(`Invalid PR URL: ${e.prUrl}`);let{owner:s,repo:o,number:i}=n,{data:a}=await r.pulls.get({owner:s,repo:o,pull_number:i});return{pr:{repo:`${s}/${o}`,number:i,title:a.title,url:e.prUrl}}}var mM=A(()=>{"use strict";le();ee();Ot();nt()});var Rg,Sg,joe,rC=A(()=>{"use strict";Rg={passFiles:10,passLines:400,warnFiles:20,warnLines:800},Sg=72,joe=[{id:"issueReference",label:"Issue Reference",description:"PR links to issue (`Closes #X` or `Fixes #X`)",tier:"required",weight:25},{id:"description",label:"Description Quality",description:"Explains what changed and why",tier:"required",weight:25},{id:"title",label:"Title Quality",description:"Descriptive, properly formatted (e.g., `fix: resolve login timeout`)",tier:"required",weight:10},{id:"focusedChanges",label:"Focused Changes",description:`One logical change per PR (< ${Rg.passFiles} files, < ${Rg.passLines} lines ideal)`,tier:"required",weight:20},{id:"minimalDiff",label:"Minimal Diff",description:"No unrelated formatting changes (whitespace, quotes, imports, trailing commas)",tier:"required",weight:null},{id:"tests",label:"Tests Included",description:"Only when the change has behavior to guard (bug fix, new logic); never filler",tier:"conditional",weight:15},{id:"docs",label:"Docs Updated",description:"If behavior changed, update docs",tier:"conditional",weight:null},{id:"branch",label:"Branch Naming",description:"Follows convention (`feature/`, `fix/`, `docs/`)",tier:"optional",weight:5},{id:"screenshots",label:"Screenshots",description:"Only for visible changes when the template or a maintainer asks",tier:"optional",weight:null}]});function e6(e,t){if(t.length===0)return null;let r=t.find(a=>a.state==="not_found");if(r){let a=r.crossRepo?`${r.repo}#${r.number}`:`#${r.number}`;return{status:"fail",weight:e,detail:`linked issue ${a} does not exist \u2014 typo or wrong repo?`}}let n=t.filter(a=>a.state!=="unverifiable");if(n.length===0)return{status:"warn",weight:e,detail:`linked issue${t.length>1?"s":""} could not be verified (rate limit or network) \u2014 confirm manually`};let s=n.find(a=>a.state==="closed"&&(a.closedDaysAgo??0)>KK);if(s)return{status:"fail",weight:e,detail:`linked issue #${s.number} has been closed for ${s.closedDaysAgo} days \u2014 reference is probably stale`};let o=n.find(a=>a.state==="closed");if(o)return{status:"warn",weight:e,detail:`linked issue #${o.number} was closed ${o.closedDaysAgo??"?"} days ago \u2014 confirm this PR is still relevant`};let i=n.find(a=>a.crossRepo);return i?{status:"warn",weight:e,detail:`cross-repo reference ${i.repo}#${i.number} \u2014 verify the linked issue applies to changes in this repo`}:{status:"pass",weight:e,detail:`linked issue${n.length>1?"s":""} verified open`}}function t6(e,t){let r=Ja.issueReference,n=YK.test(e.body);if(!(n||QK.test(e.body)||XK.test(e.body)||(t?.linkedIssues?.length??0)>0))return{status:"fail",weight:r,detail:"no issue reference"};let o=t?.linkedIssues?e6(r,t.linkedIssues):null;return o||(n?{status:"pass",weight:r,detail:"closing keyword present"}:{status:"warn",weight:r,detail:"issue referenced without a closing keyword"})}function o6(e){let t=[],r,n=0;for(let s of e.split(`
331
+ `)){let o=/^ {0,3}(`{3,})/.exec(s)?.[1].length??0;o>0&&!r?r={start:n,len:o}:o>0&&r&&o>=r.len&&(t.push([r.start,n+s.length]),r=void 0),n+=s.length+1}return t}function i6(e,t,r){let n=[...e.slice(t,r).matchAll(/`+/g)].map(c=>({start:t+c.index,len:c[0].length})),s=new Map,o=new Map;for(let c=n.length-1;c>=0;c--){let u=o.get(n[c].len);u!==void 0&&s.set(c,u),o.set(n[c].len,c)}let i=[],a=0;for(;a<n.length;){let c=s.get(a);c===void 0?a+=1:(i.push([n[a].start,n[c].start+n[c].len]),a=c+1)}return i}function a6(e){let t=new Uint8Array(e.length),r=o6(e),n=[],s=0;for(let[i,a]of r)n.push([s,i]),s=a;n.push([s,e.length]);let o=n.flatMap(([i,a])=>i6(e,i,a));for(let[i,a]of[...r,...o])t.fill(1,i,a);return t}function c6(e){let t=a6(e),r="",n=!0,s=0;for(;s<e.length;){let o=n&&t[s]===0&&e.startsWith("<!--",s)?e.indexOf("-->",s+4):-1;o===-1?(t[s]===0&&e.startsWith("<!--",s)&&(n=!1),r+=e[s],s+=1):s=o+3}return r.replaceAll(/^ {0,3}#{1,6}[ \t]+[^\n]{0,60}$/gm,o=>/[.!?。]\s*$/.test(o)?o:"").replaceAll(s6,"").trim()}function u6(e){let t=Ja.description;if(e.body.trim().length===0)return{status:"fail",weight:t,detail:"description is empty"};let n=c6(e.body),s=r6.test(e.body)||n6.test(e.body);return n.length>=80||s&&new RegExp("\\p{L}","u").test(n)?{status:"pass",weight:t,detail:"describes the change"}:{status:"warn",weight:t,detail:"short description; say what changed and why"}}function l6(e){let t=Ja.focusedChanges,r=e.additions+e.deletions,n=`${e.filesChangedCount} files, ${r} lines`;return e.filesChangedCount<_g.passFiles&&r<_g.passLines?{status:"pass",weight:t,detail:n}:e.filesChangedCount>_g.warnFiles||r>_g.warnLines?{status:"fail",weight:t,detail:`${n} \u2014 needs splitting`}:{status:"warn",weight:t,detail:n}}function p6(e,t){let r=Ja.tests;return e.files.some(s=>d6.test(s))?{status:"pass",weight:r,detail:"test file(s) touched"}:t?.hasTestInfrastructure===!1?{status:"warn",weight:r,detail:"no tests, but project has no visible test infrastructure"}:{status:"warn",weight:r,detail:"no test files; fine if nothing testable changed, a bug fix needs a regression test"}}function y6(e){let t=e.trim();return!!(f6.has(t.toLowerCase())||g6.test(t)||h6.test(t))}function b6(e){let t=Ja.title,r=e.title.length;return y6(e.title)?{status:"fail",weight:t,detail:"vague or placeholder title"}:r>Sg?{status:"warn",weight:t,detail:`title is ${r} chars (budget: ${Sg})`}:m6.test(e.title)?{status:"pass",weight:t,detail:"descriptive, conventional, within budget"}:{status:"warn",weight:t,detail:"descriptive but not conventional commit format"}}function S6(e){let t=Ja.branch;return R6.test(e.branch)||w6.test(e.branch)?{status:"fail",weight:t,detail:`non-descriptive branch name "${e.branch}"`}:/[/_-]/.test(e.branch)?{status:"pass",weight:t,detail:e.branch}:{status:"warn",weight:t,detail:`branch "${e.branch}" lacks a clear separator`}}function _6(e){return e>=nC.ready?{rating:"ready",emoji:"\u{1F31F}"}:e>=nC.minor?{rating:"minor",emoji:"\u2705"}:e>=nC.fixFirst?{rating:"fix_first",emoji:"\u26A0\uFE0F"}:{rating:"significant_work",emoji:"\u274C"}}function fM(e,t){let r={issueReference:t6(e,t),description:u6(e),focusedChanges:l6(e),tests:p6(e,t),title:b6(e),branch:S6(e)},n=Object.values(r).reduce((a,c)=>a+JK[c.status]*c.weight,0),s=Math.round(n),{rating:o,emoji:i}=_6(s);return{score:s,rating:o,emoji:i,checks:r}}var KK,Ja,JK,_g,nC,YK,QK,XK,r6,n6,s6,d6,m6,f6,g6,h6,w6,R6,gM=A(()=>{"use strict";rC();rC();KK=30,Ja={issueReference:25,description:25,focusedChanges:20,tests:15,title:10,branch:5},JK={pass:1,warn:.5,fail:0},_g=Rg,nC={ready:90,minor:75,fixFirst:60},YK=/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#\d+/i,QK=/\b(?:relates?\s+to|see|refs?|references?)\s+#\d+/i,XK=/https?:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+/i;r6=/(?:^|\n)#{1,3}\s*(?:summary|overview|what(?:\s+changed)?)\b/i,n6=/(?:^|\n)#{1,3}\s*(?:why|motivation|context|background|rationale)\b/i,s6=/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+(?:[\w.-]+\/[\w.-]+)?#\d+/gi;d6=/(?:^|\/)(?:tests?|__tests__|spec)\/|\.(?:test|spec)\.[cm]?[jt]sx?$|\.test_|_test\.(?:go|py|rb)$|(?:^|\/)test_[^/]+\.py$|_spec\.rb$/i;m6=/^(?:feat|fix|chore|docs|refactor|test|perf|build|ci|style|revert)(?:\([^)]+\))?!?:\s+\S/i,f6=new Set(["wip","test","hello","tmp","temp","untitled"]),g6=/^[asdfqwer]+$/i,h6=/^update\s+\S+\s*$/i;w6=/^patch-\d+$/i,R6=/^(?:main|master)$/i});var hM={};re(hM,{runComplianceScore:()=>E6});async function k6(e,t,r){try{let{data:n}=await e.repos.getContent({owner:t,repo:r,path:""});if(!Array.isArray(n))return;let s=/^(?:tests?|__tests__|spec)$/i;return n.some(o=>o.type==="dir"&&s.test(o.name))}catch(n){if(de(n))throw n;v(v6,`test-infrastructure probe for ${t}/${r} failed: ${I(n)}`);return}}function C6(e,t,r){let n=new Map,s=(c,u,d)=>{let p=`${c}/${u}#${d}`;n.has(p)||n.set(p,{owner:c,repo:u,number:d})},o=/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?|relates?\s+to|refs?|references?|see)\s+#(\d+)/gi;for(let c of e.matchAll(o))s(t,r,Number.parseInt(c[1],10));let i=/\b([\w.-]+)\/([\w.-]+)#(\d+)/g;for(let c of e.matchAll(i))s(c[1],c[2],Number.parseInt(c[3],10));let a=/https?:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/gi;for(let c of e.matchAll(a))s(c[1],c[2],Number.parseInt(c[3],10));return[...n.values()]}async function P6(e,t,r,n=new Date){return Promise.all(r.map(async({owner:s,repo:o,number:i})=>{let a=s!==t.owner||o!==t.repo,c=`${s}/${o}`;try{let{data:u}=await e.issues.get({owner:s,repo:o,issue_number:i});if(u.state==="open")return{number:i,repo:c,crossRepo:a,state:"open"};let d=u.closed_at?new Date(u.closed_at):null,p=d?Math.floor((n.getTime()-d.getTime())/864e5):void 0;return{number:i,repo:c,crossRepo:a,state:"closed",closedDaysAgo:p}}catch(u){return u.status===404?{number:i,repo:c,crossRepo:a,state:"not_found"}:{number:i,repo:c,crossRepo:a,state:"unverifiable"}}}))}async function E6(e){Ze(e.prUrl),Qe(e.prUrl,tr,"PR");let t=ke(),r=be(t),n=q(e.prUrl);if(!n||n.type!=="pull")throw new j(`Invalid PR URL: ${e.prUrl}`);let{owner:s,repo:o,number:i}=n,[{data:a},c,u]=await Promise.all([r.pulls.get({owner:s,repo:o,pull_number:i}),r.pulls.listFiles({owner:s,repo:o,pull_number:i,per_page:100}),k6(r,s,o)]),d={title:a.title,body:a.body??"",branch:a.head.ref,filesChangedCount:a.changed_files,additions:a.additions,deletions:a.deletions,files:c.data.map(h=>h.filename)},p=C6(d.body,s,o),m=p.length>0?await P6(r,{owner:s,repo:o},p):void 0,g=fM(d,{hasTestInfrastructure:u,linkedIssues:m});return{pr:{repo:`${s}/${o}`,number:i,title:a.title,url:e.prUrl},score:g.score,rating:g.rating,emoji:g.emoji,checks:g.checks}}var v6,yM=A(()=>{"use strict";le();ee();ce();Ot();nt();gM();v6="compliance-score"});var vg={};re(vg,{runClaim:()=>$6,runComments:()=>A6,runPost:()=>T6});async function A6(e){Ze(e.prUrl),Qe(e.prUrl,tr,"PR");let t=ke(),r=L(),n=be(t),s=q(e.prUrl);if(!s||s.type!=="pull")throw new j("Invalid PR URL format");let{owner:o,repo:i,number:a}=s,{data:c}=await n.pulls.get({owner:o,repo:i,pull_number:a}),[u,d,p]=await Promise.all([je(T=>n.pulls.listReviewComments({owner:o,repo:i,pull_number:a,per_page:100,page:T})),je(T=>n.issues.listComments({owner:o,repo:i,issue_number:a,per_page:100,page:T})),je(T=>n.pulls.listReviews({owner:o,repo:i,pull_number:a,per_page:100,page:T}))]),{items:m}=u,{items:f}=d,{items:g}=p,h=[...p.truncated?["reviews"]:[],...u.truncated?["inline review comments"]:[],...d.truncated?["discussion comments"]:[]],b=r.getState().config.githubUsername,w=T=>!(!T.user||T.user.login?.toLowerCase()===b?.toLowerCase()||T.user.type==="Bot"&&!e.showBots),y=m.filter(w).sort((T,M)=>new Date(M.created_at).getTime()-new Date(T.created_at).getTime()),S=f.filter(w).sort((T,M)=>new Date(M.created_at).getTime()-new Date(T.created_at).getTime()),k=g.filter(T=>w(T)&&T.body&&T.body.trim()).sort((T,M)=>new Date(M.submitted_at||0).getTime()-new Date(T.submitted_at||0).getTime()),R=`${o}/${i}#${a}`,P=(T,M,G,X)=>st(T,R,{author:G,association:X,source:M}),C=r.getStateStaleness(),E=[];return h.length>0&&E.push({phase:"fetch",operation:"fetch PR comments (truncated)",message:`Pagination cap reached fetching ${h.join(", ")} for ${o}/${i}#${a}; the newest entries in those streams may be missing.`}),C&&E.push(An(C)),{pr:{title:c.title,state:c.state,mergeable:c.mergeable,head:c.head.ref,base:c.base.ref,url:c.html_url},reviews:k.map(T=>({user:T.user?.login,state:T.state,body:T.body==null?null:P(T.body,"pr-review",T.user?.login,T.author_association),submittedAt:T.submitted_at??null})),reviewComments:y.map(T=>({user:T.user?.login,body:P(T.body,"pr-review-comment",T.user?.login,T.author_association),path:T.path,createdAt:T.created_at})),issueComments:S.map(T=>({user:T.user?.login,body:T.body==null?T.body:P(T.body,"pr-issue-comment",T.user?.login,T.author_association),createdAt:T.created_at})),summary:{reviewCount:k.length,inlineCommentCount:y.length,discussionCommentCount:S.length},...E.length>0&&{warnings:E}}}async function T6(e){if(du("post a comment"),Ze(e.url),Qe(e.url,Ku,"issue or PR"),!e.message.trim())throw new j("No message provided");cv(e.message);let t=ke(),r=q(e.url);if(!r)throw new j("Invalid GitHub URL format");let{owner:n,repo:s,number:o}=r,i=be(t),{data:a}=await i.issues.createComment({owner:n,repo:s,issue_number:o,body:e.message});return{commentUrl:a.html_url,url:e.url}}async function $6(e){du("claim an issue"),Ze(e.issueUrl),Qe(e.issueUrl,dr,"issue");let t=ke(),r=e.message||"Hi! I'd like to work on this issue. Could you assign it to me?";cv(r);let n=q(e.issueUrl);if(!n||n.type!=="issues")throw new j("Invalid issue URL format (must be an issue, not a PR)");let{owner:s,repo:o,number:i}=n,a=be(t),c="(claimed)",u=[],d=new Date().toISOString();try{let{data:g}=await a.issues.get({owner:s,repo:o,issue_number:i});g.title&&(c=g.title),u=(g.labels??[]).map(h=>typeof h=="string"?h:h.name??"").filter(h=>!!h),g.created_at&&(d=g.created_at)}catch(g){if(de(g))throw g;v(sC,`Failed to enrich issue metadata (title/labels) for ${e.issueUrl}; claiming with placeholder: ${g instanceof Error?g.message:g}`)}let{data:p}=await a.issues.createComment({owner:s,repo:o,issue_number:i,body:r}),m=null,f;try{let g=L(),h={id:i,url:e.issueUrl,repo:`${s}/${o}`,number:i,title:c,status:"claimed",labels:u,createdAt:d,updatedAt:new Date().toISOString(),vetted:!1};g.addIssue(h),m=await we(g,sC,()=>g.addIssue(h))}catch(g){f=`Comment posted on ${e.issueUrl} but failed to save to local state: ${g instanceof Error?g.message:g}`,v(sC,f)}return{commentUrl:p.html_url,issueUrl:e.issueUrl,...m&&{gistSyncWarning:m},...f&&{stateSaveWarning:f}}}var sC,kg=A(()=>{"use strict";le();Cn();ee();ce();io();me();Ot();sC="comments"});var wM={};re(wM,{runConfig:()=>I6});function bM(e){if(!eo.includes(e))throw new Error(`Invalid scope "${e}". Valid scopes: ${eo.join(", ")}`);return e}async function I6(e){if(e.listKeys){if(e.key||e.value)throw new j("`--list-keys` cannot be combined with a key/value. Run `config --list-keys` on its own.");return{keys:bo}}let t=L();if(!e.key)return{config:t.getState().config};if(!e.value)throw new Error("Value required");let{key:r,value:n}=e,s=()=>x6(t,r,n);s();let o=await we(t,O6,s);return{success:!0,key:r,value:n,...o&&{gistSyncWarning:o}}}function x6(e,t,r){let n=e.getState().config;switch(t){case"username":{e.updateConfig({githubUsername:Pa(r)});break}case"add-language":{n.languages.includes(r)||e.updateConfig({languages:[...n.languages,r]});break}case"add-label":{n.labels.includes(r)||e.updateConfig({labels:[...n.labels,r]});break}case"remove-label":{if(!n.labels.includes(r))throw new Error(`Label "${r}" is not currently configured. Current labels: ${n.labels.join(", ")}`);e.updateConfig({labels:n.labels.filter(s=>s!==r)});break}case"add-scope":{let s=bM(r),o=n.scope??[];o.includes(s)||e.updateConfig({scope:[...o,s]});break}case"remove-scope":{let s=bM(r),o=n.scope??[];if(!o.includes(s))throw new Error(`Scope "${r}" is not currently set`);let i=o.filter(a=>a!==s);if(i.length===0)throw new Error("Cannot remove the last scope. Use setup to clear scopes entirely.");e.updateConfig({scope:i});break}case"exclude-repo":{let s=r.split("/");if(s.length!==2||!s[0]||!s[1])throw new Error(`Invalid repo format "${r}". Use "owner/repo" format. To exclude an entire org, use: config exclude-org ${r}`);let o=r.toLowerCase();n.excludeRepos.some(i=>i.toLowerCase()===o)||e.batch(()=>{e.updateConfig({excludeRepos:[...n.excludeRepos,r]}),e.cleanupExcludedData([r],[])});break}case"exclude-org":{if(r.includes("/"))throw new Error(`Invalid org name "${r}". Use just the org name (e.g., "facebook"), not "owner/repo" format. To exclude a specific repo, use: config exclude-repo ${r}`);let s=n.excludeOrgs??[];s.some(o=>o.toLowerCase()===r.toLowerCase())||e.batch(()=>{e.updateConfig({excludeOrgs:[...s,r]}),e.cleanupExcludedData([],[r])});break}case"add-avoid-repo":{let s=r.split("/");if(s.length!==2||!s[0]||!s[1])throw new Error(`Invalid repo format "${r}". Use "owner/repo" format.`);let o=n.avoidRepos??[],i=r.toLowerCase();o.some(a=>a.toLowerCase()===i)||e.updateConfig({avoidRepos:[...o,r]});break}case"remove-avoid-repo":{let s=n.avoidRepos??[],o=r.toLowerCase();if(!s.some(i=>i.toLowerCase()===o))throw new Error(`Repo "${r}" is not on the avoid list. Current avoid list: ${s.join(", ")||"(empty)"}`);e.updateConfig({avoidRepos:s.filter(i=>i.toLowerCase()!==o)});break}case"add-boost-issue-type":{let s=n.boostIssueTypes??[],o=r.toLowerCase();s.some(i=>i.toLowerCase()===o)||e.updateConfig({boostIssueTypes:[...s,r]});break}case"remove-boost-issue-type":{let s=n.boostIssueTypes??[],o=r.toLowerCase();if(!s.some(i=>i.toLowerCase()===o))throw new Error(`Issue type "${r}" is not on the boost list. Current boost list: ${s.join(", ")||"(empty)"}`);e.updateConfig({boostIssueTypes:s.filter(i=>i.toLowerCase()!==o)});break}case"issueListPath":{e.updateConfig({issueListPath:r||void 0});break}case"diffTool":{if(!to.includes(r))throw new Error(`Invalid diffTool "${r}". Valid options: ${to.join(", ")}`);e.updateConfig({diffTool:r});break}case"diffToolCustomCommand":{e.updateConfig({diffToolCustomCommand:r||void 0});break}default:throw new j(wo(t,"config"))}}var O6,RM=A(()=>{"use strict";le();ee();ts();Ot();O6="config"});var SM={};re(SM,{runInit:()=>L6});async function L6(e){Pa(e.username);let t=L(),r=()=>t.updateConfig({githubUsername:e.username});r();let n=await we(t,D6,r);return{username:e.username,message:"Username saved. Run `daily` to fetch your open PRs from GitHub.",...n&&{gistSyncWarning:n}}}var D6,_M=A(()=>{"use strict";le();Ot();D6="init"});var oC={};re(oC,{runCheckSetup:()=>N6,runSetup:()=>F6});function vl(e,t){let r=Number(e);if(!Number.isInteger(r)||r<1)throw new j(`Invalid value for ${t}: "${e}". Must be a positive integer.`);return r}function vM(e,t){let r=Number(e);if(!Number.isInteger(r)||r<0)throw new j(`Invalid value for ${t}: "${e}". Must be a non-negative integer.`);return r}async function F6(e){let t=L(),r=t.getState().config;if(e.set&&e.set.length>0){let n={},s=[],o=new Set(zu());for(let c of e.set){let[u]=c.split("=",1);if(!o.has(u))throw new j(wo(u,"setup"))}let i=()=>{s.length=0;for(let c of e.set){let[u,...d]=c.split("="),p=d.join("=");switch(u){case"username":{Pa(p),t.updateConfig({githubUsername:p}),n[u]=p;break}case"maxActivePRs":case"maxOpenPRsPerRepo":case"maxOpenPRsColdRepo":case"maxConcurrentImplementations":{let m=vM(p,u);t.updateConfig({[u]:m}),n[u]=String(m);break}case"dormantDays":{let m=vl(p,"dormantDays");t.updateConfig({dormantThresholdDays:m}),n[u]=String(m);break}case"approachingDays":{let m=vl(p,"approachingDays");t.updateConfig({approachingDormantDays:m}),n[u]=String(m);break}case"languages":{t.updateConfig({languages:p.split(",").map(m=>m.trim())}),n[u]=p;break}case"labels":{t.updateConfig({labels:p.split(",").map(m=>m.trim())}),n[u]=p;break}case"squashByDefault":{p==="ask"?(t.updateConfig({squashByDefault:"ask"}),n[u]="ask"):(t.updateConfig({squashByDefault:p!=="false"}),n[u]=p==="false"?"false":"true");break}case"minStars":{let m=Number(p);if(!Number.isInteger(m)||m<0)throw new j(`Invalid value for minStars: "${p}". Must be a non-negative integer.`);t.updateConfig({minStars:m}),n[u]=String(m);break}case"maxIssueAgeDays":{let m=vl(p,"maxIssueAgeDays");t.updateConfig({maxIssueAgeDays:m}),n[u]=String(m);break}case"minRepoScoreThreshold":{let m=Number(p);if(!Number.isInteger(m)||m<0)throw new j(`Invalid value for minRepoScoreThreshold: "${p}". Must be a non-negative integer.`);t.updateConfig({minRepoScoreThreshold:m}),n[u]=String(m);break}case"skippedIssuesPath":{t.updateConfig({skippedIssuesPath:p||void 0}),n[u]=p||"(cleared)";break}case"autoExtractLearnings":{if(p!=="true"&&p!=="false")throw new j(`Invalid value for autoExtractLearnings: "${p}". Must be "true" or "false".`);let m=p==="true";t.updateConfig({autoExtractLearnings:m}),n[u]=String(m);break}case"autoFormatBeforePush":{if(p!=="true"&&p!=="false")throw new j(`Invalid value for autoFormatBeforePush: "${p}". Must be "true" or "false".`);let m=p==="true";t.updateConfig({autoFormatBeforePush:m}),n[u]=String(m);break}case"trustOwnRepoWrites":{if(p!=="true"&&p!=="false")throw new j(`Invalid value for trustOwnRepoWrites: "${p}". Must be "true" or "false".`);let m=p==="true";t.updateConfig({trustOwnRepoWrites:m}),n[u]=String(m);break}case"includeDocIssues":{t.updateConfig({includeDocIssues:p==="true"}),n[u]=p==="true"?"true":"false";break}case"aiPolicyBlocklist":{let m=p.split(",").map(h=>h.trim()).filter(Boolean),f=[],g=[];for(let h of m){let b=h.replaceAll(/\s+/g,"");/^[\w.-]+\/[\w.-]+$/.test(b)?f.push(b):g.push(h)}if(g.length>0&&(s.push(`Warning: Skipping invalid entries (expected "owner/repo" format): ${g.join(", ")}`),n.aiPolicyBlocklist_invalidEntries=g.join(", ")),f.length===0&&m.length>0){s.push("Warning: All entries were invalid. Blocklist not updated."),n[u]="(all entries invalid)";break}t.updateConfig({aiPolicyBlocklist:f}),n[u]=f.length>0?f.join(", "):"(empty)";break}case"avoidRepos":{let m=p.split(",").map(b=>b.trim()).filter(Boolean),f=[],g=[];for(let b of m){let w=b.replaceAll(/\s+/g,"");/^[\w.-]+\/[\w.-]+$/.test(w)?f.push(w):g.push(b)}if(g.length>0&&s.push(`Warning: Skipping invalid entries (expected "owner/repo" format): ${g.join(", ")}`),f.length===0&&m.length>0){s.push("Warning: All entries were invalid. avoidRepos not updated."),n[u]="(all entries invalid)";break}let h=[...new Set(f)];t.updateConfig({avoidRepos:h}),n[u]=h.length>0?h.join(", "):"(empty)";break}case"boostIssueTypes":{let m=[...new Set(p.split(",").map(f=>f.trim()).filter(Boolean))];t.updateConfig({boostIssueTypes:m}),n[u]=m.length>0?m.join(", "):"(empty)";break}case"projectCategories":{let m=p.split(",").map(b=>b.trim()).filter(Boolean),f=[],g=[];for(let b of m)um.includes(b)?f.push(b):g.push(b);g.length>0&&s.push(`Unknown project categories: ${g.join(", ")}. Valid: ${um.join(", ")}`);let h=[...new Set(f)];t.updateConfig({projectCategories:h}),n[u]=h.length>0?h.join(", "):"(empty)";break}case"preferredOrgs":case"untrackedOrgs":{let m=p.split(",").map(h=>h.trim()).filter(Boolean),f=[];for(let h of m)h.includes("/")?s.push(`"${h}" looks like a repo path. Use org name only (e.g., "vercel" not "vercel/next.js").`):/^[\da-z](?:[\da-z-]*[\da-z])?$/i.test(h)?f.push(h.toLowerCase()):s.push(`"${h}" is not a valid GitHub organization name. Skipping.`);let g=[...new Set(f)];t.updateConfig({[u]:g}),n[u]=g.length>0?g.join(", "):"(empty)";break}case"scope":{let m=p.split(",").map(b=>b.trim()).filter(Boolean),f=[],g=[];for(let b of m)eo.includes(b)?f.push(b):g.push(b);g.length>0&&s.push(`Unknown issue scopes: ${g.join(", ")}. Valid: ${eo.join(", ")}`);let h=[...new Set(f)];t.updateConfig({scope:h.length>0?h:void 0}),n[u]=h.length>0?h.join(", "):"(empty \u2014 using labels only)";break}case"persistence":{if(p!=="local"&&p!=="gist")throw new j(`Invalid value for persistence: "${p}". Must be "local" or "gist".`);t.updateConfig({persistence:p}),n[u]=p;break}case"issueListPath":{t.updateConfig({issueListPath:p||void 0}),n[u]=p||"(cleared)";break}case"diffTool":{if(!to.includes(p)){s.push(`Invalid diffTool "${p}". Valid: ${to.join(", ")}`);break}t.updateConfig({diffTool:p}),n[u]=p;break}case"diffToolCustomCommand":{t.updateConfig({diffToolCustomCommand:p||void 0}),n[u]=p||"(cleared)";break}case"skipBroadWhenSufficientResults":{let m=vM(p,"skipBroadWhenSufficientResults");t.updateConfig({skipBroadWhenSufficientResults:m}),n[u]=String(m);break}case"healthCheckFreshnessMinutes":{let m=vl(p,"healthCheckFreshnessMinutes");t.updateConfig({healthCheckFreshnessMinutes:m}),n[u]=String(m);break}case"reviewMaxPasses":{let m=vl(p,"reviewMaxPasses");t.updateConfig({reviewMaxPasses:m}),n[u]=String(m);break}case"complete":{p==="true"&&(t.markSetupComplete(),n[u]="true");break}default:throw new j(wo(u,"setup"))}}};t.batch(i);let a=await we(t,M6,()=>t.batch(i));return{success:!0,settings:n,warnings:s.length>0?s:void 0,...a&&{gistSyncWarning:a}}}return r.setupComplete&&!e.reset?{setupComplete:!0,config:{githubUsername:r.githubUsername,maxActivePRs:r.maxActivePRs,dormantThresholdDays:r.dormantThresholdDays,approachingDormantDays:r.approachingDormantDays,languages:r.languages,labels:r.labels,projectCategories:r.projectCategories??[],preferredOrgs:r.preferredOrgs??[],scope:r.scope??[],persistence:r.persistence??"local"}}:{setupRequired:!0,prompts:[{setting:"username",prompt:"What is your GitHub username?",current:r.githubUsername||null,required:!0,type:"string"},{setting:"maxActivePRs",prompt:"How many PRs do you want to work on at once?",current:r.maxActivePRs,default:10,type:"number"},{setting:"dormantDays",prompt:"After how many days of inactivity should a PR be considered dormant?",current:r.dormantThresholdDays,default:30,type:"number"},{setting:"approachingDays",prompt:"At how many days should we warn about approaching dormancy?",current:r.approachingDormantDays,default:25,type:"number"},{setting:"languages",prompt:"What programming languages do you want to contribute to?",current:r.languages,default:["typescript","javascript"],type:"list"},{setting:"labels",prompt:"What issue labels should we search for?",current:r.labels,default:["good first issue","help wanted"],type:"list"},{setting:"scope",prompt:"What scope of issues do you want to discover? (beginner, intermediate, advanced \u2014 leave empty for default labels only)",current:r.scope??[],default:[],type:"list"},{setting:"aiPolicyBlocklist",prompt:"Repos with anti-AI contribution policies to block (owner/repo, comma-separated)?",current:r.aiPolicyBlocklist??xS.aiPolicyBlocklist??null,default:["matplotlib/matplotlib"],type:"list"},{setting:"projectCategories",prompt:"What types of projects interest you? (nonprofit, devtools, infrastructure, web-frameworks, data-ml, education)",current:r.projectCategories??[],default:[],type:"list"},{setting:"preferredOrgs",prompt:"Any GitHub organizations to prioritize? (org names, comma-separated)",current:r.preferredOrgs??[],default:[],type:"list"},{setting:"persistence",prompt:'Where should state be stored? "local" for file only, "gist" for GitHub Gist (survives device loss)',current:r.persistence??"local",default:"local",type:"string"}]}}async function N6(){let e=L();return{setupComplete:e.isSetupComplete(),username:e.getState().config.githubUsername}}var M6,iC=A(()=>{"use strict";le();ee();Ot();ts();M6="setup"});var kM={};re(kM,{runCheckIntegration:()=>B6});function j6(e){let t=hr.extname(e),r=hr.basename(e,t);return r==="index"?hr.basename(hr.dirname(e)):r}function z6(e,t){let r=hr.dirname(e),n=[];for(let o of[".ts",".tsx",".js",".jsx"]){let i=hr.join(r,`index${o}`);t.includes(i)&&n.push(i)}let s=hr.dirname(r);for(let o of[".ts",".tsx",".js",".jsx"]){let i=hr.join(s,`index${o}`);t.includes(i)&&n.push(i)}return[...new Set(n)]}async function B6(e){let t=e.base,r;try{let a=(0,Cg.execFileSync)("git",["diff","--name-only","--diff-filter=A",`${t}...HEAD`],{encoding:"utf8",timeout:1e4}).trim();r=a?a.split(`
332
+ `).filter(Boolean):[]}catch(a){let c=I(a);throw new Error(`Failed to run git diff: ${c}`,{cause:a})}let n=r.filter(a=>{let c=hr.extname(a);return G6.has(c)?!U6.some(u=>u.test(a)):!1});if(n.length===0)return{newFiles:[],unreferencedCount:0};let s;try{s=(0,Cg.execFileSync)("git",["ls-files"],{encoding:"utf8",timeout:1e4}).trim().split(`
333
+ `).filter(Boolean)}catch(a){O("check-integration","git ls-files failed, reference checking will be skipped",a),s=[]}let o=[];for(let a of n){let c=j6(a),u=a.replace(/\.[^.]+$/,""),d=[],p=[c];u.includes("/")&&p.push(u);for(let g of p)try{let h=(0,Cg.execFileSync)("git",["grep","-l","--",g],{encoding:"utf8",timeout:1e4}).trim();if(h){let b=h.split(`
334
+ `).filter(w=>w!==a);d.push(...b)}}catch(h){let b=h&&typeof h=="object"&&"status"in h?h.status:void 0;if(b!==void 0&&b!==1){let w=I(h);O("check-integration",`git grep failed for "${g}": ${w}`)}}d=[...new Set(d)];let m=d.length>0,f={path:a,referencedBy:d,isIntegrated:m};m||(f.suggestedEntryPoints=z6(a,s)),o.push(f)}let i=o.filter(a=>!a.isIntegrated).length;return{newFiles:o,unreferencedCount:i}}var hr,Cg,G6,U6,CM=A(()=>{"use strict";hr=B(require("node:path"),1),Cg=require("node:child_process");le();ee();G6=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".vue",".svelte"]),U6=[/^\./,/\.(test|spec|e2e)\.[^.]+$/,/\.(config|rc)\.[^.]+$/,/__tests__\//,/\.d\.ts$/,/\.md$/,/\.json$/,/\.ya?ml$/]});var NM={};re(NM,{checkBundleUpToDate:()=>DM,checkGhAuth:()=>IM,checkGhCli:()=>OM,checkGitHubRateLimit:()=>FM,checkGitHubToken:()=>xM,checkScoutResolvable:()=>MM,checkStateFile:()=>LM,runDoctor:()=>V6});function aC(e){if(e&&typeof e=="object"&&"code"in e){let t=e.code;if(typeof t=="string")return t}}async function OM(){try{let{stdout:e}=await TM("gh",["--version"],{timeout:$M});return{name:"gh CLI installed",status:"ok",message:e.split(`
335
+ `,1)[0]?.trim()||"gh present"}}catch(e){return aC(e)==="ENOENT"?{name:"gh CLI installed",status:"warning",message:"gh CLI not found on PATH",remediation:"Install the GitHub CLI from https://cli.github.com/"}:{name:"gh CLI installed",status:"warning",message:`gh CLI present but failed to run: ${I(e)}`,remediation:"Check that `gh --version` works in your shell; a timeout or permission error may indicate a broken install"}}}async function IM(){try{return await TM("gh",["auth","status"],{timeout:$M}),{name:"gh CLI authenticated",status:"ok",message:"Signed in to github.com"}}catch(e){return{name:"gh CLI authenticated",status:"warning",message:`gh auth status failed: ${I(e)}`,remediation:"Run `gh auth login` to authenticate, or check network/proxy connectivity if the error looks network-related"}}}async function xM(e){let t=e===void 0?await xr():e;if(!t)return{name:"GitHub token resolvable",status:"warning",message:"No GitHub token available via $GITHUB_TOKEN or `gh auth token`",remediation:"Set $GITHUB_TOKEN or run `gh auth login`"};try{let r=be(t),{data:n}=await r.users.getAuthenticated();return{name:"GitHub token resolvable",status:"ok",message:`Authenticated as @${n.login}`}}catch(r){return{name:"GitHub token resolvable",status:"error",message:`Token present but API auth failed: ${I(r)}`,remediation:"Token may be expired or revoked \u2014 run `gh auth refresh` or set a fresh $GITHUB_TOKEN"}}}function H6(){let e=kl.resolve(__dirname,"../../dist/cli.bundle.cjs"),t=kl.resolve(__dirname,"cli.bundle.cjs"),r=kl.resolve(__dirname,"../cli.ts"),n=kl.resolve(__dirname,"../src/cli.ts"),s=on.existsSync(e)?e:on.existsSync(t)?t:e,o=on.existsSync(r)?r:on.existsSync(n)?n:r;return{bundlePath:s,sourcePath:o}}function PM(e){try{return{stat:on.statSync(e)}}catch(t){return aC(t)==="ENOENT"?{stat:null}:{stat:null,error:t}}}function DM(e){let t=H6(),r=e?.bundlePath??t.bundlePath,n=e?.sourcePath??t.sourcePath,s=PM(r),o=PM(n);if(s.error||o.error){let c=s.error??o.error;return{name:"CLI bundle",status:"error",message:`Bundle freshness check failed: ${I(c)}`,remediation:"Check filesystem permissions on packages/core/dist/"}}let i=s.stat,a=o.stat;return!i&&!a?{name:"CLI bundle",status:"warning",message:"Neither cli.ts nor cli.bundle.cjs could be located",remediation:"Reinstall the package or check your install location"}:i?a&&a.mtimeMs>i.mtimeMs?{name:"CLI bundle",status:"warning",message:"Source files are newer than dist/cli.bundle.cjs",remediation:"Run `pnpm run bundle` to rebuild"}:{name:"CLI bundle",status:"ok",message:"Bundle present and up-to-date"}:{name:"CLI bundle",status:"warning",message:"dist/cli.bundle.cjs not built yet",remediation:"Run `pnpm run bundle` to build the CLI bundle"}}function LM(e){let t=e?.statePathOverride??jt();if(!on.existsSync(t))return{name:"state.json valid",status:"ok",message:"No state.json yet (first run \u2014 nothing to validate)"};try{let r=on.readFileSync(t,"utf8"),n=JSON.parse(r),s=Gt.safeParse(n);return s.success?{name:"state.json valid",status:"ok",message:`state v${typeof n?.version=="number"?n.version:"?"} parses and validates`}:{name:"state.json valid",status:"error",message:`state.json failed schema validation \u2014 ${s.error.issues.slice(0,3).map(a=>`${a.path.join(".")||"<root>"}: ${a.message}`).join("; ")}`,remediation:"Restore from a backup in `~/.oss-autopilot/backups/` or re-run `oss-autopilot init`"}}catch(r){return{name:"state.json valid",status:"error",message:`Failed to read/parse state.json: ${I(r)}`,remediation:"Restore from a backup in `~/.oss-autopilot/backups/`"}}}async function MM(e=W6){try{return await e(),{name:"@oss-scout/core resolvable",status:"ok",message:"Found on module path"}}catch(t){let r=aC(t),n=r==="ERR_MODULE_NOT_FOUND"||r==="MODULE_NOT_FOUND",s=r==="ERR_PACKAGE_PATH_NOT_EXPORTED"||r==="ERR_PACKAGE_IMPORT_NOT_DEFINED"||r==="ERR_INVALID_PACKAGE_CONFIG"||t instanceof SyntaxError,o=n||s;return{name:"@oss-scout/core resolvable",status:"error",message:o?`@oss-scout/core cannot be loaded (install issue): ${I(t)}`:`@oss-scout/core failed to load: ${I(t)}`,remediation:o?"Reinstall dependencies (`pnpm install` or `npm install`)":"Scout loaded but threw during initialization \u2014 report this as a bug in oss-scout with the error above"}}}async function FM(e){let t=e===void 0?await xr():e;if(!t)return{name:"GitHub rate limit",status:"warning",message:"Cannot check \u2014 no token available",remediation:"Set $GITHUB_TOKEN or run `gh auth login` to enable API-backed checks"};try{let r=be(t),{data:n}=await r.rateLimit.get(),s=n.resources.core,o=new Date(s.reset*1e3).toISOString();return s.remaining<100?{name:"GitHub rate limit",status:"warning",message:`Only ${s.remaining}/${s.limit} core requests remaining (resets at ${o})`,remediation:"Wait for the window to reset or use a token with a higher limit"}:{name:"GitHub rate limit",status:"ok",message:`${s.remaining}/${s.limit} core requests remaining`}}catch(r){return{name:"GitHub rate limit",status:"error",message:`Failed to check rate limit: ${I(r)}`}}}async function Go(e,t){try{return await t()}catch(r){return{name:e,status:"error",message:`Check crashed unexpectedly: ${I(r)}`,remediation:"This is a bug in the doctor command \u2014 please report it with the error above"}}}async function V6(){let e=null;try{e=await xr()}catch{e=null}let t=await Promise.all([Go("gh CLI installed",()=>OM()),Go("gh CLI authenticated",()=>IM()),Go("GitHub token resolvable",()=>xM(e)),Go("GitHub rate limit",()=>FM(e)),Go("@oss-scout/core resolvable",()=>MM()),Go("CLI bundle",()=>DM()),Go("state.json valid",()=>LM())]),r={ok:t.filter(n=>n.status==="ok").length,warnings:t.filter(n=>n.status==="warning").length,errors:t.filter(n=>n.status==="error").length};return{checks:t,summary:r}}var on,kl,EM,AM,TM,$M,W6,GM=A(()=>{"use strict";on=B(require("node:fs"),1),kl=B(require("node:path"),1),EM=require("node:child_process"),AM=require("node:util");le();gn();ee();TM=(0,AM.promisify)(EM.execFile),$M=3e3;W6=()=>Promise.resolve().then(()=>(gg(),bL))});var zM={};re(zM,{runLocalRepos:()=>X6,scanForRepos:()=>jM});function K6(e,t,r,n,s){for(let o of e){if(!o.isDirectory())continue;let i=an.default.join(t,o.name),a=r+1;o.name===".git"?s.push(i):a<Z6&&n.push({directory:i,depth:a})}}function J6(e){let t=[],r=[{directory:e,depth:0}],n=Date.now()+UM;for(;r.length>0;){if(Date.now()>n){O("local-repos",`Scan of ${e} exceeded ${UM}ms; returning partial results`);break}let{directory:s,depth:o}=r.pop(),i;try{i=Cl.readdirSync(s,{withFileTypes:!0})}catch(a){O("local-repos",`Failed to read directory ${s}`,a);continue}K6(i,s,o,r,t)}return t}function Y6(e){try{let t=(0,cC.execFileSync)("git",["-C",e,"remote","get-url","origin"],{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim(),r=t.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);if(r)return r[1];let n=t.match(/github\.com[/:]([^/]+\/[^/]+?)(?:\.git)?$/);return n?n[1]:null}catch(t){return O("local-repos",`Failed to get GitHub remote for ${e}`,t),null}}function Q6(e){try{return(0,cC.execFileSync)("git",["-C",e,"branch","--show-current"],{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim()||null}catch(t){return O("local-repos",`Failed to get current branch for ${e}`,t),null}}function jM(e){let t={};for(let r of e){if(!Cl.existsSync(r))continue;let n=J6(r);for(let s of n){let o=an.default.dirname(s),i=Y6(o);if(!i)continue;let a=Q6(o);t[i]={path:o,exists:!0,currentBranch:a}}}return t}async function X6(e){let t=L(),r=t.getState(),n=e.paths?.map(i=>an.default.resolve(i))??r.config.localRepoScanPaths??q6.filter(i=>Cl.existsSync(i));if(!e.scan&&r.localRepoCache){let i=r.localRepoCache;return{repos:i.repos,scanPaths:i.scanPaths,cachedAt:i.cachedAt,fromCache:!0}}let s=jM(n),o=new Date().toISOString();try{t.setLocalRepoCache({repos:s,scanPaths:n,cachedAt:o})}catch(i){let a=I(i);console.error(`Warning: Failed to cache scan results to disk: ${a}`)}return{repos:s,scanPaths:n,cachedAt:o,fromCache:!1}}var Cl,an,Uo,cC,q6,Z6,UM,BM=A(()=>{"use strict";Cl=B(require("node:fs"),1),an=B(require("node:path"),1),Uo=B(require("node:os"),1),cC=require("node:child_process");le();ee();q6=[an.default.join(Uo.homedir(),"Documents","oss"),an.default.join(Uo.homedir(),"dev"),an.default.join(Uo.homedir(),"projects"),an.default.join(Uo.homedir(),"src"),an.default.join(Uo.homedir(),"code"),an.default.join(Uo.homedir(),"repos")],Z6=4,UM=3e4});var Pl={};re(Pl,{claimWork:()=>ZM,finishWork:()=>KM,listWork:()=>YM,releaseWork:()=>JM,runWorkClaim:()=>l3,runWorkFinish:()=>d3,runWorkList:()=>m3,runWorkRelease:()=>p3});function Pg(e){return new Date(e).toISOString()}function Ya(e,t){if(t===void 0)return;let r=t.trim();if(r.length===0)throw new j(`--${e} must not be empty`);if(r.length>HM)throw new j(`--${e} is longer than ${HM} characters`);if(e3.test(r))throw new j(`--${e} must not contain control characters`);return r}function qM(e){if(e==="implementation"||e==="pr")return e;throw new j(`--kind must be "implementation" or "pr", got "${e}"`)}function t3(e){if(e!==void 0){if(!Number.isFinite(e)||e<=0||e>iu)throw new j(`--ttl must be a number of hours between 0 and ${iu}`);return e}}function r3(e,t){Ze(e),t==="pr"?Qe(e,tr,"PR"):Qe(e,dr,"issue")}function n3(){return VM.default.hostname().split(".",1)[0]}function s3(e){let t=Ya("worktree",e);return t===void 0?{}:{worktree:Ni(t),host:n3(),machineId:cf()}}function o3(e){let t=qM(e.kind);r3(e.url,t);let r=Ya("session",e.session);if(r===void 0)throw new j("--session is required");let n=Ya("branch",e.branch),s=Ya("run-id",e.runId),o=s3(e.worktree);if(t==="implementation"&&s===void 0&&o.worktree===void 0)throw new j("An implementation claim needs --worktree (local checkout) or --run-id (remote worker run)");let i=t3(e.ttlHours),a=e.takeover===!0;return{kind:t,session:r,branch:n,...o,runId:s,ttlHours:i,url:e.url,takeover:a}}function WM(e,t,r){let n=e.getWorkClaims(),s=qp(n,t.url,t.session,r);if(s&&!t.takeover)return`${t.url} is already claimed: ${cu(s,r)}. Pass --takeover (takeover: true) to replace that claim.`;if(t.kind==="implementation"){let o=e.getState().config.maxConcurrentImplementations,i=Jp(n,t,o,r);if(i)return i.message}return null}function i3(e,t,r){let n=c3(e,t)?t:void 0,s=e.ttlHours??(n?au:Vp[e.kind]);return{kind:e.kind,url:e.url,session:e.session,startedAt:Pg(r),expiresAt:Pg(r+s*36e5),status:n?"finished":"running",...a3(e),...n?.finishedAt!==void 0&&{finishedAt:n.finishedAt}}}function a3(e){let{branch:t,worktree:r,host:n,machineId:s,runId:o}=e;return{...t!==void 0&&{branch:t},...r!==void 0&&{worktree:r},...n!==void 0&&{host:n},...s!==void 0&&{machineId:s},...o!==void 0&&{runId:o}}}function c3(e,t){return t!==void 0&&t.session===e.session&&t.kind===e.kind&&t.status==="finished"}function u3(e,t){return e===void 0?"claimed":e.session===t?"renewed":"took-over"}async function l3(e){return ZM(L(),e)}async function ZM(e,t){let r=o3(t),n=Date.now(),s=WM(e,r,n);if(s)throw new j(s);let o=Js(e.getWorkClaims(),r.url,n),i=i3(r,o,n),a=u3(o,r.session),c={message:null},u=()=>{c.message=WM(e,r,n),c.message===null&&e.upsertWorkClaim(i,n)};u();let d=await we(e,uC,u);if(c.message!==null)throw new j(`${c.message} (recorded on another machine first; this claim was not saved)`);let p=d===null&&e.getGistHealth().degraded===null;return{claim:i,outcome:a,synced:p,...d&&{gistSyncWarning:d}}}async function d3(e){return KM(L(),e)}async function KM(e,t){Ze(t.url);let r=Ya("session",t.session),n=Date.now(),s=Pg(n),o=()=>{let d=Js(e.getWorkClaims(),t.url,n);return d===void 0||r===void 0||d.session===r?null:`The claim on ${t.url} belongs to session ${d.session}, not ${r}; it was not marked finished.`},i={message:o()};if(i.message!==null)throw new j(i.message);let a={claim:null},c=()=>{i.message=o(),i.message===null&&(a.claim=e.finishWorkClaim(t.url,s,n)??null)};c();let u=a.claim?await we(e,uC,c):null;if(i.message!==null)throw new j(i.message);return{url:t.url,claim:a.claim,...u&&{gistSyncWarning:u}}}async function p3(e){return JM(L(),e)}async function JM(e,t){let r=Ya("session",t.session),n=t.kind===void 0?void 0:qM(t.kind);if(t.url!==void 0&&Ze(t.url),r===void 0&&t.url===void 0)throw new j("work release needs a URL or --session <name>");let s={url:t.url,session:r,kind:n},o=e.releaseWorkClaims(s),i=o.length>0?await we(e,uC,()=>e.releaseWorkClaims(s)):null;return{released:o,...i&&{gistSyncWarning:i}}}async function m3(){return YM(L())}async function YM(e){e.isGistMode()?await e.refreshFromGist():e.reloadIfChanged();let t=Date.now(),r=e.getWorkClaims(),n=e.getActiveWorkClaims(t),s=e.getStateStaleness();return{claims:n,expiredCount:r.length-n.length,now:Pg(t),...s&&{warnings:[An(s)]}}}var VM,uC,HM,e3,El=A(()=>{"use strict";VM=B(require("node:os"),1);le();ee();me();Ot();uC="work",HM=500,e3=new RegExp("\\p{Cc}","u")});var QM={};re(QM,{runPRTemplate:()=>f3});async function f3(e){let{owner:t,repo:r}=Ks(e.repo),n=ke(),s=be(n);return Ym(s,t,r)}var XM=A(()=>{"use strict";so();Lm();nt();z_()});var eF={};re(eF,{runRepoCap:()=>g3});async function g3(e){let t=mf(e.repo),r=L().getState(),n=r.config.githubUsername;if(!n)throw new Te("githubUsername is not configured; run setup first.");let{data:s}=await be(ke()).search.issuesAndPullRequests({q:`is:pr is:open author:${n} repo:${t}`,per_page:1});return Ff(r,t,{openPRCount:s.total_count})}var tF=A(()=>{"use strict";le();ee();xa();Ot()});function y3(e){if(e.length===0)return 0;let t=[...e].sort((n,s)=>n-s),r=Math.floor(t.length/2);return t.length%2===0?(t[r-1]+t[r])/2:t[r]}function b3(e){return e.isArchived?0:Math.min(1,e.commitsLast30Days/30)}function w3(e){if(e.prMergeTimesDays.length===0)return 0;let t=e.prMergeTimesDays.reduce((r,n)=>r+n,0)/e.prMergeTimesDays.length;return t<=0?1:t>=14?0:Math.max(0,Math.min(1,(14-t)/14))}function R3(e){if(e.openedCount90Days===0)return 0;let t=e.mergedCount90Days/e.openedCount90Days;return Math.max(0,Math.min(1,t))}function S3(e){let t=0;return e.hasContributing&&(t+=.4),e.hasIssueTemplates&&(t+=.25),e.hasPRTemplate&&(t+=.25),e.hasCodeOfConduct&&(t+=.1),Math.min(1,t)}function _3(e){if(e.isArchived)return 0;let t=.5;if(e.lastReleaseISO){let r=Date.now()-new Date(e.lastReleaseISO).getTime(),n=1e3*60*60*24*30*6;r<=n&&(t+=.5)}return t}function v3(e){if(e.isArchived)return!0;if(e.lastCommitISO){let t=Date.now()-new Date(e.lastCommitISO).getTime(),r=1440*60*60*1e3;if(t>r)return!0}return e.openedCount90Days>0&&e.mergedCount90Days===0}function k3(e,t){return t?"avoid":e>=rF.recommended?"recommended":e>=rF.cautious?"proceed_with_caution":"avoid"}function nF(e){let t={activity:b3(e),prSpeed:w3(e),mergeRate:R3(e),guidelines:S3(e),stability:_3(e)},r=t.activity*cn.activity+t.prSpeed*cn.prSpeed+t.mergeRate*cn.mergeRate+t.guidelines*cn.guidelines+t.stability*cn.stability,n=Math.round(r/h3*100)/10,s=e.prMergeTimesDays.length,o=s===0?null:e.prMergeTimesDays.reduce((u,d)=>u+d,0)/s,i=s===0?null:y3(e.prMergeTimesDays),a=e.openedCount90Days===0?null:Math.min(100,e.mergedCount90Days/e.openedCount90Days*100),c=k3(n,v3(e));return{repo:{stars:e.stars,forks:e.forks,openIssues:e.openIssues,watchers:e.watchers,isArchived:e.isArchived,lastPushed:e.lastPushed,createdAt:e.createdAt},prMergeTime:{avgDays:o,medianDays:i,sampleSize:s,sourceWindowDays:90},mergeRate:{merged:e.mergedCount90Days,opened:e.openedCount90Days,percent:a,windowDays:90},maintainerActivity:{lastCommitISO:e.lastCommitISO,contributorsLast90d:e.contributorsLast90d,lastReleaseISO:e.lastReleaseISO},communityHealth:{contributing:e.hasContributing,issueTemplates:e.hasIssueTemplates,prTemplate:e.hasPRTemplate,codeOfConduct:e.hasCodeOfConduct},rubricScore:n,rubricVerdict:c}}var cn,h3,rF,sF=A(()=>{"use strict";cn={activity:.25,prSpeed:.25,mergeRate:.2,guidelines:.1,stability:.05},h3=cn.activity+cn.prSpeed+cn.mergeRate+cn.guidelines+cn.stability,rF={recommended:7.5,cautious:5}});var oF={};re(oF,{runRepoVet:()=>O3});async function P3(e,t,r,n){try{return await e.repos.getContent({owner:t,repo:r,path:n}),!0}catch(s){if(s.status===404)return!1;throw s}}async function E3(e,t,r){let n={hasContributing:!1,hasIssueTemplates:!1,hasPRTemplate:!1,hasCodeOfConduct:!1},s=!1;return await Promise.all(C3.map(async({key:o,candidates:i})=>{let a=!1;for(let c of i)try{if(await P3(e,t,r,c)){n[o]=!0;return}}catch(u){v(lC,`community-health probe for ${t}/${r}/${c} failed: ${I(u)}`),a=!0;continue}a&&(s=!0)})),{hasContributing:n.hasContributing,hasIssueTemplates:n.hasIssueTemplates,hasPRTemplate:n.hasPRTemplate,hasCodeOfConduct:n.hasCodeOfConduct,incomplete:s}}function A3(e){try{let t=L(),r=t.getRepoScore(e);if(r)return r.score;let n=e.toLowerCase();return Object.values(t.getState().repoScores).find(o=>o.repo.toLowerCase()===n)?.score}catch(t){v(lC,`History-score lookup skipped (state unavailable): ${I(t)}`);return}}function T3(e,t,r){let n=r.getTime()-t*Eg,s=[],o=0,i=0;for(let a of e){let c=new Date(a.created_at).getTime();if(c>=n&&(i+=1),a.merged_at){let u=new Date(a.merged_at).getTime();if(u>=n){o+=1;let d=(u-c)/Eg;Number.isFinite(d)&&d>=0&&s.push(d)}}}return{prMergeTimesDays:s,mergedCount:o,openedCount:i}}function $3(e,t){let r=t.getTime()-30*Eg,n=t.getTime()-90*Eg,s=new Set,o=0,i=null;for(let a of e){let c=a.commit.author?.date;if(!c)continue;let u=new Date(c).getTime();Number.isNaN(u)||((i===null||u>i)&&(i=u),u>=r&&(o+=1),u>=n&&a.author?.login&&s.add(a.author.login))}return{commitsLast30Days:o,contributorsLast90d:s.size,lastCommitISO:i?new Date(i).toISOString():null}}async function O3(e){mf(e.repo);let[t,r]=e.repo.split("/",2),n=ke(),s=be(n),o=new Date,i=!1,[a,c,u,d,p]=await Promise.all([s.repos.get({owner:t,repo:r}),s.pulls.list({owner:t,repo:r,state:"closed",sort:"updated",direction:"desc",per_page:100}),s.repos.listCommits({owner:t,repo:r,per_page:100}),s.repos.listReleases({owner:t,repo:r,per_page:1}).catch(M=>{if(de(M))throw M;let G={data:[]};return Ue(M)===404||(i=!0,v(lC,`release listing for ${t}/${r} failed: ${I(M)} \u2014 release-recency signal is incomplete`)),G}),E3(s,t,r)]),m=c.data.map(M=>({created_at:M.created_at,merged_at:M.merged_at,updated_at:M.updated_at})),{prMergeTimesDays:f,mergedCount:g,openedCount:h}=T3(m,90,o),b=$3(u.data,o),w=d.data,y=w.length>0?w[0].published_at??w[0].created_at??null:null,S={stars:a.data.stargazers_count??0,forks:a.data.forks_count??0,openIssues:a.data.open_issues_count??0,watchers:a.data.subscribers_count??0,isArchived:a.data.archived??!1,lastPushed:a.data.pushed_at??new Date(0).toISOString(),createdAt:a.data.created_at??new Date(0).toISOString(),commitsLast30Days:b.commitsLast30Days,prMergeTimesDays:f,mergedCount90Days:g,openedCount90Days:h,lastCommitISO:b.lastCommitISO,contributorsLast90d:b.contributorsLast90d,lastReleaseISO:y,hasContributing:p.hasContributing,hasIssueTemplates:p.hasIssueTemplates,hasPRTemplate:p.hasPRTemplate,hasCodeOfConduct:p.hasCodeOfConduct},k=nF(S),{repo:R,communityHealth:P,maintainerActivity:C,...E}=k,T=A3(e.repo);return{repoSlug:e.repo,fetchedAt:o.toISOString(),repoMeta:R,communityHealth:{...P,incomplete:p.incomplete},maintainerActivity:{...C,releasesIncomplete:i},...E,...T!==void 0&&{historyScore:T}}}var lC,Eg,C3,iF=A(()=>{"use strict";le();ee();ce();Ot();sF();lC="repo-vet",Eg=864e5,C3=[{key:"hasContributing",candidates:["CONTRIBUTING.md",".github/CONTRIBUTING.md"]},{key:"hasIssueTemplates",candidates:[".github/ISSUE_TEMPLATE"]},{key:"hasPRTemplate",candidates:[".github/pull_request_template.md","pull_request_template.md","PULL_REQUEST_TEMPLATE.md"]},{key:"hasCodeOfConduct",candidates:["CODE_OF_CONDUCT.md",".github/CODE_OF_CONDUCT.md"]}]});var cF={};re(cF,{runDetectFormatters:()=>I3});async function I3(e){let t=dC.resolve(e.repoPath??process.cwd()),r={...ju(t)};if(e.ciLog){let n;try{n=aF.readFileSync(dC.resolve(e.ciLog),"utf8")}catch(s){throw new Error(`Failed to read CI log file: ${I(s)}`,{cause:s})}r.ciDiagnosis=nf(n,t)}return r}var aF,dC,uF=A(()=>{"use strict";aF=B(require("node:fs"),1),dC=B(require("node:path"),1);W_();ee()});var RF={};re(RF,{PREP_REF_PREFIX:()=>Al,PrepNamespaceError:()=>Qa,buildPrepRef:()=>yF,compareUrlFor:()=>bF,parseRemoteOwner:()=>fF,parseRemotesOutput:()=>gF,prepBranchName:()=>pC,resolvePushRemote:()=>hF,runOvernightPushPrep:()=>M3});function fF(e){let t=e.trim().match(x3);return t?{owner:t[1],repo:t[2]}:null}function gF(e){let t=[];for(let r of e.split(`
336
+ `)){let n=r.match(/^(\S+)\s+(\S+)\s+\(push\)$/);n&&t.push({name:n[1],url:n[2]})}return t}function hF(e,t){let r=new Map;for(let n of e)r.set(n.name,(r.get(n.name)??0)+1);for(let n of e){if(n.name.startsWith("-")||r.get(n.name)!==1)continue;let s=fF(n.url);if(s&&s.owner.toLowerCase()===t.toLowerCase())return{remote:n.name,...s}}return null}function mC(e){if(!e.startsWith(Al)||e.length===Al.length)throw new Qa(e)}function yF(e){if(e.length===0||e.startsWith("/")||e.endsWith("/")||e.endsWith(".lock")||e.includes("//")||e.includes("..")||e.includes("@{")||/[\s~^:?*[\\]/.test(e)||[...e].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===127))throw new Error(`Refusing to build a prep ref from branch "${e}": not a valid ref name`);let t=`${Al}${e}`;return mC(t),t}function pC(e){return mC(e),e.slice(11)}function bF(e,t,r){return`https://github.com/${e.owner}/${e.repo}/compare/${t}...${r}`}function lF(e,t){return(0,dF.execFileSync)("git",["-C",e,...t],{encoding:"utf8",timeout:mF,stdio:["ignore","pipe","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}function wF(e){let t=e?.stderr;return typeof t=="string"?t.trim():""}function D3(e){return/non-fast-forward|fetch first/.test(wF(e))}function L3(e){let t=e?.code==="ETIMEDOUT",r=wF(e).split(`
337
+ `).slice(-3).join(" | ");return`push failed: ${t?`timed out after ${mF/1e3}s (the ref may still have landed; the next run re-checks)`:I(e)}${r?` [git: ${r}]`:""}`}function Tg(e,t,r,n,s){return v(Ag,`${e==="failed"?"Failed":"Skipping"} ${t.branch} for ${t.url}: ${r}`),{url:t.url,branch:t.branch,status:e,...n?{remote:n.remote,repo:`${n.owner}/${n.repo}`}:{},...s?{ref:s}:{},reason:r}}function jo(e,t,r,n){return Tg("skipped",e,t,r,n)}async function M3(e){du("push prepared branches");let t=L(),r=Ta(),n=r?Wx(r):null,s=n?{...n.record,reportPath:pF.join(ji(),`overnight-${tl(new Date(n.record.runAt))}.md`)}:t.getLastOvernight();if(!s)throw new Error("No overnight run recorded yet; run `overnight` first.");let o=s;n?.report!=null&&!e.dryRun&&$g.writeFileSync(o.reportPath,n.report,{mode:384});let i=be(ke()),{data:a}=await i.users.getAuthenticated(),c=a.login?.trim();if(!c)throw new Error("Could not read the authenticated login from the token; refusing to push anywhere.");let u=t.getState().config.githubUsername;if(u&&u.toLowerCase()!==c.toLowerCase())throw new Error(`Configured githubUsername "${u}" does not match the token's login "${c}"; refusing to push anywhere.`);let d=new Map;async function p(C,E){let T=`${C.owner}/${C.repo}|${E??""}`.toLowerCase(),M=d.get(T);if(M!==void 0)return M;let G;try{let{data:X}=await i.repos.get({owner:C.owner,repo:C.repo});X.fork?X.owner.login.toLowerCase()!==c.toLowerCase()?G=`${C.owner}/${C.repo} resolved to ${X.full_name}, not owned by ${c}`:E&&X.parent?.full_name?.toLowerCase()!==E.toLowerCase()?G=`${X.full_name} is not a fork of ${E}`:G=null:G=`${C.owner}/${C.repo} is not a fork`}catch(X){if(zt(X))throw X;G=`could not read ${C.owner}/${C.repo}: ${I(X)}`}return d.set(T,G),G}let m=new Map;function f(C){let E=q(C);if(!E||E.type!=="pull")return Promise.resolve(void 0);let T=m.get(C);return T||(T=i.pulls.get({owner:E.owner,repo:E.repo,pull_number:E.number}).then(({data:M})=>M.head).catch(M=>{if(zt(M))throw M;v(Ag,`Could not read the head of ${C}: ${I(M)}`)}),m.set(C,T)),T}async function g(C){let E=q(C);if(!E)return`${C} is not a GitHub PR or issue URL`;let T=`${E.owner}/${E.repo}`,M=c,G=E.repo;if(E.type==="pull"){let X=(await f(C))?.repo;if(!X)return`could not read the head repository of ${C}`;if(X.owner.login.toLowerCase()!==c.toLowerCase())return`the head of ${C} is ${X.full_name}, not a repo owned by ${c}`;M=X.owner.login,G=X.name}return{target:{owner:M,repo:G,remote:`https://github.com/${M}/${G}.git`},upstream:T}}async function h(C){let E,T;if(r){let Z=await g(C.url);if(typeof Z=="string")return jo(C,Z);({target:E,upstream:T}=Z)}else{if(!C.worktree)return jo(C,"no worktree recorded");if(!$g.existsSync(C.worktree))return jo(C,`worktree ${C.worktree} does not exist`);let Z=hF(gF(lF(C.worktree,["remote","-v"])),c);if(!Z)return jo(C,`no remote in ${C.worktree} is owned by ${c}`);E=Z}let M=await p(E,T);if(M)return jo(C,M,E);let G;try{G=yF(C.branch)}catch(Z){if(Z instanceof Qa)throw Z;return jo(C,I(Z),E)}let X=pC(G),ve=(await f(C.url))?.ref,he={url:C.url,branch:C.branch,remote:E.remote,repo:`${E.owner}/${E.repo}`,ref:G,...ve?{compareUrl:bF(E,ve,X)}:{}};if(e.dryRun)return{...he,status:"planned"};mC(G);let oe;try{oe=r?Vx(r,C.branch):{repo:C.worktree,cleanup:()=>{}}}catch(Z){return Tg("failed",C,`bundle import failed: ${I(Z)}`,E,G)}try{lF(oe.repo,["push","--no-follow-tags","--",E.remote,`refs/heads/${C.branch}:${G}`])}catch(Z){return D3(Z)?jo(C,`non-fast-forward: ${X} on ${E.remote} has commits this worktree lacks; not forced`,E,G):Tg("failed",C,L3(Z),E,G)}finally{oe.cleanup()}return{...he,status:"pushed"}}let b=[],w=[...s.prepared],y=!1,S=null,k=null;async function R(){if(e.dryRun)return;let C=()=>t.setLastOvernight({...t.getLastOvernight()??o,prepared:w});C();try{y=_f(o.reportPath,w).reportRecreated}catch(E){S=`could not rewrite ${o.reportPath}: ${I(E)}`,v(Ag,S)}S||rl(t,o.reportPath),k=await we(t,Ag,C)}try{for(let[C,E]of s.prepared.entries()){let T;try{T=await h(E)}catch(M){if(M instanceof Qa||zt(M))throw M;T=Tg("failed",E,I(M))}if(b.push(T),T.status==="pushed"&&T.ref){let{pushProblem:M,...G}=E;w[C]={...G,pushedRef:pC(T.ref),pushedAt:new Date().toISOString(),...T.compareUrl?{compareUrl:T.compareUrl}:{}}}else T.status!=="planned"&&T.reason&&(w[C]={...E,pushProblem:T.reason})}}finally{await R()}let P=C=>b.filter(E=>E.status===C).length;return{dryRun:e.dryRun,login:c,reportPath:s.reportPath,results:b,pushed:P("pushed"),planned:P("planned"),skipped:P("skipped"),failed:P("failed"),...y?{reportRecreated:!0}:{},...S?{reportWarning:S}:{},...k?{gistSyncWarning:k}:{}}}var dF,$g,pF,Ag,Al,mF,Qa,x3,SF=A(()=>{"use strict";dF=require("node:child_process"),$g=B(require("node:fs"),1),pF=B(require("node:path"),1);le();ee();ce();Vr();Ov();bs();Ag="overnight-push-prep",Al="refs/heads/prep/",mF=6e4,Qa=class extends Error{constructor(t){super(`Internal error: refusing to push ref "${t}" outside ${Al}`),this.name="PrepNamespaceError"}},x3=/^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com(?::\d+)?\/)([\w-]+)\/([\w.-]+?)(?:\.git)?\/?$/i});var _F={};re(_F,{formatStatsBadge:()=>U3,formatStatsMarkdown:()=>N3,runStats:()=>F3});async function F3(){let t=L().getState(),r=t.lastDigest?.summary?.totalActivePRs??0,n=Gm({repoScores:t.repoScores??{},activePRCount:r});return{...n,mergeRateFormatted:`${(n.mergeRate*100).toFixed(1)}%`,username:t.config.githubUsername}}function N3(e){let t=[`# OSS Contribution Stats for @${e.username}`,"","| Metric | Value |","|--------|-------|",`| Merged PRs | ${e.totalMerged} |`,`| Merge Rate | ${e.mergeRateFormatted} |`,`| Active PRs | ${e.activePRs} |`,`| Repos Contributed | ${e.reposContributed} |`,""];if(e.topRepos.length>0){t.push("## Top Repos","","| Repo | Merged PRs |","|------|-----------|");for(let r of e.topRepos)t.push(`| ${r.repo} | ${r.mergedCount} |`);t.push("")}return t.push("---","*Generated by [OSS Autopilot](https://github.com/costajohnt/oss-autopilot)*"),t.join(`
338
+ `)}function G3(e){return e.totalMerged===0?"blue":e.mergeRate>=.8?"brightgreen":e.mergeRate>=.6?"green":e.mergeRate>=.4?"yellow":"orange"}function U3(e){return{schemaVersion:1,label:"OSS Contributions",message:e.totalMerged>0?`${e.mergeRateFormatted} merge rate | ${e.totalMerged} merged`:"Getting Started",color:G3(e)}}var vF=A(()=>{"use strict";le();N_()});var zo={};re(zo,{runFetchCorpus:()=>K3,runGuidelinesList:()=>W3,runGuidelinesReset:()=>Z3,runGuidelinesStore:()=>V3,runGuidelinesView:()=>H3,runMarkExtracted:()=>q3});function $l(e){if(!j3.test(e))throw new Error(`Invalid repo identifier "${e}". Expected "owner/repo" format.`)}async function H3(e){$l(e.repo);let t=L(),r=t.getGuidelines(e.repo);return{repo:e.repo,content:r,agentContent:r===null?null:Du(r),byteSize:r===null?0:Buffer.byteLength(r,"utf8"),exists:r!==null,storageMode:t.isGuidelinesAvailable()?"gist":"local-unavailable"}}async function W3(){let e=L(),t=e.listGuidelinesRepos();return{repos:t,count:t.length,storageMode:e.isGuidelinesAvailable()?"gist":"local-unavailable"}}async function V3(e){if($l(e.repo),!e.content||e.content.length===0)throw new Error("Cannot store empty content. Use `guidelines reset` to delete a guidelines file.");let t=L();t.setGuidelines(e.repo,e.content);let r=await we(t,Tl,()=>t.setGuidelines(e.repo,e.content));return{repo:e.repo,byteSize:Buffer.byteLength(e.content,"utf8"),stored:!0,...r&&{gistSyncWarning:r}}}async function q3(e){$l(e.repo);let t=L(),r=`https://github.com/${e.repo}/`,n=new Date().toISOString(),s=()=>{let a=0;for(let c of[...t.getMergedPRs()??[],...t.getClosedPRs()??[]])!c.url.startsWith(r)||!c.commentsFetchedAt||c.learningsExtractedAt||(t.markPRLearningsExtracted(c.url,n),a++);return a},o=s(),i=o>0?await we(t,Tl,s):null;return{repo:e.repo,marked:o,...i&&{gistSyncWarning:i}}}async function Z3(e){$l(e.repo);let t=L();if(!t.isGuidelinesAvailable())throw new rs;let r=t.getGuidelines(e.repo)!==null,n=null;return r&&(t.deleteGuidelines(e.repo),n=await we(t,Tl,()=>t.deleteGuidelines(e.repo))),{repo:e.repo,deleted:r,...n&&{gistSyncWarning:n}}}async function K3(e){$l(e.repo);let t=J3(e.limit),r=L(),n=r.getMergedPRs()??[],s=r.getClosedPRs()??[],o=Date.now()-B3,i=[...n.map(k=>({url:k.url,timestamp:k.mergedAt,alreadyFetched:!!k.commentsFetchedAt})),...s.map(k=>({url:k.url,timestamp:k.closedAt,alreadyFetched:!!k.commentsFetchedAt}))],a=`https://github.com/${e.repo}/`,c=i.filter(k=>{if(!k.url.startsWith(a))return!1;let R=Date.parse(k.timestamp||"");return!(!Number.isFinite(R)||R<o)}),u=e.forceRefetch?0:c.filter(k=>k.alreadyFetched).length,d=(e.forceRefetch?c:c.filter(k=>!k.alreadyFetched)).sort((k,R)=>Date.parse(R.timestamp||"")-Date.parse(k.timestamp||"")).slice(0,t);if(d.length===0)return{repo:e.repo,bundles:[],prCount:0,skipped:u,failures:[]};let p=ke(),m=be(p),f=r.getState().config.githubUsername;f||v(Tl,"githubUsername is not set; bot/own-comment filtering will be incomplete");let{bundles:g,failures:h}=await sf(m,d.map(k=>k.url),f),b=new Date().toISOString(),w=()=>{for(let k of g)r.markPRCommentsFetched(k.prUrl,b)};w();let y=null;g.length>0&&(y=await we(r,Tl,w));let S=g.filter(k=>k.truncated).map(k=>`${k.prUrl}: comment streams hit the pagination cap; newest comments are missing from the corpus`);return{repo:e.repo,bundles:g,prCount:g.length,skipped:u,failures:h,...y&&{gistSyncWarning:y},...S.length>0&&{warnings:S}}}function J3(e){return e===void 0||!Number.isFinite(e)||e<1?kF:Math.min(e,z3)}var Tl,j3,kF,z3,B3,Bo=A(()=>{"use strict";le();Q_();ce();Tl="guidelines",j3=/^[^/]+\/[^/]+$/,kF=5,z3=10,B3=365*24*60*60*1e3});var Nn=class extends Error{constructor(t,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=t,this.nestedError=void 0}},As=class extends Nn{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var tc=class{constructor(t,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,r){return r===this.defaultValue||!Array.isArray(r)?[t]:(r.push(t),r)}default(t,r){return this.defaultValue=t,this.defaultValueDescription=r,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new As(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Ol(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}var vC=require("node:events"),xl=B(require("node:child_process"),1),Gr=B(require("node:path"),1),nc=B(require("node:fs"),1),Ae=B(require("node:process"),1),kC=require("node:util");var wC=require("node:util"),rc=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let r=t.commands.filter(s=>!s._hidden),n=t._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,o)=>s.name().localeCompare(o.name())),r}compareOptions(t,r){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(t).localeCompare(n(r))}visibleOptions(t){let r=t.options.filter(s=>!s.hidden),n=t._getHelpOption();if(n&&!n.hidden){let s=n.short&&t._findOption(n.short),o=n.long&&t._findOption(n.long);!s&&!o?r.push(n):n.long&&!o?r.push(t.createOption(n.long,n.description)):n.short&&!s&&r.push(t.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let r=[];for(let n=t.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(r=>{r.description=r.description||t._argsDescription[r.name()]||""}),t.registeredArguments.find(r=>r.description)?t.registeredArguments:[]}subcommandTerm(t){let r=t.registeredArguments.map(n=>Ol(n)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,r){return r.visibleCommands(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(s)))),0)}longestOptionTermLength(t,r){return r.visibleOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestGlobalOptionTermLength(t,r){return r.visibleGlobalOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestArgumentTermLength(t,r){return r.visibleArguments(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(s)))),0)}commandUsage(t){let r=t._name;t._aliases[0]&&(r=r+"|"+t._aliases[0]);let n="";for(let s=t.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&r.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&r.push(`env: ${t.envVar}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}argumentDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatItemList(t,r,n){return r.length===0?[]:[n.styleTitle(t),...r,""]}groupItems(t,r,n){let s=new Map;return t.forEach(o=>{let i=n(o);s.has(i)||s.set(i,[])}),r.forEach(o=>{let i=n(o);s.has(i)||s.set(i,[]),s.get(i).push(o)}),s}formatHelp(t,r){let n=r.padWidth(t,r),s=r.helpWidth??80;function o(p,m){return r.formatItem(p,n,m,r)}let i=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(t))}`,""],a=r.commandDescription(t);a.length>0&&(i=i.concat([r.boxWrap(r.styleCommandDescription(a),s),""]));let c=r.visibleArguments(t).map(p=>o(r.styleArgumentTerm(r.argumentTerm(p)),r.styleArgumentDescription(r.argumentDescription(p))));if(i=i.concat(this.formatItemList("Arguments:",c,r)),this.groupItems(t.options,r.visibleOptions(t),p=>p.helpGroupHeading??"Options:").forEach((p,m)=>{let f=p.map(g=>o(r.styleOptionTerm(r.optionTerm(g)),r.styleOptionDescription(r.optionDescription(g))));i=i.concat(this.formatItemList(m,f,r))}),r.showGlobalOptions){let p=r.visibleGlobalOptions(t).map(m=>o(r.styleOptionTerm(r.optionTerm(m)),r.styleOptionDescription(r.optionDescription(m))));i=i.concat(this.formatItemList("Global Options:",p,r))}return this.groupItems(t.commands,r.visibleCommands(t),p=>p.helpGroup()||"Commands:").forEach((p,m)=>{let f=p.map(g=>o(r.styleSubcommandTerm(r.subcommandTerm(g)),r.styleSubcommandDescription(r.subcommandDescription(g))));i=i.concat(this.formatItemList(m,f,r))}),i.join(`
339
339
  `)}displayWidth(t){return(0,wC.stripVTControlCharacters)(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r==="[command]"?this.styleSubcommandText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleCommandText(r)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleSubcommandText(r)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,r){return Math.max(r.longestOptionTermLength(t,r),r.longestGlobalOptionTermLength(t,r),r.longestSubcommandTermLength(t,r),r.longestArgumentTermLength(t,r))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,r,n,s){let i=" ".repeat(2);if(!n)return i+t;let a=t.padEnd(r+t.length-s.displayWidth(t)),c=2,d=(this.helpWidth??80)-r-c-2,p;return d<this.minWidthToWrap||s.preformatted(n)?p=n:p=s.boxWrap(n,d).replace(/\n/g,`
340
340
  `+" ".repeat(r+c)),i+a+" ".repeat(c)+p.replace(/\n/g,`
341
341
  ${i}`)}boxWrap(t,r){if(r<this.minWidthToWrap)return t;let n=t.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,o=[];return n.forEach(i=>{let a=i.match(s);if(a===null){o.push("");return}let c=[a.shift()],u=this.displayWidth(c[0]);a.forEach(d=>{let p=this.displayWidth(d);if(u+p<=r){c.push(d),u+=p;return}o.push(c.join(""));let m=d.trimStart();c=[m],u=this.displayWidth(m)}),o.push(c.join(""))}),o.join(`
@@ -360,7 +360,7 @@ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[t]?this._life
360
360
  `),this.outputHelp({error:!0}));let n=r||{},s=n.exitCode||1,o=n.code||"commander.error";this._exit(s,o,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in Ae.default.env){let r=t.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,Ae.default.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new Il(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&t.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!r(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(t){let r=`error: missing required argument '${t}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(t){let r=`error: option '${t.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let r=`error: required option '${t.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,r){let n=i=>{let a=i.attributeName(),c=this.getOptionValue(a),u=this.options.find(p=>p.negate&&a===p.attributeName()),d=this.options.find(p=>!p.negate&&a===p.attributeName());return u&&(u.presetArg===void 0&&c===!1||u.presetArg!==void 0&&c===u.presetArg)?u:d||i},s=i=>{let a=n(i),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${s(t)} cannot be used with ${s(r)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let r="";if(t.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let i=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);s=s.concat(i),o=o.parent}while(o&&!o._enablePositionalOptions);r=Lg(t,s)}let n=`error: unknown option '${t}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",s=t.length,o=this.parent?` for '${this.name()}'`:"",i=t.join(", "),a=`error: too many arguments${o}. Expected ${r} argument${n} but got ${s}: ${i}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],r="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),r=Lg(t,s)}let n=`error: unknown command '${t}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(t,r,n){if(t===void 0)return this._version;this._version=t,r=r||"-V, --version",n=n||"output the version number";let s=this.createOption(r,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${t}
361
361
  `),this._exit(0,"commander.version",t)}),this}description(t,r){return t===void 0&&r===void 0?this._description:(this._description=t,r&&(this._argsDescription=r),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),t===r._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(t);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${s}'`)}return r._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(r=>this.alias(r)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>Ol(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup)}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup)}nameFromFilename(t){return this._name=Gr.default.basename(t,Gr.default.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let r=this.createHelp(),n=this._getOutputContext(t);r.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let s=r.formatHelp(this,r);return n.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(t){t=t||{};let r=!!t.error,n,s,o;return r?(n=a=>this._outputConfiguration.writeErr(a),s=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),s=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:r,write:a=>(s||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:s,helpWidth:o}}outputHelp(t){let r;typeof t=="function"&&(r=t,t=void 0);let n=this._getOutputContext(t),s={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let o=this.helpInformation({error:n.error});if(r&&(o=r(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",s))}helpOption(t,r){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",r??"display help for command"),(t||r)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let r=Number(Ae.default.exitCode??0);r===0&&t&&typeof t!="function"&&t.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(t,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(t))throw new Error(`Unexpected value for position to addHelpText.
362
362
  Expecting one of '${n.join("', '")}'`);let s=`${t}Help`;return this.on(s,o=>{let i;typeof r=="function"?i=r({error:o.error,command:o.command}):i=r,i&&o.write(`${i}
363
- `)}),this}_outputHelpIfRequested(t){let r=this._getHelpOption();r&&t.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function SC(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let r,n="127.0.0.1",s="9229",o;return(o=t.match(/^(--inspect(-brk)?)$/))!==null?r=o[1]:(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=o[1],/^\d+$/.test(o[3])?s=o[3]:n=o[3]):(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=o[1],n=o[3],s=o[4]),r&&s!=="0"?`${r}=${n}:${parseInt(s)+1}`:t})}function _C(){if(Ae.default.env.NO_COLOR||Ae.default.env.FORCE_COLOR==="0"||Ae.default.env.FORCE_COLOR==="false")return!1;if(Ae.default.env.FORCE_COLOR||Ae.default.env.CLICOLOR_FORCE!==void 0)return!0}var SJ=new Ko;le();ee();me();function Ho(e,t){let r=I(e);t?iv(r,am(e)):console.error(`Error: ${r}`),process.exit(1)}async function ae(e,t,r,n){try{let s=await t();e.json?n?av(n,s):ka(s):await r(s)}catch(s){Ho(s,e.json)}}function CF(e){let t=Object.entries(e).sort(([r],[n])=>r.localeCompare(n));for(let[r,n]of t){let s=n.currentBranch?` (${n.currentBranch})`:"";console.log(` ${r}${s}`),console.log(` ${n.path}`)}}var Og=[{name:"manifest",localOnly:!0,register(e){e.command("manifest").description("Print the CLI contract (registered commands + version) for plugin/MCP introspection (#1190)").option("--json","Output as JSON").action(async t=>{let{ManifestOutputSchema:r}=await Promise.resolve().then(()=>(me(),_e));await ae(t,async()=>{let{getCLIVersion:n}=await Promise.resolve().then(()=>(le(),uf));return{schemaVersion:1,cliVersion:n(),commands:Og.map(s=>({name:s.name,localOnly:!!s.localOnly})).sort((s,o)=>s.name.localeCompare(o.name))}},n=>{console.log(`oss-autopilot v${n.cliVersion} (${n.commands.length} commands)`)},r)})}},{name:"daily",register(e){e.command("daily").description("Run daily check on all tracked PRs").option("--json","Output as JSON").option("--compact","Reduce JSON payload by omitting summary, repoGroups, and full failure details").action(async t=>{try{let{stopStaleDashboardServer:r}=await Promise.resolve().then(()=>(Uv(),E0));if(await r(),t.json){let{runDaily:n}=await Promise.resolve().then(()=>(el(),vv)),s=await n();if(t.compact){let{toCompactDailyOutput:o,outputJsonValidated:i,CompactDailyOutputSchema:a}=await Promise.resolve().then(()=>(me(),_e));i(a,o(s))}else{let{outputJsonValidated:o,DailyOutputSchema:i}=await Promise.resolve().then(()=>(me(),_e));o(i,s)}}else{let{runDailyForDisplay:n,printDigest:s}=await Promise.resolve().then(()=>(el(),vv)),o=await n();s(o.digest,o.capacity,o.commentedIssues)}}catch(r){Ho(r,t.json)}})}},{name:"status",localOnly:!0,register(e){e.command("status").description("Show current status and stats").option("--json","Output as JSON").option("--offline","Show cache-freshness metadata (lastUpdated). Status always reads local state \u2014 no GitHub API calls are made either way.").action(async t=>{let{StatusOutputSchema:r}=await Promise.resolve().then(()=>(me(),_e));await ae(t,async()=>{let{runStatus:n}=await Promise.resolve().then(()=>(T0(),A0));return n({offline:t.offline})},n=>{console.log(`
363
+ `)}),this}_outputHelpIfRequested(t){let r=this._getHelpOption();r&&t.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function SC(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let r,n="127.0.0.1",s="9229",o;return(o=t.match(/^(--inspect(-brk)?)$/))!==null?r=o[1]:(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=o[1],/^\d+$/.test(o[3])?s=o[3]:n=o[3]):(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=o[1],n=o[3],s=o[4]),r&&s!=="0"?`${r}=${n}:${parseInt(s)+1}`:t})}function _C(){if(Ae.default.env.NO_COLOR||Ae.default.env.FORCE_COLOR==="0"||Ae.default.env.FORCE_COLOR==="false")return!1;if(Ae.default.env.FORCE_COLOR||Ae.default.env.CLICOLOR_FORCE!==void 0)return!0}var _J=new Ko;le();ee();me();function Ho(e,t){let r=I(e);t?iv(r,am(e)):console.error(`Error: ${r}`),process.exit(1)}async function ae(e,t,r,n){try{let s=await t();e.json?n?av(n,s):ka(s):await r(s)}catch(s){Ho(s,e.json)}}function CF(e){let t=Object.entries(e).sort(([r],[n])=>r.localeCompare(n));for(let[r,n]of t){let s=n.currentBranch?` (${n.currentBranch})`:"";console.log(` ${r}${s}`),console.log(` ${n.path}`)}}var Og=[{name:"manifest",localOnly:!0,register(e){e.command("manifest").description("Print the CLI contract (registered commands + version) for plugin/MCP introspection (#1190)").option("--json","Output as JSON").action(async t=>{let{ManifestOutputSchema:r}=await Promise.resolve().then(()=>(me(),_e));await ae(t,async()=>{let{getCLIVersion:n}=await Promise.resolve().then(()=>(le(),uf));return{schemaVersion:1,cliVersion:n(),commands:Og.map(s=>({name:s.name,localOnly:!!s.localOnly})).sort((s,o)=>s.name.localeCompare(o.name))}},n=>{console.log(`oss-autopilot v${n.cliVersion} (${n.commands.length} commands)`)},r)})}},{name:"daily",register(e){e.command("daily").description("Run daily check on all tracked PRs").option("--json","Output as JSON").option("--compact","Reduce JSON payload by omitting summary, repoGroups, and full failure details").action(async t=>{try{let{stopStaleDashboardServer:r}=await Promise.resolve().then(()=>(Uv(),E0));if(await r(),t.json){let{runDaily:n}=await Promise.resolve().then(()=>(el(),vv)),s=await n();if(t.compact){let{toCompactDailyOutput:o,outputJsonValidated:i,CompactDailyOutputSchema:a}=await Promise.resolve().then(()=>(me(),_e));i(a,o(s))}else{let{outputJsonValidated:o,DailyOutputSchema:i}=await Promise.resolve().then(()=>(me(),_e));o(i,s)}}else{let{runDailyForDisplay:n,printDigest:s}=await Promise.resolve().then(()=>(el(),vv)),o=await n();s(o.digest,o.capacity,o.commentedIssues)}}catch(r){Ho(r,t.json)}})}},{name:"status",localOnly:!0,register(e){e.command("status").description("Show current status and stats").option("--json","Output as JSON").option("--offline","Show cache-freshness metadata (lastUpdated). Status always reads local state \u2014 no GitHub API calls are made either way.").action(async t=>{let{StatusOutputSchema:r}=await Promise.resolve().then(()=>(me(),_e));await ae(t,async()=>{let{runStatus:n}=await Promise.resolve().then(()=>(T0(),A0));return n({offline:t.offline})},n=>{console.log(`
364
364
  \u{1F4CA} OSS Status
365
365
  `),console.log(`Merged PRs: ${n.stats.mergedPRs}`),console.log(`Closed PRs: ${n.stats.closedPRs}`),console.log(`Merge Rate: ${n.stats.mergeRate}`),console.log(`Needs Response: ${n.stats.needsResponse}`),n.offline?(console.log(`
366
366
  Last Updated: ${n.lastUpdated||"Never"}`),console.log("(Status reads from local state \u2014 no GitHub API calls)")):console.log(`
@@ -441,7 +441,7 @@ ${n.summary.ok} ok / ${n.summary.warnings} warning / ${n.summary.errors} error
441
441
  `)},r)})}},{name:"local-repos",localOnly:!0,register(e){e.command("local-repos").description("Scan filesystem for local git clones").option("--scan","Force re-scan (ignores cache)").option("--paths <dirs...>","Directories to scan").option("--json","Output as JSON").action(async t=>{let{LocalReposOutputSchema:r}=await Promise.resolve().then(()=>(me(),_e));await ae(t,async()=>(await Promise.resolve().then(()=>(BM(),zM))).runLocalRepos({scan:t.scan,paths:t.paths}),n=>{n.fromCache?(console.log(`
442
442
  \u{1F4C1} Local Repos (cached ${n.cachedAt})
443
443
  `),CF(n.repos)):(console.log(`Found ${Object.keys(n.repos).length} repos:
444
- `),CF(n.repos))},r)})}},{name:"startup",localOnly:!0,register(e){e.command("startup").description("Run all pre-flight checks and daily fetch in one call").option("--json","Output as JSON").option("--compact","Reduce JSON payload by omitting summary, repoGroups, and full failure details").action(async t=>{try{let{runStartup:r}=await Promise.resolve().then(()=>(sl(),u0)),n=await r();if(t.json)if(t.compact){let{toCompactStartupOutput:s}=await Promise.resolve().then(()=>(me(),_e));ka(s(n))}else ka(n);else n.setupComplete?n.authError?console.error(`Error: ${n.authError}`):(console.log(`OSS Autopilot v${n.version}`),console.log(n.daily?.briefSummary??"")):console.log("Setup incomplete. Run /setup-oss first.")}catch(r){Ho(r,t.json)}})}},{name:"move",localOnly:!0,register(e){e.command("move <pr-url> <target>").description("Move a PR between states: attention, waiting, shelved, or auto (reset to computed)").option("--json","Output as JSON").action(async(t,r,n)=>{let{MoveOutputSchema:s}=await Promise.resolve().then(()=>(me(),_e));await ae(n,async()=>(await Promise.resolve().then(()=>(qv(),Vv))).runMove({prUrl:t,target:r}),o=>{console.log(o.description)},s)})}},{name:"dismiss",localOnly:!0,register(e){e.command("dismiss <url>").description("Dismiss notifications for an issue or PR (resurfaces on new activity)").option("--head <sha>","PR URLs only: the PR's full head SHA now, so the review follow-up stays hidden until a new push or comment").option("--json","Output as JSON").action((t,r)=>ae(r,async()=>(await Promise.resolve().then(()=>(Tf(),Af))).runDismiss({url:t,head:r.head}),n=>{n.dismissed?(console.log(`Dismissed: ${t}`),console.log("Notifications are now muted."),console.log(r.head?"A new push or a comment after this point will resurface it automatically.":"New responses after this point will resurface automatically.")):console.log("Already dismissed.")}))}},{name:"undismiss",localOnly:!0,register(e){e.command("undismiss <url>").description("Undismiss an issue or PR (re-enable notifications)").option("--json","Output as JSON").action((t,r)=>ae(r,async()=>(await Promise.resolve().then(()=>(Tf(),Af))).runUndismiss({url:t}),n=>{n.undismissed?(console.log(`Undismissed: ${t}`),console.log("Notifications are active again.")):console.log("Was not dismissed.")}))}},{name:"work",localOnly:!0,register(e){let t=e.command("work").description("Record which items are being worked on: background implementations and PRs under Tier 2 work (#1856, #1852)");t.command("claim <url>").description("Claim an issue (--kind implementation, while a fix is built) or a PR (--kind pr, while this session works it)").requiredOption("--kind <kind>","implementation (issue URL) or pr (PR URL)").requiredOption("--session <name>","Name of the session taking the claim").option("--branch <name>","Branch the implementation is on").option("--worktree <path>","Checkout the implementation runs in (one running implementation per checkout)").option("--run-id <id>","Remote worker run id, when the implementation runs off-machine").option("--ttl <hours>","Claim lifetime in hours (default: 24 for implementation, 12 for pr)",Number).option("--takeover","Replace a live claim another session holds on this item (refused without it)").option("--json","Output as JSON").action(async(r,n)=>{let{WorkClaimOutputSchema:s}=await Promise.resolve().then(()=>(me(),_e)),{runWorkClaim:o}=await Promise.resolve().then(()=>(El(),Pl)),i={claimed:"Claimed",renewed:"Renewed","took-over":"Took over"};await ae(n,()=>o({url:r,kind:n.kind,session:n.session,branch:n.branch,worktree:n.worktree,runId:n.runId,ttlHours:n.ttl,takeover:n.takeover}),a=>{console.log(`${i[a.outcome]} ${a.claim.kind} on ${a.claim.url} for session ${a.claim.session} (expires ${a.claim.expiresAt})`),a.synced||console.log("Claimed locally only: other machines cannot see this claim yet."),a.gistSyncWarning&&console.log(`Warning: ${a.gistSyncWarning}`)},s)}),t.command("finish <url>").description("Mark the implementation claim on an issue finished: its branch is ready to collect and review").option("--session <name>","Refuse unless the live claim belongs to this session").option("--json","Output as JSON").action(async(r,n)=>{let{WorkFinishOutputSchema:s}=await Promise.resolve().then(()=>(me(),_e)),{runWorkFinish:o}=await Promise.resolve().then(()=>(El(),Pl));await ae(n,()=>o({url:r,session:n.session}),i=>{console.log(i.claim?`Finished: ${r} (session ${i.claim.session})`:`No live claim on ${r}.`),i.gistSyncWarning&&console.log(`Warning: ${i.gistSyncWarning}`)},s)}),t.command("release [url]").description("Drop the claim on a URL, or every claim a session holds (--session, optionally --kind)").option("--session <name>","Release every claim this session holds").option("--kind <kind>","With --session: only claims of this kind (implementation or pr)").option("--json","Output as JSON").action(async(r,n)=>{let{WorkReleaseOutputSchema:s}=await Promise.resolve().then(()=>(me(),_e)),{runWorkRelease:o}=await Promise.resolve().then(()=>(El(),Pl));await ae(n,()=>o({url:r,session:n.session,kind:n.kind}),i=>{let a=i.released.map(c=>" "+c).join(`
444
+ `),CF(n.repos))},r)})}},{name:"startup",localOnly:!0,register(e){e.command("startup").description("Run all pre-flight checks and daily fetch in one call").option("--json","Output as JSON").option("--compact","Reduce JSON payload by omitting summary, repoGroups, and full failure details").action(async t=>{try{let{runStartup:r}=await Promise.resolve().then(()=>(sl(),u0)),n=await r();if(t.json)if(t.compact){let{toCompactStartupOutput:s}=await Promise.resolve().then(()=>(me(),_e));ka(s(n))}else ka(n);else n.setupComplete?n.authError?console.error(`Error: ${n.authError}`):(console.log(`OSS Autopilot v${n.version}`),console.log(n.daily?.briefSummary??"")):console.log("Setup incomplete. Run /setup-oss first.")}catch(r){Ho(r,t.json)}})}},{name:"move",localOnly:!0,register(e){e.command("move <pr-url> <target>").description("Move a PR between states: attention, waiting, shelved, or auto (reset to computed)").option("--json","Output as JSON").action(async(t,r,n)=>{let{MoveOutputSchema:s}=await Promise.resolve().then(()=>(me(),_e));await ae(n,async()=>(await Promise.resolve().then(()=>(qv(),Vv))).runMove({prUrl:t,target:r}),o=>{console.log(o.description)},s)})}},{name:"dismiss",localOnly:!0,register(e){e.command("dismiss <url>").description("Dismiss notifications for an issue or PR (resurfaces on new activity)").option("--head <sha>","PR URLs only: the PR's full head SHA now, so the review follow-up stays hidden until a new push or comment").option("--json","Output as JSON").action((t,r)=>ae(r,async()=>(await Promise.resolve().then(()=>(Tf(),Af))).runDismiss({url:t,head:r.head}),n=>{n.dismissed?(console.log(`Dismissed: ${t}`),n.warning?console.log(`Warning: ${n.warning}`):(console.log("Notifications are now muted."),console.log(r.head?"A new push or a comment after this point will resurface it automatically.":"New responses after this point will resurface automatically."))):console.log("Already dismissed.")}))}},{name:"undismiss",localOnly:!0,register(e){e.command("undismiss <url>").description("Undismiss an issue or PR (re-enable notifications)").option("--json","Output as JSON").action((t,r)=>ae(r,async()=>(await Promise.resolve().then(()=>(Tf(),Af))).runUndismiss({url:t}),n=>{n.undismissed?(console.log(`Undismissed: ${t}`),console.log("Notifications are active again.")):console.log("Was not dismissed.")}))}},{name:"work",localOnly:!0,register(e){let t=e.command("work").description("Record which items are being worked on: background implementations and PRs under Tier 2 work (#1856, #1852)");t.command("claim <url>").description("Claim an issue (--kind implementation, while a fix is built) or a PR (--kind pr, while this session works it)").requiredOption("--kind <kind>","implementation (issue URL) or pr (PR URL)").requiredOption("--session <name>","Name of the session taking the claim").option("--branch <name>","Branch the implementation is on").option("--worktree <path>","Checkout the implementation runs in (one running implementation per checkout)").option("--run-id <id>","Remote worker run id, when the implementation runs off-machine").option("--ttl <hours>","Claim lifetime in hours (default: 24 for implementation, 12 for pr)",Number).option("--takeover","Replace a live claim another session holds on this item (refused without it)").option("--json","Output as JSON").action(async(r,n)=>{let{WorkClaimOutputSchema:s}=await Promise.resolve().then(()=>(me(),_e)),{runWorkClaim:o}=await Promise.resolve().then(()=>(El(),Pl)),i={claimed:"Claimed",renewed:"Renewed","took-over":"Took over"};await ae(n,()=>o({url:r,kind:n.kind,session:n.session,branch:n.branch,worktree:n.worktree,runId:n.runId,ttlHours:n.ttl,takeover:n.takeover}),a=>{console.log(`${i[a.outcome]} ${a.claim.kind} on ${a.claim.url} for session ${a.claim.session} (expires ${a.claim.expiresAt})`),a.synced||console.log("Claimed locally only: other machines cannot see this claim yet."),a.gistSyncWarning&&console.log(`Warning: ${a.gistSyncWarning}`)},s)}),t.command("finish <url>").description("Mark the implementation claim on an issue finished: its branch is ready to collect and review").option("--session <name>","Refuse unless the live claim belongs to this session").option("--json","Output as JSON").action(async(r,n)=>{let{WorkFinishOutputSchema:s}=await Promise.resolve().then(()=>(me(),_e)),{runWorkFinish:o}=await Promise.resolve().then(()=>(El(),Pl));await ae(n,()=>o({url:r,session:n.session}),i=>{console.log(i.claim?`Finished: ${r} (session ${i.claim.session})`:`No live claim on ${r}.`),i.gistSyncWarning&&console.log(`Warning: ${i.gistSyncWarning}`)},s)}),t.command("release [url]").description("Drop the claim on a URL, or every claim a session holds (--session, optionally --kind)").option("--session <name>","Release every claim this session holds").option("--kind <kind>","With --session: only claims of this kind (implementation or pr)").option("--json","Output as JSON").action(async(r,n)=>{let{WorkReleaseOutputSchema:s}=await Promise.resolve().then(()=>(me(),_e)),{runWorkRelease:o}=await Promise.resolve().then(()=>(El(),Pl));await ae(n,()=>o({url:r,session:n.session,kind:n.kind}),i=>{let a=i.released.map(c=>" "+c).join(`
445
445
  `);console.log(i.released.length===0?"No live claims matched; nothing released.":`Released ${i.released.length} claim(s):
446
446
  ${a}`),i.gistSyncWarning&&console.log(`Warning: ${i.gistSyncWarning}`)},s)}),t.command("list").description("List live claims across sessions and machines").option("--json","Output as JSON").action(async r=>{let{WorkListOutputSchema:n}=await Promise.resolve().then(()=>(me(),_e)),{runWorkList:s}=await Promise.resolve().then(()=>(El(),Pl));await ae(r,()=>s(),o=>{if(o.claims.length===0)console.log("No live work claims.");else{console.log(`${o.claims.length} live work claim(s):`);for(let a of o.claims){let c=a.worktree??a.runId??"";console.log(` [${a.kind}/${a.status}] ${a.url} \u2014 session ${a.session} ${c}`.trimEnd())}}o.expiredCount>0&&console.log(`${o.expiredCount} expired claim(s) will be pruned on the next write.`);let i=o.warnings??[];for(let a of i)console.log(`Warning (may be stale): ${a.message}`)},n)})}},{name:"pr-template",register(e){e.command("pr-template <repo>").description("Fetch a repository's PR description template").option("--json","Output as JSON").action(async(t,r)=>{let{PRTemplateOutputSchema:n}=await Promise.resolve().then(()=>(me(),_e));await ae(r,async()=>(await Promise.resolve().then(()=>(XM(),QM))).runPRTemplate({repo:t}),s=>{s.template?(console.log(`
447
447
  PR template found at: ${s.source}
@@ -463,7 +463,7 @@ OSS Contribution Stats (@${o.username})
463
463
  `),console.log(` Merged PRs: ${o.totalMerged}`),console.log(` Closed PRs: ${o.totalClosed}`),console.log(` Merge Rate: ${o.mergeRateFormatted}`),console.log(` Active PRs: ${o.activePRs}`),console.log(` Repos Contributed: ${o.reposContributed}`),o.topRepos.length>0){console.log(`
464
464
  Top Repos:`);for(let i of o.topRepos.slice(0,5))console.log(` ${i.repo}: ${i.mergedCount} merged`)}console.log(`
465
465
  Use --markdown for a shareable report or --badge for shields.io`)}}catch(r){Ho(r,t.json)}})}},{name:"guidelines",localOnly:!0,register(e){let t=e.command("guidelines").description("Manage per-repo learning guidelines extracted from PR feedback (#867)");t.command("list").description("List repos with stored guidelines (always empty in local mode)").option("--json","Output as JSON").action(async r=>{await ae(r,async()=>(await Promise.resolve().then(()=>(Bo(),zo))).runGuidelinesList(),n=>{if(n.count===0)console.log(`No guidelines stored for any repo (storage: ${n.storageMode}).`);else{console.log(`${n.count} repo(s) with stored guidelines:`);for(let s of n.repos)console.log(` ${s}`)}})}),t.command("view").description("Read the per-repo guidelines file (returns null when none exists or in local mode)").requiredOption("--repo <owner/repo>","Repository identifier").option("--json","Output as JSON").action(async r=>{await ae(r,async()=>(await Promise.resolve().then(()=>(Bo(),zo))).runGuidelinesView({repo:r.repo}),n=>{n.content===null?console.log(`No guidelines stored for ${n.repo} (storage: ${n.storageMode}).`):(console.log(`# Guidelines for ${n.repo} (${n.byteSize} bytes)
466
- `),console.log(n.content))})}),t.command("store").description("Persist per-repo guidelines (overwrites). Reads markdown content from --content or stdin.").requiredOption("--repo <owner/repo>","Repository identifier").option("--content <markdown>","Markdown content. If omitted, reads from stdin.").option("--json","Output as JSON").action(async r=>{await ae(r,async()=>{let n=r.content??await J3();return(await Promise.resolve().then(()=>(Bo(),zo))).runGuidelinesStore({repo:r.repo,content:n})},n=>{console.log(`Stored ${n.byteSize} bytes of guidelines for ${n.repo}.`)})}),t.command("mark-extracted").description("Stamp learningsExtractedAt on fetched PRs of a repo so daily stops reporting them as unextracted (#1696)").requiredOption("--repo <owner/repo>","Repository identifier").option("--json","Output as JSON").action(async r=>{await ae(r,async()=>(await Promise.resolve().then(()=>(Bo(),zo))).runMarkExtracted({repo:r.repo}),n=>{console.log(`Marked ${n.marked} PR(s) in ${n.repo} as extracted.`)})}),t.command("reset").description("Tombstone the guidelines file for a repo (subsequent reads return null)").requiredOption("--repo <owner/repo>","Repository identifier").option("--json","Output as JSON").action(async r=>{await ae(r,async()=>(await Promise.resolve().then(()=>(Bo(),zo))).runGuidelinesReset({repo:r.repo}),n=>{console.log(n.deleted?`Reset guidelines for ${n.repo}.`:`No guidelines existed for ${n.repo}; nothing to reset.`)})}),t.command("fetch-corpus").description("Fetch raw PR comment bundles for the host extract-learnings prompt to consume").requiredOption("--repo <owner/repo>","Repository identifier").option("--limit <n>","Max PRs to process (1-10, default 5)",r=>parseInt(r,10)).option("--force","Re-fetch even when commentsFetchedAt is already set").option("--json","Output as JSON").action(async r=>{await ae(r,async()=>(await Promise.resolve().then(()=>(Bo(),zo))).runFetchCorpus({repo:r.repo,limit:r.limit,forceRefetch:r.force}),n=>{console.log(`Fetched ${n.prCount} PR comment bundle(s) for ${n.repo}.`),n.skipped>0&&console.log(` Skipped ${n.skipped} PR(s) already processed (use --force to re-fetch).`)})})}}];async function J3(){if(process.stdin.isTTY)throw new Error('No --content provided and stdin is a TTY. Pipe content or pass --content "...".');let e="";for await(let t of process.stdin)e+=t;return e}le();function PF(e,t){e.hook("preAction",async(r,n)=>{r.opts().debug&&(rm(),O("cli",`Running command: ${n.name()}`));let o=n,i=!1;for(;o;){if(t.has(o.name())){i=!0;break}o=o.parent}if(i){let{bootstrapGistBestEffort:a}=await Promise.resolve().then(()=>(le(),uf)),c=await a(xr);if(c){console.error(`Warning: ${c}`);let{setEnvelopeGistWarning:u}=await Promise.resolve().then(()=>(me(),_e));u(c)}}else{let a=await xr();if(!a){if(!!n.opts().json||process.argv.includes("--json")){let{outputJsonError:m}=await Promise.resolve().then(()=>(me(),_e));m("GitHub authentication required. Install gh CLI and run `gh auth login`, or set GITHUB_TOKEN.","AUTH_REQUIRED")}else console.error("Error: GitHub authentication required."),console.error(""),console.error("Option 1 (Recommended): Install and authenticate GitHub CLI"),console.error(" Install: https://cli.github.com/"),console.error(" Then run: gh auth login"),console.error(""),console.error("Option 2: Set GITHUB_TOKEN environment variable"),console.error(' export GITHUB_TOKEN="your-github-token-here"'),console.error(""),console.error("Then run your command again.");process.exit(1)}let{ensureGistPersistence:c,renderGistWarning:u}=await Promise.resolve().then(()=>(le(),uf)),d=await c(a);if(d==="degraded"||d==="state-unreadable"){let{setEnvelopeGistWarning:p}=await Promise.resolve().then(()=>(me(),_e));p(u(d==="degraded"?"init-fallback":"state-unreadable"))}}})}var Y3=Wr(),Ig=new Ko;Ig.name("oss-autopilot").description("AI-powered autopilot for managing open source contributions").version(Y3).option("--debug","Enable debug logging");var Q3=new Set(Og.filter(e=>e.localOnly).map(e=>e.name));for(let e of Og)e.register(Ig);PF(Ig,Q3);var EF=process.argv.slice(2),X3=EF.some(e=>!e.startsWith("-")),eJ=EF.some(e=>e==="--help"||e==="-h"||e==="--version"||e==="-V");!X3&&!eJ&&!em()&&(console.log(`
466
+ `),console.log(n.content))})}),t.command("store").description("Persist per-repo guidelines (overwrites). Reads markdown content from --content or stdin.").requiredOption("--repo <owner/repo>","Repository identifier").option("--content <markdown>","Markdown content. If omitted, reads from stdin.").option("--json","Output as JSON").action(async r=>{await ae(r,async()=>{let n=r.content??await Y3();return(await Promise.resolve().then(()=>(Bo(),zo))).runGuidelinesStore({repo:r.repo,content:n})},n=>{console.log(`Stored ${n.byteSize} bytes of guidelines for ${n.repo}.`)})}),t.command("mark-extracted").description("Stamp learningsExtractedAt on fetched PRs of a repo so daily stops reporting them as unextracted (#1696)").requiredOption("--repo <owner/repo>","Repository identifier").option("--json","Output as JSON").action(async r=>{await ae(r,async()=>(await Promise.resolve().then(()=>(Bo(),zo))).runMarkExtracted({repo:r.repo}),n=>{console.log(`Marked ${n.marked} PR(s) in ${n.repo} as extracted.`)})}),t.command("reset").description("Tombstone the guidelines file for a repo (subsequent reads return null)").requiredOption("--repo <owner/repo>","Repository identifier").option("--json","Output as JSON").action(async r=>{await ae(r,async()=>(await Promise.resolve().then(()=>(Bo(),zo))).runGuidelinesReset({repo:r.repo}),n=>{console.log(n.deleted?`Reset guidelines for ${n.repo}.`:`No guidelines existed for ${n.repo}; nothing to reset.`)})}),t.command("fetch-corpus").description("Fetch raw PR comment bundles for the host extract-learnings prompt to consume").requiredOption("--repo <owner/repo>","Repository identifier").option("--limit <n>","Max PRs to process (1-10, default 5)",r=>parseInt(r,10)).option("--force","Re-fetch even when commentsFetchedAt is already set").option("--json","Output as JSON").action(async r=>{await ae(r,async()=>(await Promise.resolve().then(()=>(Bo(),zo))).runFetchCorpus({repo:r.repo,limit:r.limit,forceRefetch:r.force}),n=>{console.log(`Fetched ${n.prCount} PR comment bundle(s) for ${n.repo}.`),n.skipped>0&&console.log(` Skipped ${n.skipped} PR(s) already processed (use --force to re-fetch).`)})})}}];async function Y3(){if(process.stdin.isTTY)throw new Error('No --content provided and stdin is a TTY. Pipe content or pass --content "...".');let e="";for await(let t of process.stdin)e+=t;return e}le();function PF(e,t){e.hook("preAction",async(r,n)=>{r.opts().debug&&(rm(),O("cli",`Running command: ${n.name()}`));let o=n,i=!1;for(;o;){if(t.has(o.name())){i=!0;break}o=o.parent}if(i){let{bootstrapGistBestEffort:a}=await Promise.resolve().then(()=>(le(),uf)),c=await a(xr);if(c){console.error(`Warning: ${c}`);let{setEnvelopeGistWarning:u}=await Promise.resolve().then(()=>(me(),_e));u(c)}}else{let a=await xr();if(!a){if(!!n.opts().json||process.argv.includes("--json")){let{outputJsonError:m}=await Promise.resolve().then(()=>(me(),_e));m("GitHub authentication required. Install gh CLI and run `gh auth login`, or set GITHUB_TOKEN.","AUTH_REQUIRED")}else console.error("Error: GitHub authentication required."),console.error(""),console.error("Option 1 (Recommended): Install and authenticate GitHub CLI"),console.error(" Install: https://cli.github.com/"),console.error(" Then run: gh auth login"),console.error(""),console.error("Option 2: Set GITHUB_TOKEN environment variable"),console.error(' export GITHUB_TOKEN="your-github-token-here"'),console.error(""),console.error("Then run your command again.");process.exit(1)}let{ensureGistPersistence:c,renderGistWarning:u}=await Promise.resolve().then(()=>(le(),uf)),d=await c(a);if(d==="degraded"||d==="state-unreadable"){let{setEnvelopeGistWarning:p}=await Promise.resolve().then(()=>(me(),_e));p(u(d==="degraded"?"init-fallback":"state-unreadable"))}}})}var Q3=Wr(),Ig=new Ko;Ig.name("oss-autopilot").description("AI-powered autopilot for managing open source contributions").version(Q3).option("--debug","Enable debug logging");var X3=new Set(Og.filter(e=>e.localOnly).map(e=>e.name));for(let e of Og)e.register(Ig);PF(Ig,X3);var EF=process.argv.slice(2),eJ=EF.some(e=>!e.startsWith("-")),tJ=EF.some(e=>e==="--help"||e==="-h"||e==="--version"||e==="-V");!eJ&&!tJ&&!em()&&(console.log(`
467
467
  OSS Autopilot \u2014 AI copilot for open source contributions
468
468
 
469
469
  Looks like this is your first run! Quick start: