@skyramp/testbot-core 0.13.0-v3.237 → 0.13.0-v3.238
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/VERSION.json +1 -1
- package/dist/main.js +3 -3
- package/package.json +1 -1
package/dist/VERSION.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":"0.13.0-v3.
|
|
1
|
+
{"version":"0.13.0-v3.238","commit":"3279e4b35044d782953d676187d3edf31b0ef486"}
|
package/dist/main.js
CHANGED
|
@@ -239,7 +239,7 @@ If the error persists, please check whether Actions and API requests are operati
|
|
|
239
239
|
`),{[t]:fu.relative(e.runDir,s)}}function Qi(e,t){return{name:e,verify(r,n){let{errors:s}=t(r,n);return s.length===0?{name:this.name,passed:!0}:sr(this.name,s,{fatal:!0})}}}function mu(e,t){return fu.relative(e,fu.resolve(e,t)).replace(/\/+$/,"")}function OR(e){return e.replace(/\s+/g," ").trim()}function xA(e){return fu.basename(e).replace(/\.[^.]+$/,"").toLowerCase()}function dQ(e,t){let r=e.trim().replace(/^\.\//,""),n=t.trim().replace(/^\.\//,"");return r===n||r.endsWith(`/${n}`)||n.endsWith(`/${r}`)}function pQ(e,t){return(e.match(/[\w.@-]+(?:\/[\w.@-]+)*\.\w+/g)??[]).some(r=>dQ(r,t))}var pc=new RegExp("(^|/)("+["test_[^/]+\\.py","[^/]+_test\\.py","[^/]+\\.(spec|test)\\.[cm]?[jt]sx?","[^/]+\\.e2e-(spec|test)\\.[cm]?[jt]sx?","[^/]+_test\\.go","[^/]+Tests?\\.(java|kts?)","[^/]+_(test|spec)\\.rb","[^/]+\\.feature","[^/]+Tests?\\.cs","[^/]+_test\\.rs","tests/[^/]+\\.rs","[^/]+Test\\.php","[^/]+(Test|Spec|Suite)\\.scala","[^/]+Tests?\\.swift","[^/]+_test\\.exs","[^/]+_test\\.dart","[^/]+_test\\.(c|cc|cpp|cxx)","test_[^/]+\\.(c|cc|cpp|cxx)","[^/]+(Spec|Test)\\.groovy"].join("|")+")$","i");function QR(e){if(!e.inputs.skyrampMcp?.command)return!1;for(let t of Object.values(e.state.stages))for(let r of t.attempts??[]){let n=r.mcpServers?.skyramp;if(n!==void 0&&n!=="connected")return!1}return!0}var E={};Jm(E,{BRAND:()=>SRt,DIRTY:()=>vA,EMPTY_PATH:()=>eRt,INVALID:()=>At,NEVER:()=>o0t,OK:()=>Mi,ParseStatus:()=>hi,Schema:()=>$t,ZodAny:()=>Ah,ZodArray:()=>pp,ZodBigInt:()=>RA,ZodBoolean:()=>TA,ZodBranded:()=>FR,ZodCatch:()=>LA,ZodDate:()=>kA,ZodDefault:()=>FA,ZodDiscriminatedUnion:()=>mQ,ZodEffects:()=>mc,ZodEnum:()=>QA,ZodError:()=>qo,ZodFirstPartyTypeKind:()=>Ct,ZodFunction:()=>AQ,ZodIntersection:()=>PA,ZodIssueCode:()=>Re,ZodLazy:()=>DA,ZodLiteral:()=>OA,ZodMap:()=>qb,ZodNaN:()=>jb,ZodNativeEnum:()=>MA,ZodNever:()=>dl,ZodNull:()=>NA,ZodNullable:()=>yu,ZodNumber:()=>IA,ZodObject:()=>Go,ZodOptional:()=>fc,ZodParsedType:()=>Ve,ZodPipeline:()=>LR,ZodPromise:()=>yh,ZodReadonly:()=>UA,ZodRecord:()=>gQ,ZodSchema:()=>$t,ZodSet:()=>Gb,ZodString:()=>gh,ZodSymbol:()=>Ub,ZodTransformer:()=>mc,ZodTuple:()=>Au,ZodType:()=>$t,ZodUndefined:()=>BA,ZodUnion:()=>_A,ZodUnknown:()=>dp,ZodVoid:()=>$b,addIssueToContext:()=>Me,any:()=>NRt,array:()=>ORt,bigint:()=>IRt,boolean:()=>DBe,coerce:()=>i0t,custom:()=>NBe,date:()=>RRt,datetimeRegex:()=>kBe,defaultErrorMap:()=>lp,discriminatedUnion:()=>LRt,effect:()=>KRt,enum:()=>WRt,function:()=>HRt,getErrorMap:()=>Mb,getParsedType:()=>gu,instanceof:()=>xRt,intersection:()=>URt,isAborted:()=>fQ,isAsync:()=>Fb,isDirty:()=>hQ,isValid:()=>mh,late:()=>CRt,lazy:()=>zRt,literal:()=>VRt,makeIssue:()=>MR,map:()=>GRt,nan:()=>vRt,nativeEnum:()=>JRt,never:()=>PRt,null:()=>BRt,nullable:()=>ZRt,number:()=>PBe,object:()=>QRt,objectUtil:()=>l4,oboolean:()=>s0t,onumber:()=>n0t,optional:()=>XRt,ostring:()=>r0t,pipeline:()=>t0t,preprocess:()=>e0t,promise:()=>YRt,quotelessJson:()=>KIt,record:()=>qRt,set:()=>jRt,setErrorMap:()=>ZIt,strictObject:()=>MRt,string:()=>_Be,symbol:()=>TRt,transformer:()=>KRt,tuple:()=>$Rt,undefined:()=>kRt,union:()=>FRt,unknown:()=>_Rt,util:()=>Yt,void:()=>DRt});var Yt;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function r(s){throw new Error}e.assertNever=r,e.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},e.getValidEnumValues=s=>{let i=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return e.objectValues(o)},e.objectValues=s=>e.objectKeys(s).map(function(i){return s[i]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},e.find=(s,i)=>{for(let o of s)if(i(o))return o},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Yt||(Yt={}));var l4;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(l4||(l4={}));var Ve=Yt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),gu=e=>{switch(typeof e){case"undefined":return Ve.undefined;case"string":return Ve.string;case"number":return Number.isNaN(e)?Ve.nan:Ve.number;case"boolean":return Ve.boolean;case"function":return Ve.function;case"bigint":return Ve.bigint;case"symbol":return Ve.symbol;case"object":return Array.isArray(e)?Ve.array:e===null?Ve.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Ve.promise:typeof Map<"u"&&e instanceof Map?Ve.map:typeof Set<"u"&&e instanceof Set?Ve.set:typeof Date<"u"&&e instanceof Date?Ve.date:Ve.object;default:return Ve.unknown}};var Re=Yt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),KIt=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),qo=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c<o.path.length;){let l=o.path[c],u=c===o.path.length-1;if(l==="_errors"){u&&a._errors.push(r(o)),c++;continue}Object.prototype.hasOwnProperty.call(a,l)||(l==="__proto__"?Object.defineProperty(a,l,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):a[l]={_errors:[]}),a=a[l],u&&a._errors.push(r(o)),c++}}};return s(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Yt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r=Object.create(null),n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];r[i]=r[i]||[],r[i].push(t(s))}else n.push(t(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};qo.create=e=>new qo(e);var XIt=(e,t)=>{let r;switch(e.code){case Re.invalid_type:e.received===Ve.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case Re.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Yt.jsonStringifyReplacer)}`;break;case Re.unrecognized_keys:r=`Unrecognized key(s) in object: ${Yt.joinValues(e.keys,", ")}`;break;case Re.invalid_union:r="Invalid input";break;case Re.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Yt.joinValues(e.options)}`;break;case Re.invalid_enum_value:r=`Invalid enum value. Expected ${Yt.joinValues(e.options)}, received '${e.received}'`;break;case Re.invalid_arguments:r="Invalid function arguments";break;case Re.invalid_return_type:r="Invalid function return type";break;case Re.invalid_date:r="Invalid date";break;case Re.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Yt.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case Re.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case Re.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case Re.custom:r="Invalid input";break;case Re.invalid_intersection_types:r="Intersection results could not be merged";break;case Re.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Re.not_finite:r="Number must be finite";break;default:r=t.defaultError,Yt.assertNever(e)}return{message:r}},lp=XIt;var xBe=lp;function ZIt(e){xBe=e}function Mb(){return xBe}var MR=e=>{let{data:t,path:r,errorMaps:n,issueData:s}=e,i=[...r,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:t,defaultError:a}).message;return{...s,path:i,message:a}},eRt=[];function Me(e,t){let r=Mb(),n=MR({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===lp?void 0:lp].filter(s=>!!s)});e.common.issues.push(n)}var hi=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let s of r){if(s.status==="aborted")return At;s.status==="dirty"&&t.dirty(),n.push(s.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let s of r){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let s of r){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return At;i.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:t.value,value:n}}},At=Object.freeze({status:"aborted"}),vA=e=>({status:"dirty",value:e}),Mi=e=>({status:"valid",value:e}),fQ=e=>e.status==="aborted",hQ=e=>e.status==="dirty",mh=e=>e.status==="valid",Fb=e=>typeof Promise<"u"&&e instanceof Promise;var nt;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(nt||(nt={}));var hc=class{constructor(t,r,n,s){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},vBe=(e,t)=>{if(mh(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new qo(e.common.issues);return this._error=r,this._error}}};function Ot(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(o,a)=>{let{message:c}=e;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}var $t=class{get description(){return this._def.description}_getType(t){return gu(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:gu(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new hi,ctx:{common:t.parent.common,data:t.data,parsedType:gu(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(Fb(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gu(t)},s=this._parseSync({data:t,path:n.path,parent:n});return vBe(n,s)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gu(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return mh(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>mh(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gu(t)},s=this._parse({data:t,path:n.path,parent:n}),i=await(Fb(s)?s:Promise.resolve(s));return vBe(n,i)}refine(t,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,i)=>{let o=t(s),a=()=>i.addIssue({code:Re.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,s)=>t(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(t){return new mc({schema:this,typeName:Ct.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return fc.create(this,this._def)}nullable(){return yu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pp.create(this)}promise(){return yh.create(this,this._def)}or(t){return _A.create([this,t],this._def)}and(t){return PA.create(this,t,this._def)}transform(t){return new mc({...Ot(this._def),schema:this,typeName:Ct.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new FA({...Ot(this._def),innerType:this,defaultValue:r,typeName:Ct.ZodDefault})}brand(){return new FR({typeName:Ct.ZodBranded,type:this,...Ot(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new LA({...Ot(this._def),innerType:this,catchValue:r,typeName:Ct.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return LR.create(this,t)}readonly(){return UA.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},tRt=/^c[^\s-]{8,}$/i,rRt=/^[0-9a-z]+$/,nRt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sRt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,iRt=/^[a-z0-9_-]{21}$/i,oRt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,aRt=/^[-+]?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)?)??$/,cRt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lRt="^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$",u4,uRt=/^(?:(?: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])$/,dRt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,pRt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,fRt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,hRt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mRt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,RBe="((\\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])))",gRt=new RegExp(`^${RBe}$`);function TBe(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function ARt(e){return new RegExp(`^${TBe(e)}$`)}function kBe(e){let t=`${RBe}T${TBe(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function yRt(e,t){return!!((t==="v4"||!t)&&uRt.test(e)||(t==="v6"||!t)&&pRt.test(e))}function ERt(e,t){if(!oRt.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function wRt(e,t){return!!((t==="v4"||!t)&&dRt.test(e)||(t==="v6"||!t)&&fRt.test(e))}var gh=class e extends $t{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Ve.string){let i=this._getOrReturnCtx(t);return Me(i,{code:Re.invalid_type,expected:Ve.string,received:i.parsedType}),At}let n=new hi,s;for(let i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(s=this._getOrReturnCtx(t,s),Me(s,{code:Re.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")t.data.length>i.value&&(s=this._getOrReturnCtx(t,s),Me(s,{code:Re.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=t.data.length>i.value,a=t.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(t,s),o?Me(s,{code:Re.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&Me(s,{code:Re.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")cRt.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"email",code:Re.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")u4||(u4=new RegExp(lRt,"u")),u4.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"emoji",code:Re.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")sRt.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"uuid",code:Re.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")iRt.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"nanoid",code:Re.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")tRt.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"cuid",code:Re.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")rRt.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"cuid2",code:Re.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")nRt.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"ulid",code:Re.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),Me(s,{validation:"url",code:Re.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"regex",code:Re.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(t,s),Me(s,{code:Re.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(s=this._getOrReturnCtx(t,s),Me(s,{code:Re.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(s=this._getOrReturnCtx(t,s),Me(s,{code:Re.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?kBe(i).test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{code:Re.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?gRt.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{code:Re.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?ARt(i).test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{code:Re.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?aRt.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"duration",code:Re.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?yRt(t.data,i.version)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"ip",code:Re.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?ERt(t.data,i.alg)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"jwt",code:Re.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?wRt(t.data,i.version)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"cidr",code:Re.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?hRt.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"base64",code:Re.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?mRt.test(t.data)||(s=this._getOrReturnCtx(t,s),Me(s,{validation:"base64url",code:Re.invalid_string,message:i.message}),n.dirty()):Yt.assertNever(i);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(s=>t.test(s),{validation:r,code:Re.invalid_string,...nt.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...nt.errToObj(t)})}url(t){return this._addCheck({kind:"url",...nt.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...nt.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...nt.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...nt.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...nt.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...nt.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...nt.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...nt.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...nt.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...nt.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...nt.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...nt.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...nt.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...nt.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...nt.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...nt.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...nt.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...nt.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...nt.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...nt.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...nt.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...nt.errToObj(r)})}nonempty(t){return this.min(1,nt.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};gh.create=e=>new gh({checks:[],typeName:Ct.ZodString,coerce:e?.coerce??!1,...Ot(e)});function bRt(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n,i=Number.parseInt(e.toFixed(s).replace(".","")),o=Number.parseInt(t.toFixed(s).replace(".",""));return i%o/10**s}var IA=class e extends $t{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Ve.number){let i=this._getOrReturnCtx(t);return Me(i,{code:Re.invalid_type,expected:Ve.number,received:i.parsedType}),At}let n,s=new hi;for(let i of this._def.checks)i.kind==="int"?Yt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Me(n,{code:Re.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(n=this._getOrReturnCtx(t,n),Me(n,{code:Re.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),Me(n,{code:Re.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?bRt(t.data,i.value)!==0&&(n=this._getOrReturnCtx(t,n),Me(n,{code:Re.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Me(n,{code:Re.not_finite,message:i.message}),s.dirty()):Yt.assertNever(i);return{status:s.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,nt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,nt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,nt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,nt.toString(r))}setLimit(t,r,n,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:nt.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:nt.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:nt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:nt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:nt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:nt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:nt.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:nt.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:nt.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:nt.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Yt.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};IA.create=e=>new IA({checks:[],typeName:Ct.ZodNumber,coerce:e?.coerce||!1,...Ot(e)});var RA=class e extends $t{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Ve.bigint)return this._getInvalidInput(t);let n,s=new hi;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(n=this._getOrReturnCtx(t,n),Me(n,{code:Re.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),Me(n,{code:Re.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),Me(n,{code:Re.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Yt.assertNever(i);return{status:s.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Me(r,{code:Re.invalid_type,expected:Ve.bigint,received:r.parsedType}),At}gte(t,r){return this.setLimit("min",t,!0,nt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,nt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,nt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,nt.toString(r))}setLimit(t,r,n,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:nt.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:nt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:nt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:nt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:nt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:nt.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};RA.create=e=>new RA({checks:[],typeName:Ct.ZodBigInt,coerce:e?.coerce??!1,...Ot(e)});var TA=class extends $t{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Ve.boolean){let n=this._getOrReturnCtx(t);return Me(n,{code:Re.invalid_type,expected:Ve.boolean,received:n.parsedType}),At}return Mi(t.data)}};TA.create=e=>new TA({typeName:Ct.ZodBoolean,coerce:e?.coerce||!1,...Ot(e)});var kA=class e extends $t{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Ve.date){let i=this._getOrReturnCtx(t);return Me(i,{code:Re.invalid_type,expected:Ve.date,received:i.parsedType}),At}if(Number.isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return Me(i,{code:Re.invalid_date}),At}let n=new hi,s;for(let i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(s=this._getOrReturnCtx(t,s),Me(s,{code:Re.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(s=this._getOrReturnCtx(t,s),Me(s,{code:Re.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):Yt.assertNever(i);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:nt.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:nt.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};kA.create=e=>new kA({checks:[],coerce:e?.coerce||!1,typeName:Ct.ZodDate,...Ot(e)});var Ub=class extends $t{_parse(t){if(this._getType(t)!==Ve.symbol){let n=this._getOrReturnCtx(t);return Me(n,{code:Re.invalid_type,expected:Ve.symbol,received:n.parsedType}),At}return Mi(t.data)}};Ub.create=e=>new Ub({typeName:Ct.ZodSymbol,...Ot(e)});var BA=class extends $t{_parse(t){if(this._getType(t)!==Ve.undefined){let n=this._getOrReturnCtx(t);return Me(n,{code:Re.invalid_type,expected:Ve.undefined,received:n.parsedType}),At}return Mi(t.data)}};BA.create=e=>new BA({typeName:Ct.ZodUndefined,...Ot(e)});var NA=class extends $t{_parse(t){if(this._getType(t)!==Ve.null){let n=this._getOrReturnCtx(t);return Me(n,{code:Re.invalid_type,expected:Ve.null,received:n.parsedType}),At}return Mi(t.data)}};NA.create=e=>new NA({typeName:Ct.ZodNull,...Ot(e)});var Ah=class extends $t{constructor(){super(...arguments),this._any=!0}_parse(t){return Mi(t.data)}};Ah.create=e=>new Ah({typeName:Ct.ZodAny,...Ot(e)});var dp=class extends $t{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Mi(t.data)}};dp.create=e=>new dp({typeName:Ct.ZodUnknown,...Ot(e)});var dl=class extends $t{_parse(t){let r=this._getOrReturnCtx(t);return Me(r,{code:Re.invalid_type,expected:Ve.never,received:r.parsedType}),At}};dl.create=e=>new dl({typeName:Ct.ZodNever,...Ot(e)});var $b=class extends $t{_parse(t){if(this._getType(t)!==Ve.undefined){let n=this._getOrReturnCtx(t);return Me(n,{code:Re.invalid_type,expected:Ve.void,received:n.parsedType}),At}return Mi(t.data)}};$b.create=e=>new $b({typeName:Ct.ZodVoid,...Ot(e)});var pp=class e extends $t{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),s=this._def;if(r.parsedType!==Ve.array)return Me(r,{code:Re.invalid_type,expected:Ve.array,received:r.parsedType}),At;if(s.exactLength!==null){let o=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(o||a)&&(Me(r,{code:o?Re.too_big:Re.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(Me(r,{code:Re.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(Me(r,{code:Re.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>s.type._parseAsync(new hc(r,o,r.path,a)))).then(o=>hi.mergeArray(n,o));let i=[...r.data].map((o,a)=>s.type._parseSync(new hc(r,o,r.path,a)));return hi.mergeArray(n,i)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:nt.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:nt.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:nt.toString(r)}})}nonempty(t){return this.min(1,t)}};pp.create=(e,t)=>new pp({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ct.ZodArray,...Ot(t)});function Lb(e){if(e instanceof Go){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=fc.create(Lb(n))}return new Go({...e._def,shape:()=>t})}else return e instanceof pp?new pp({...e._def,type:Lb(e.element)}):e instanceof fc?fc.create(Lb(e.unwrap())):e instanceof yu?yu.create(Lb(e.unwrap())):e instanceof Au?Au.create(e.items.map(t=>Lb(t))):e}var Go=class e extends $t{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Yt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Ve.object){let l=this._getOrReturnCtx(t);return Me(l,{code:Re.invalid_type,expected:Ve.object,received:l.parsedType}),At}let{status:n,ctx:s}=this._processInputParams(t),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof dl&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let u=i[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new hc(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof dl){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(Me(s,{code:Re.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new hc(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,p=await u.value;l.push({key:d,value:p,alwaysSet:u.alwaysSet})}return l}).then(l=>hi.mergeObjectSync(n,l)):hi.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return nt.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:nt.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ct.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of Yt.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of Yt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return Lb(this)}partial(t){let r={};for(let n of Yt.objectKeys(this.shape)){let s=this.shape[n];t&&!t[n]?r[n]=s:r[n]=s.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of Yt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof fc;)i=i._def.innerType;r[n]=i}return new e({...this._def,shape:()=>r})}keyof(){return BBe(Yt.objectKeys(this.shape))}};Go.create=(e,t)=>new Go({shape:()=>e,unknownKeys:"strip",catchall:dl.create(),typeName:Ct.ZodObject,...Ot(t)});Go.strictCreate=(e,t)=>new Go({shape:()=>e,unknownKeys:"strict",catchall:dl.create(),typeName:Ct.ZodObject,...Ot(t)});Go.lazycreate=(e,t)=>new Go({shape:e,unknownKeys:"strip",catchall:dl.create(),typeName:Ct.ZodObject,...Ot(t)});var _A=class extends $t{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new qo(a.ctx.common.issues));return Me(r,{code:Re.invalid_union,unionErrors:o}),At}if(r.common.async)return Promise.all(n.map(async i=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new qo(c));return Me(r,{code:Re.invalid_union,unionErrors:a}),At}}get options(){return this._def.options}};_A.create=(e,t)=>new _A({options:e,typeName:Ct.ZodUnion,...Ot(t)});var up=e=>e instanceof DA?up(e.schema):e instanceof mc?up(e.innerType()):e instanceof OA?[e.value]:e instanceof QA?e.options:e instanceof MA?Yt.objectValues(e.enum):e instanceof FA?up(e._def.innerType):e instanceof BA?[void 0]:e instanceof NA?[null]:e instanceof fc?[void 0,...up(e.unwrap())]:e instanceof yu?[null,...up(e.unwrap())]:e instanceof FR||e instanceof UA?up(e.unwrap()):e instanceof LA?up(e._def.innerType):[],mQ=class e extends $t{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ve.object)return Me(r,{code:Re.invalid_type,expected:Ve.object,received:r.parsedType}),At;let n=this.discriminator,s=r.data[n],i=this.optionsMap.get(s);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(Me(r,{code:Re.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),At)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let s=new Map;for(let i of r){let o=up(i.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,i)}}return new e({typeName:Ct.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:s,...Ot(n)})}};function d4(e,t){let r=gu(e),n=gu(t);if(e===t)return{valid:!0,data:e};if(r===Ve.object&&n===Ve.object){let s=Yt.objectKeys(t),i=Yt.objectKeys(e).filter(a=>s.indexOf(a)!==-1),o={...e,...t};Object.prototype.hasOwnProperty.call(o,"__proto__")&&delete o.__proto__;for(let a of i){if(a==="__proto__")continue;let c=d4(e[a],t[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===Ve.array&&n===Ve.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let i=0;i<e.length;i++){let o=e[i],a=t[i],c=d4(o,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===Ve.date&&n===Ve.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var PA=class extends $t{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),s=(i,o)=>{if(fQ(i)||fQ(o))return At;let a=d4(i.value,o.value);return a.valid?((hQ(i)||hQ(o))&&r.dirty(),{status:r.value,value:a.data}):(Me(n,{code:Re.invalid_intersection_types}),At)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};PA.create=(e,t,r)=>new PA({left:e,right:t,typeName:Ct.ZodIntersection,...Ot(r)});var Au=class e extends $t{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ve.array)return Me(n,{code:Re.invalid_type,expected:Ve.array,received:n.parsedType}),At;if(n.data.length<this._def.items.length)return Me(n,{code:Re.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),At;!this._def.rest&&n.data.length>this._def.items.length&&(Me(n,{code:Re.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new hc(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>hi.mergeArray(r,o)):hi.mergeArray(r,i)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Au.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Au({items:e,typeName:Ct.ZodTuple,rest:null,...Ot(t)})};var gQ=class e extends $t{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ve.object)return Me(n,{code:Re.invalid_type,expected:Ve.object,received:n.parsedType}),At;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new hc(n,a,n.path,a)),value:o._parse(new hc(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?hi.mergeObjectAsync(r,s):hi.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof $t?new e({keyType:t,valueType:r,typeName:Ct.ZodRecord,...Ot(n)}):new e({keyType:gh.create(),valueType:t,typeName:Ct.ZodRecord,...Ot(r)})}},qb=class extends $t{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ve.map)return Me(n,{code:Re.invalid_type,expected:Ve.map,received:n.parsedType}),At;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],l)=>({key:s._parse(new hc(n,a,n.path,[l,"key"])),value:i._parse(new hc(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return At;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return At;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};qb.create=(e,t,r)=>new qb({valueType:t,keyType:e,typeName:Ct.ZodMap,...Ot(r)});var Gb=class e extends $t{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ve.set)return Me(n,{code:Re.invalid_type,expected:Ve.set,received:n.parsedType}),At;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(Me(n,{code:Re.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(Me(n,{code:Re.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let i=this._def.valueType;function o(c){let l=new Set;for(let u of c){if(u.status==="aborted")return At;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>i._parse(new hc(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:nt.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:nt.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Gb.create=(e,t)=>new Gb({valueType:e,minSize:null,maxSize:null,typeName:Ct.ZodSet,...Ot(t)});var AQ=class e extends $t{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ve.function)return Me(r,{code:Re.invalid_type,expected:Ve.function,received:r.parsedType}),At;function n(a,c){return MR({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Mb(),lp].filter(l=>!!l),issueData:{code:Re.invalid_arguments,argumentsError:c}})}function s(a,c){return MR({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Mb(),lp].filter(l=>!!l),issueData:{code:Re.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof yh){let a=this;return Mi(async function(...c){let l=new qo([]),u=await a._def.args.parseAsync(c,i).catch(h=>{throw l.addIssue(n(c,h)),l}),d=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(h=>{throw l.addIssue(s(d,h)),l})})}else{let a=this;return Mi(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new qo([n(c,l.error)]);let u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new qo([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Au.create(t).rest(dp.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||Au.create([]).rest(dp.create()),returns:r||dp.create(),typeName:Ct.ZodFunction,...Ot(n)})}},DA=class extends $t{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};DA.create=(e,t)=>new DA({getter:e,typeName:Ct.ZodLazy,...Ot(t)});var OA=class extends $t{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Me(r,{received:r.data,code:Re.invalid_literal,expected:this._def.value}),At}return{status:"valid",value:t.data}}get value(){return this._def.value}};OA.create=(e,t)=>new OA({value:e,typeName:Ct.ZodLiteral,...Ot(t)});function BBe(e,t){return new QA({values:e,typeName:Ct.ZodEnum,...Ot(t)})}var QA=class e extends $t{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Me(r,{expected:Yt.joinValues(n),received:r.parsedType,code:Re.invalid_type}),At}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return Me(r,{received:r.data,code:Re.invalid_enum_value,options:n}),At}return Mi(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};QA.create=BBe;var MA=class extends $t{_parse(t){let r=Yt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Ve.string&&n.parsedType!==Ve.number){let s=Yt.objectValues(r);return Me(n,{expected:Yt.joinValues(s),received:n.parsedType,code:Re.invalid_type}),At}if(this._cache||(this._cache=new Set(Yt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=Yt.objectValues(r);return Me(n,{received:n.data,code:Re.invalid_enum_value,options:s}),At}return Mi(t.data)}get enum(){return this._def.values}};MA.create=(e,t)=>new MA({values:e,typeName:Ct.ZodNativeEnum,...Ot(t)});var yh=class extends $t{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ve.promise&&r.common.async===!1)return Me(r,{code:Re.invalid_type,expected:Ve.promise,received:r.parsedType}),At;let n=r.parsedType===Ve.promise?r.data:Promise.resolve(r.data);return Mi(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};yh.create=(e,t)=>new yh({type:e,typeName:Ct.ZodPromise,...Ot(t)});var mc=class extends $t{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ct.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),s=this._def.effect||null,i={addIssue:o=>{Me(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return At;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?At:c.status==="dirty"?vA(c.value):r.value==="dirty"?vA(c.value):c});{if(r.value==="aborted")return At;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?At:a.status==="dirty"?vA(a.value):r.value==="dirty"?vA(a.value):a}}if(s.type==="refinement"){let o=a=>{let c=s.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?At:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?At:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!mh(o))return At;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>mh(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:r.value,value:a})):At);Yt.assertNever(s)}};mc.create=(e,t,r)=>new mc({schema:e,typeName:Ct.ZodEffects,effect:t,...Ot(r)});mc.createWithPreprocess=(e,t,r)=>new mc({schema:t,effect:{type:"preprocess",transform:e},typeName:Ct.ZodEffects,...Ot(r)});var fc=class extends $t{_parse(t){return this._getType(t)===Ve.undefined?Mi(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};fc.create=(e,t)=>new fc({innerType:e,typeName:Ct.ZodOptional,...Ot(t)});var yu=class extends $t{_parse(t){return this._getType(t)===Ve.null?Mi(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};yu.create=(e,t)=>new yu({innerType:e,typeName:Ct.ZodNullable,...Ot(t)});var FA=class extends $t{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Ve.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};FA.create=(e,t)=>new FA({innerType:e,typeName:Ct.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ot(t)});var LA=class extends $t{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Fb(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new qo(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new qo(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};LA.create=(e,t)=>new LA({innerType:e,typeName:Ct.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ot(t)});var jb=class extends $t{_parse(t){if(this._getType(t)!==Ve.nan){let n=this._getOrReturnCtx(t);return Me(n,{code:Re.invalid_type,expected:Ve.nan,received:n.parsedType}),At}return{status:"valid",value:t.data}}};jb.create=e=>new jb({typeName:Ct.ZodNaN,...Ot(e)});var SRt=Symbol("zod_brand"),FR=class extends $t{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},LR=class e extends $t{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?At:i.status==="dirty"?(r.dirty(),vA(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?At:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:Ct.ZodPipeline})}},UA=class extends $t{_parse(t){let r=this._def.innerType._parse(t),n=s=>(mh(s)&&(s.value=Object.freeze(s.value)),s);return Fb(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};UA.create=(e,t)=>new UA({innerType:e,typeName:Ct.ZodReadonly,...Ot(t)});function IBe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function NBe(e,t={},r){return e?Ah.create().superRefine((n,s)=>{let i=e(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=IBe(t,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=IBe(t,n),a=o.fatal??r??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Ah.create()}var CRt={object:Go.lazycreate},Ct;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Ct||(Ct={}));var xRt=(e,t={message:`Input not instance of ${e.name}`})=>NBe(r=>r instanceof e,t),_Be=gh.create,PBe=IA.create,vRt=jb.create,IRt=RA.create,DBe=TA.create,RRt=kA.create,TRt=Ub.create,kRt=BA.create,BRt=NA.create,NRt=Ah.create,_Rt=dp.create,PRt=dl.create,DRt=$b.create,ORt=pp.create,QRt=Go.create,MRt=Go.strictCreate,FRt=_A.create,LRt=mQ.create,URt=PA.create,$Rt=Au.create,qRt=gQ.create,GRt=qb.create,jRt=Gb.create,HRt=AQ.create,zRt=DA.create,VRt=OA.create,WRt=QA.create,JRt=MA.create,YRt=yh.create,KRt=mc.create,XRt=fc.create,ZRt=yu.create,e0t=mc.createWithPreprocess,t0t=LR.create,r0t=()=>_Be().optional(),n0t=()=>PBe().optional(),s0t=()=>DBe().optional(),i0t={string:(e=>gh.create({...e,coerce:!0})),number:(e=>IA.create({...e,coerce:!0})),boolean:(e=>TA.create({...e,coerce:!0})),bigint:(e=>RA.create({...e,coerce:!0})),date:(e=>kA.create({...e,coerce:!0}))};var o0t=At;function Eu(e,t=0,r=new Set){return UR(e,t,r)}var OBe=e=>" ".repeat(e);function UR(e,t,r){let n=a0t(e);switch(n._def.typeName){case"ZodObject":{let i=n.shape,o=Object.keys(i).filter(c=>!r.has(c)&&!i[c].description?.startsWith("[derived]"));return o.length===0?"{}":`{
|
|
240
240
|
${o.map((c,l)=>{let u=i[c],d=u.isOptional()?" (optional)":"",p=u.description?` // ${u.description}`:"",h=UR(u,t+2,r);return`${OBe(t+2)}"${c}": ${h}${l<o.length-1?",":""}${d}${p}`}).join(`
|
|
241
241
|
`)}
|
|
242
|
-
${OBe(t)}}`}case"ZodArray":{let i=n.element;return`[ ${UR(i,t,r)}, \u2026 ]`}case"ZodEnum":return n.options.map(i=>JSON.stringify(i)).join(" | ");case"ZodNativeEnum":return Object.values(n.enum).map(i=>JSON.stringify(i)).join(" | ");case"ZodLiteral":return JSON.stringify(n.value);case"ZodString":return'"\u2026"';case"ZodNumber":return"<number>";case"ZodBoolean":return"true | false";case"ZodNull":return"null";case"ZodUnion":return n.options.map(i=>UR(i,t,r)).join(" | ");case"ZodRecord":return`{ "<key>": ${UR(n.valueSchema,t,r)} }`;default:return"<value>"}}function a0t(e){let t=e;for(;;){let r=t._def;if(r.typeName==="ZodOptional"||r.typeName==="ZodNullable"||r.typeName==="ZodDefault"){if(r.typeName==="ZodNullable")return E.union([r.innerType,E.null()]);t=r.innerType}else if(r.typeName==="ZodEffects")t=r.schema;else return t}}function c0t(e){return e.issues.map(t=>{let r=t.path.map(s=>typeof s=="number"?`[${s}]`:`.${s}`).join("").replace(/^\./,""),n=r||"output";if(!/^(Expected |Required$|Invalid |String must|Array must|Number must)/.test(t.message))return`${n} ${t.message}`;switch(t.code){case"invalid_type":return r?t.expected==="object"?`${n} must be an object`:t.received==="undefined"?`${n} is required`:`${n} must be ${t.expected}, got ${t.received}`:"output is not a JSON object";case"invalid_enum_value":{let s=JSON.stringify(t.received),i=t.options.find(a=>typeof a=="string"&&typeof t.received=="string"&&t.received.startsWith(a)),o=i?` \u2014 you sent ${s}; the value must be exactly ${JSON.stringify(i)}, with any qualifier moved to a field that takes free text`:` \u2014 you sent ${s}`;return`${n} must be one of: ${t.options.join(", ")}${o}`}case"invalid_literal":return`${n} must be ${JSON.stringify(t.expected)}`;case"too_small":return t.type==="string"?`${n} must be a non-empty string`:`${n} must have at least ${t.minimum} item(s)`;case"unrecognized_keys":return`${n} has unknown key(s): ${t.keys.join(", ")}`;default:return`${n}: ${t.message}`}})}function Zn(e,t){let r=e.safeParse(t);if(r.success)return{value:r.data,errors:[]};let n=(i,o)=>o.reduce((a,c)=>a&&typeof a=="object"?a[c]:void 0,i),s=r.error.issues.filter(i=>i.path.length&&n(t,i.path)===null);if(s.length===r.error.issues.length)try{let i=e.safeParse(s.reduce((o,{path:a})=>QBe(o,a),t));if(i.success)return{value:i.data,errors:[]}}catch{}return{errors:c0t(r.error)}}function QBe(e,t){if(!t.length||!e||typeof e!="object")return e;let[r,...n]=t,s=Array.isArray(e)?e.slice():{...e};return n.length?s[r]=QBe(s[r],n):delete s[r],s}function $R(e,t,r){let n=Zn(e,r),s=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,i=[...n.errors,...s?t(s):[]];return i.length?{errors:i}:{value:n.value,errors:[]}}var MBe=Y(require("path"));var p4="outputs/preflight.json",fp="pr-diff.txt";function pl(e,t){return[...e.changedFiles.map(r=>({repository:t,path:r.path})),...(e.relatedChanges??[]).flatMap(r=>r.changedFiles.map(n=>({repository:r.repository,path:n.path})))]}function qR(e,t,r){return e.some(n=>n.path===r&&n.repository.toLowerCase()===t.toLowerCase())}function Xr(e){if(e.outputsDir)return hu(MBe.join(e.outputsDir,"preflight.json"))}var SQ=Y(require("fs")),Hr=Y(require("path"));var LBe=require("child_process"),EQ=Y(require("fs")),Hb=Y(require("path"));var wQ="ci-evidence.json",yQ=(e,t)=>(0,LBe.execFileSync)("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim(),l0t=/^Merge ([0-9a-f]{40}) into [0-9a-f]{40}$/;function u0t(e){try{let t=yQ(e,["rev-parse","HEAD"]);if(yQ(e,["rev-list","--parents","-n","1","HEAD"]).split(/\s+/).slice(1).length===2){let n=l0t.exec(yQ(e,["log","-1","--format=%s","HEAD"]));if(n)return n[1]}return t}catch{return}}function bQ(e){let t="";try{t=yQ(e,["remote","get-url","origin"])}catch{}let r=/[:/]([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec(t);return r&&!t.startsWith("/")&&!t.startsWith(".")?`${r[1]}/${r[2]}`:`local/${Hb.basename(Hb.resolve(e)).replace(/[^A-Za-z0-9._-]/g,"-")||"repo"}`}var d0t=new Set(Object.values(hh));function p0t(e){let t=[];for(let r of e??[]){let n=r.trim();if(!n)continue;let s=n.lastIndexOf("="),i=s>0?n.slice(s+1).trim():"",o=d0t.has(i),c=(o?n.slice(0,s).trim():n).split("*").map(l=>l.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");t.push({pattern:new RegExp(`^${c}$`,"i"),kind:o?i:"ci_check"})}return t}var f0t=new Set(["failure","timed_out","action_required","error","startup_failure"]);function FBe(e,t){let r=new Map(t.revisions.map(s=>[s.repository.toLowerCase(),s])),n=[];for(let s of e){if(s.name.startsWith(pi))continue;let i=r.get((s.repository??t.primary).toLowerCase());if(!i)continue;let o=t.trusted.find(l=>l.pattern.test(s.name)),a=s.conclusion??s.status,c=o?s.headSha.toLowerCase()!==i.revision.toLowerCase()?"stale":s.status!=="completed"?"pending":s.conclusion==="success"?"accepted":f0t.has(s.conclusion??"")?"failing":"inconclusive":"untrusted";n.push({id:`ci-${n.length+1}`,repository:i.repository,revision:i.revision,checkSha:s.headSha,name:s.name,kind:o?.kind??"ci_check",status:c,conclusion:a,reference:s.url||`${i.repository}@${s.headSha.slice(0,12)} ${s.name}`,summary:(s.summary||`${s.name}: ${a}`).slice(0,300)})}return n}var h0t=E.object({checks:E.array(E.object({repository:E.string().optional(),name:E.string().min(1),headSha:E.string().regex(/^[0-9a-f]{40}$|^[0-9a-f]{64}$/i),status:E.string().default("completed"),conclusion:E.string().nullable().optional(),url:E.string().optional(),summary:E.string().optional()}))});function m0t(e){let t=h0t.safeParse(JSON.parse(EQ.readFileSync(e,"utf-8")));if(!t.success)throw new Error(`${e} is not a CI evidence file: ${t.error.issues[0]?.message??"invalid"}`);return t.data.checks}function g0t(e){let t=[{path:e.inputs.repositoryPath,slug:e.inputs.repositorySlug},...(e.inputs.relatedRepos??[]).map(n=>({path:n.path,slug:n.slug}))],r=[];for(let n of t){let s=u0t(n.path);s&&r.push({repository:n.slug??bQ(n.path),revision:s})}return r}async function UBe(e){let t=g0t(e),r=t[0]?.repository??bQ(e.inputs.repositoryPath),n=p0t(e.inputs.trustedChecks),s;try{if(e.inputs.ciEvidenceFile){let i=m0t(e.inputs.ciEvidenceFile);s={source:"file",revisions:t,items:FBe(i,{revisions:t,primary:r,trusted:n})}}else if(e.platform?.listCommitChecks){let i=[],o=[],a=[];for(let l of t){let u=`${l.repository}@${l.revision.slice(0,12)}`,d=await e.platform.listCommitChecks(l);d?i.push(...d.records):o.push(u);for(let p of d?.
|
|
242
|
+
${OBe(t)}}`}case"ZodArray":{let i=n.element;return`[ ${UR(i,t,r)}, \u2026 ]`}case"ZodEnum":return n.options.map(i=>JSON.stringify(i)).join(" | ");case"ZodNativeEnum":return Object.values(n.enum).map(i=>JSON.stringify(i)).join(" | ");case"ZodLiteral":return JSON.stringify(n.value);case"ZodString":return'"\u2026"';case"ZodNumber":return"<number>";case"ZodBoolean":return"true | false";case"ZodNull":return"null";case"ZodUnion":return n.options.map(i=>UR(i,t,r)).join(" | ");case"ZodRecord":return`{ "<key>": ${UR(n.valueSchema,t,r)} }`;default:return"<value>"}}function a0t(e){let t=e;for(;;){let r=t._def;if(r.typeName==="ZodOptional"||r.typeName==="ZodNullable"||r.typeName==="ZodDefault"){if(r.typeName==="ZodNullable")return E.union([r.innerType,E.null()]);t=r.innerType}else if(r.typeName==="ZodEffects")t=r.schema;else return t}}function c0t(e){return e.issues.map(t=>{let r=t.path.map(s=>typeof s=="number"?`[${s}]`:`.${s}`).join("").replace(/^\./,""),n=r||"output";if(!/^(Expected |Required$|Invalid |String must|Array must|Number must)/.test(t.message))return`${n} ${t.message}`;switch(t.code){case"invalid_type":return r?t.expected==="object"?`${n} must be an object`:t.received==="undefined"?`${n} is required`:`${n} must be ${t.expected}, got ${t.received}`:"output is not a JSON object";case"invalid_enum_value":{let s=JSON.stringify(t.received),i=t.options.find(a=>typeof a=="string"&&typeof t.received=="string"&&t.received.startsWith(a)),o=i?` \u2014 you sent ${s}; the value must be exactly ${JSON.stringify(i)}, with any qualifier moved to a field that takes free text`:` \u2014 you sent ${s}`;return`${n} must be one of: ${t.options.join(", ")}${o}`}case"invalid_literal":return`${n} must be ${JSON.stringify(t.expected)}`;case"too_small":return t.type==="string"?`${n} must be a non-empty string`:`${n} must have at least ${t.minimum} item(s)`;case"unrecognized_keys":return`${n} has unknown key(s): ${t.keys.join(", ")}`;default:return`${n}: ${t.message}`}})}function Zn(e,t){let r=e.safeParse(t);if(r.success)return{value:r.data,errors:[]};let n=(i,o)=>o.reduce((a,c)=>a&&typeof a=="object"?a[c]:void 0,i),s=r.error.issues.filter(i=>i.path.length&&n(t,i.path)===null);if(s.length===r.error.issues.length)try{let i=e.safeParse(s.reduce((o,{path:a})=>QBe(o,a),t));if(i.success)return{value:i.data,errors:[]}}catch{}return{errors:c0t(r.error)}}function QBe(e,t){if(!t.length||!e||typeof e!="object")return e;let[r,...n]=t,s=Array.isArray(e)?e.slice():{...e};return n.length?s[r]=QBe(s[r],n):delete s[r],s}function $R(e,t,r){let n=Zn(e,r),s=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,i=[...n.errors,...s?t(s):[]];return i.length?{errors:i}:{value:n.value,errors:[]}}var MBe=Y(require("path"));var p4="outputs/preflight.json",fp="pr-diff.txt";function pl(e,t){return[...e.changedFiles.map(r=>({repository:t,path:r.path})),...(e.relatedChanges??[]).flatMap(r=>r.changedFiles.map(n=>({repository:r.repository,path:n.path})))]}function qR(e,t,r){return e.some(n=>n.path===r&&n.repository.toLowerCase()===t.toLowerCase())}function Xr(e){if(e.outputsDir)return hu(MBe.join(e.outputsDir,"preflight.json"))}var SQ=Y(require("fs")),Hr=Y(require("path"));var LBe=require("child_process"),EQ=Y(require("fs")),Hb=Y(require("path"));var wQ="ci-evidence.json",yQ=(e,t)=>(0,LBe.execFileSync)("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim(),l0t=/^Merge ([0-9a-f]{40}) into [0-9a-f]{40}$/;function u0t(e){try{let t=yQ(e,["rev-parse","HEAD"]);if(yQ(e,["rev-list","--parents","-n","1","HEAD"]).split(/\s+/).slice(1).length===2){let n=l0t.exec(yQ(e,["log","-1","--format=%s","HEAD"]));if(n)return n[1]}return t}catch{return}}function bQ(e){let t="";try{t=yQ(e,["remote","get-url","origin"])}catch{}let r=/[:/]([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec(t);return r&&!t.startsWith("/")&&!t.startsWith(".")?`${r[1]}/${r[2]}`:`local/${Hb.basename(Hb.resolve(e)).replace(/[^A-Za-z0-9._-]/g,"-")||"repo"}`}var d0t=new Set(Object.values(hh));function p0t(e){let t=[];for(let r of e??[]){let n=r.trim();if(!n)continue;let s=n.lastIndexOf("="),i=s>0?n.slice(s+1).trim():"",o=d0t.has(i),c=(o?n.slice(0,s).trim():n).split("*").map(l=>l.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");t.push({pattern:new RegExp(`^${c}$`,"i"),kind:o?i:"ci_check"})}return t}var f0t=new Set(["failure","timed_out","action_required","error","startup_failure"]);function FBe(e,t){let r=new Map(t.revisions.map(s=>[s.repository.toLowerCase(),s])),n=[];for(let s of e){if(s.name.startsWith(pi))continue;let i=r.get((s.repository??t.primary).toLowerCase());if(!i)continue;let o=t.trusted.find(l=>l.pattern.test(s.name)),a=s.conclusion??s.status,c=o?s.headSha.toLowerCase()!==i.revision.toLowerCase()?"stale":s.status!=="completed"?"pending":s.conclusion==="success"?"accepted":f0t.has(s.conclusion??"")?"failing":"inconclusive":"untrusted";n.push({id:`ci-${n.length+1}`,repository:i.repository,revision:i.revision,checkSha:s.headSha,name:s.name,kind:o?.kind??"ci_check",status:c,conclusion:a,reference:s.url||`${i.repository}@${s.headSha.slice(0,12)} ${s.name}`,summary:(s.summary||`${s.name}: ${a}`).slice(0,300)})}return n}var h0t=E.object({checks:E.array(E.object({repository:E.string().optional(),name:E.string().min(1),headSha:E.string().regex(/^[0-9a-f]{40}$|^[0-9a-f]{64}$/i),status:E.string().default("completed"),conclusion:E.string().nullable().optional(),url:E.string().optional(),summary:E.string().optional()}))});function m0t(e){let t=h0t.safeParse(JSON.parse(EQ.readFileSync(e,"utf-8")));if(!t.success)throw new Error(`${e} is not a CI evidence file: ${t.error.issues[0]?.message??"invalid"}`);return t.data.checks}function g0t(e){let t=[{path:e.inputs.repositoryPath,slug:e.inputs.repositorySlug},...(e.inputs.relatedRepos??[]).map(n=>({path:n.path,slug:n.slug}))],r=[];for(let n of t){let s=u0t(n.path);s&&r.push({repository:n.slug??bQ(n.path),revision:s})}return r}async function UBe(e){let t=g0t(e),r=t[0]?.repository??bQ(e.inputs.repositoryPath),n=p0t(e.inputs.trustedChecks),s;try{if(e.inputs.ciEvidenceFile){let i=m0t(e.inputs.ciEvidenceFile);s={source:"file",revisions:t,items:FBe(i,{revisions:t,primary:r,trusted:n})}}else if(e.platform?.listCommitChecks){let i=[],o=[],a=[];for(let l of t){let u=`${l.repository}@${l.revision.slice(0,12)}`,d=await e.platform.listCommitChecks(l);d?i.push(...d.records):o.push(u);for(let p of d?.unreadSources??[])a.push(`${p} could not be read for ${u}`)}let c=[...o.length?[`CI results could not be read for ${o.join(", ")}`]:[],...a];s={source:"platform",revisions:t,items:FBe(i,{revisions:t,primary:r,trusted:n}),...c.length?{note:c.join("; ")}:{}}}else s={source:"none",revisions:t,items:[],note:"this platform keeps no CI results"}}catch(i){s={source:"none",revisions:t,items:[],note:`CI results could not be read: ${i instanceof Error?i.message:String(i)}`}}return s.items.length>0&&n.length===0&&(s.note=[s.note,"no trustedChecks were configured, so no CI result counts as evidence"].filter(Boolean).join("; ")),EQ.writeFileSync(Hb.join(e.outputsDir,wQ),JSON.stringify(s,null,2)+`
|
|
243
243
|
`),s}var hp=8e3,f4=new Map;function qBe(e){return e.repositorySlug?e.repositorySlug:(f4.has(e.repositoryPath)||f4.set(e.repositoryPath,bQ(e.repositoryPath)),f4.get(e.repositoryPath))}function Qt(e){return[{slug:qBe(e),path:e.repositoryPath,writable:!0,working:!0},...(e.relatedRepos??[]).map(t=>({slug:t.slug,path:t.path,writable:t.writable===!0,working:!1}))]}function jo(e){return Qt(e)[0]}function CQ(e,t){return[...Qt(e)].sort((r,n)=>n.path.length-r.path.length).find(r=>{let n=Hr.relative(r.path,t);return!n.startsWith("..")&&!Hr.isAbsolute(n)})}var GR=(e,t)=>e.toLowerCase()===t.toLowerCase();function wu(e,t){return`${e?.trim().toLowerCase()??""}\0${Hr.posix.normalize(t.trim().replace(/^\.\//,""))}`}function Vb(e,t){return t?.trim()?e.find(r=>GR(r.slug,t.trim())):e[0]}function $Be(e,t){return t?e.find(r=>GR(r.slug,t)):void 0}function an(e,t){return Vb(Qt(e),t)}var GBe=(e,t)=>`${t} is not a repository of this run (${Qt(e).map(r=>r.slug).join(", ")})`;function Wb(e,t){let r=an(e,t);if(!r)throw new Error(GBe(e,t));return r.path}function Eh(e,t){let r=an(e,t);return r?r.writable?{source:r}:{error:`${r.slug} is read-only in this run: tests are written only to ${Qt(e).filter(n=>n.writable).map(n=>n.slug).join(", ")}`}:{error:GBe(e,t)}}function or(e,t){return h4(Qt(e),t)}var zb=e=>Hr.basename(Hr.resolve(e.path));function wh(e,t,r){let n=e.relatedRepos??[],s=c=>n.filter(l=>zb(l)===c).length;if(!t||!$Be(n,t)&&GR(t,qBe(e)))return s(r.split("/")[0])?Hr.join(Hr.resolve(e.repositoryPath),r):r;let o=$Be(n,t);if(!o)return r;let a=zb(o);return s(a)>1||SQ.existsSync(Hr.join(e.repositoryPath,a))?Hr.join(Hr.resolve(o.path),r):`${a}/${r}`}function h4(e,t){return e.length<2?"":`${Vb(e,t)?.slug??t}: `}function $A(e,t,r){let n=e.testPlacements?.find(s=>s.testType===r&&GR(s.repository,t));return n&&(n.directory.trim().replace(/\/+$/,"")||".")}function jBe(e){return(e.relatedRepos??[]).map(t=>t.path)}function HBe(e){let t=Qt(e);if(t.length<2)return[];let r=n=>n.working?"your working directory; writable":n.writable?"writable":"read-only: read it, never write a test there";return["",`This run has ${t.length} checkouts, and none is primary. Every test, maintained test and result lives in exactly one of`,'them: name it by "repository" (owner/repo), with its path relative to that checkout. Place a test in the',"checkout whose test tree it belongs to, which need not be the checkout the change is in.",...t.map(n=>` - ${n.slug}: ${n.path} (${r(n)})`)]}function Jb(e){return e.pullRequest?`the description of ${e.pullRequest}`:e.repository?`the description of the related PR in ${e.repository}`:"the PR description"}function Yb(e){let t=(e.pullRequests??[]).flatMap(n=>n.body?.trim()?[{pullRequest:`${n.repository}#${n.number}`,body:n.body}]:[]),r=e.prDescription;return r?.trim()&&!t.some(n=>n.body.trim()===r.trim())?[{body:r},...t]:t}function bh(e){return[...Yb(e),...(e.relatedRepos??[]).map(t=>({repository:t.slug,body:t.prDescription??""}))]}var m4=e=>e?`(the first ${hp.toLocaleString("en-US")} characters; the whole description is in ${e}: read it)`:`(cut at ${hp.toLocaleString("en-US")} characters)`;function qA(e,t=new Map){let r={label:"PR",title:e.prTitle,body:e.prDescription?.trim(),cut:!1,note:void 0},n=e.pullRequests?.length?[...e.pullRequests.map(a=>({label:`${a.repository}#${a.number}`,title:a.title,body:a.body?.trim().slice(0,hp),cut:(a.body?.trim().length??0)>hp,note:a.note})),...Yb(e).some(a=>!a.pullRequest)?[r]:[]]:r.title||r.body?[r]:[];if(n.length===0)return["","No pull request describes this change."];let s=`This change is ${n.length} pull requests. Read every description: each states part of what the change must do.`;return["",...e.pullRequests?.length||!e.relatedRepos?.length?[n.length>1?s:"This change is 1 pull request. Read its description: it states what the change must do."]:[],...n.flatMap(a=>[`--- ${[a.label,a.title].filter(Boolean).join(": ")} ---`,a.note?`(${a.note})`:a.body||"(no description)",...a.cut?[m4(t.get(a.label))]:[]])]}function jR(e,t){let r=e.relatedRepos??[];if(Hr.isAbsolute(t)){let a=r.find(c=>t.startsWith(Hr.resolve(c.path)+Hr.sep));return a?{file:Hr.relative(Hr.resolve(a.path),t),repository:a.slug}:{file:Hr.relative(Hr.resolve(e.repositoryPath),t)}}let n=t.replace(/^\.\//,"");if(SQ.existsSync(Hr.resolve(e.repositoryPath,n)))return{file:n};let s=n.split("/")[0],i=n.slice(s.length+1),o=r.find(a=>Hr.basename(Hr.resolve(a.path))===s&&SQ.existsSync(Hr.join(a.path,i)));return o?{file:i,repository:o.slug}:{file:n}}var xQ=Y(require("fs")),zBe=Y(require("path"));function A0t(e){let t=new Map,r,n;for(let s of e.split(`
|
|
244
244
|
`)){let i=/^diff --git a\/.+ b\/(.+)$/.exec(s);if(i){r=i[1],n=void 0,t.has(r)||t.set(r,[]);continue}let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(s);if(o){n=Number(o[1]);continue}!r||n===void 0||(s.startsWith("+")?t.get(r).push([n,n++]):s.startsWith("-")?t.get(r).push([n,n]):s.startsWith(" ")&&n++)}return t}function VBe(e){let t=zBe.join(e.runDir,fp);if(xQ.existsSync(t))return A0t(xQ.readFileSync(t,"utf-8"))}function y0t(e){let t=/([\w./@+-]+\.[\w]+)(?::(\d+)(?:-(\d+))?)?/.exec(e);if(!t)return{};let r=t[1].replace(/^\.\//,"");if(!t[2])return{file:r};let n=Number(t[2]);return{file:r,lines:[n,t[3]?Number(t[3]):n]}}function WBe(e,t){if(!t)return!0;let{file:r,lines:n}=y0t(e);if(!r)return!0;let s=t.get(r)??[...t].find(([i])=>i.endsWith(`/${r}`)||r.endsWith(`/${i}`))?.[1];return s?n?s.some(([i,o])=>n[0]<=o&&n[1]>=i):!0:!1}var Fi=["-c","core.fsmonitor=false"],E0t=new Set(["GH_TOKEN","GITHUB_TOKEN","GH_ENTERPRISE_TOKEN","GITHUB_ENTERPRISE_TOKEN","ACTIONS_RUNTIME_TOKEN","ACTIONS_ID_TOKEN_REQUEST_TOKEN","ACTIONS_ID_TOKEN_REQUEST_URL","SYSTEM_ACCESSTOKEN","SYSTEM_OIDCREQUESTURI","SKYRAMP_MCP_GITHUB_TOKEN","SSH_AUTH_SOCK","GIT_SSH","GIT_SSH_COMMAND","GITHUB_STEP_SUMMARY"]),vQ=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_BEARER_TOKEN_BEDROCK","AWS_PROFILE","AWS_WEB_IDENTITY_TOKEN_FILE","AWS_ROLE_ARN","AWS_ROLE_SESSION_NAME","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"]);function JBe(e){return e?[...vQ].filter(t=>t.startsWith("AWS_")):["ANTHROPIC_API_KEY"]}function Bt(e=process.env,t,r="repo-command"){let n={};for(let[s,i]of Object.entries(e))r==="repo-command"&&vQ.has(s)||(n[s]=i);Object.assign(n,t??{});for(let s of Object.keys(n))(E0t.has(s)||s.startsWith("INPUT_"))&&delete n[s];return n}var a8=require("child_process"),Ph=Y(require("path"));var IQ=Y(require("fs")),KBe=Y(require("path")),w0t=/[;|`$<>(){}\n\r]|(?<!&)&(?!&)|\|\|/,b0t=/`|\$[\w{(@*#?!$-]|\\[$`"\\\n]/;function S0t(e){let t="";for(let n=0;n<e.length;){let s=e[n];if(s==="\\"&&(e[n+1]==='"'||e[n+1]==="'"))return{syntax:"a backslash before a quote",quoted:!1};if(s!=='"'&&s!=="'"){t+=s,n++;continue}let i=e.indexOf(s,n+1);if(i<0)return;let o=s==='"'?b0t.exec(e.slice(n+1,i+(e[i-1]==="\\"?1:0))):null;if(o)return{syntax:`${YBe(o[0])} inside double quotes`,quoted:!0};t+=" ",n=i+1}let r=w0t.exec(t);return r?{syntax:YBe(r[0]),quoted:!1}:void 0}var YBe=e=>e==="`"?"a backtick":/[\n\r]/.test(e)?"a line break":`\`${e}\``;function gc(e){let t=(e??"").trim();if(!t)return{kind:"empty",reason:"the command is empty"};let r=S0t(t);if(r)return{kind:"shell-syntax",reason:`it uses shell syntax (${r.syntax}), and this is re-executed WITHOUT a shell so the recorded string cannot be interpreted \u2014 put the logic in a script and record the script invocation instead, or put an argument that holds such characters in ${r.quoted?"single quotes":"quotes"}`};let n=[],s=[],i="",o,a=!1,c=()=>{(i||a)&&s.push(i),i="",a=!1},l=()=>{c(),s.length>0&&n.push(s),s=[]};for(let d=0;d<t.length;d++){let p=t[d];if(o){p===o?o=void 0:i+=p;continue}if(p==='"'||p==="'"){o=p,a=!0;continue}if(p==="&"&&t[d+1]==="&"){l(),d+=1;continue}if(/\s/.test(p)){c();continue}i+=p}if(o)return{kind:"unterminated-quote",reason:"it has an unterminated quote"};if(l(),n.length===0)return{kind:"empty",reason:"the command is empty"};if(n.some(d=>d.length===0))return{kind:"empty-step",reason:"it has an empty step between && operators"};let u=n.find(d=>["cd","export","source","."].includes(d[0]));return u?{kind:"builtin",reason:`it runs the shell builtin "${u[0]}", which cannot be executed as a program \u2014 record a script that does this instead`}:{argv:n[0],steps:n}}function XBe(e,t,r){let n=(e??"").trim(),{steps:s,kind:i}=gc(n);if(!s&&!(i!=="shell-syntax"&&i!=="builtin")){try{IQ.mkdirSync(KBe.dirname(t),{recursive:!0}),IQ.writeFileSync(t,`#!/usr/bin/env bash
|
|
245
245
|
# Written by ${r}: the recorded command, which needed a shell to run.
|
|
@@ -338,7 +338,7 @@ ${e}`:e}function s7t(e,t){let r=n7t.exec(e??"")?.[1];if(!(!r||/[()[\]<>`\\]/.tes
|
|
|
338
338
|
`).filter(i=>!i.startsWith(`${Bx}:`)).join(`
|
|
339
339
|
`).trimEnd(),s=t?`${n}
|
|
340
340
|
${Bx}: ${t}`:n;e(["-c",`user.name=${pi}`,"-c",`user.email=${$o}`,"commit","--amend","--allow-empty","-m",s])}function l7t(e,t,r,n){if(n===void 0)return;let s=Bq(e,["-1","HEAD"])[0];if(!s||!BB(s)||s.deliveryOwner!==n||!Hie.test(s.testedRevision))return;let i=s.testedRevision;for(let o of t){let a=o.testedRevision;if(!(!BB(o)||o.deliveryOwner!==n||!Hie.test(a)||i===a)){try{e(["merge-base","--is-ancestor",i,a])}catch{continue}return`This run's tests for revision ${Rr(i)} are superseded: tests for newer revision ${Rr(a)} are already on '${r}'. The run left that branch unchanged; use the newer run's tests.`}}}function u7t(e,t){let r=t[0],n=BB(r)?"a Testbot run for another pull request":`${r.authorName} <${r.authorEmail}>`,s=t.length>1?` and ${t.length-1} more commit(s)`:"";return`The run did not overwrite the tests branch '${e}': it has commit ${Rr(r.sha)} by ${n}${s} that this run did not make. To deliver this run's tests, merge or close the open tests PR, delete the branch, and run again. Commit ${Rr(r.sha)}: "${r.subject.slice(0,60)}".`}async function _q(e,t,r){let n=`refs/heads/${r.branch}`,s=`refs/remotes/${r.remote}/${r.branch}`,i;try{if(!(await t(["ls-remote","--heads",r.remote,n])).trim())return{pushFlags:[]};await t(["fetch","--no-tags",r.remote,`+${n}:${s}`]),i=e(["rev-parse",s]).trim()}catch{return{pushFlags:[]}}let o,a;try{let u=NB(e,i);a=Bq(e,["--no-merges",i,...u?["--not",u]:[]]),o=Bq(e,["--no-merges",i,"--not","HEAD",...u?[u]:[]])}catch{return{pushFlags:[]}}let c=u=>BB(u)&&(u.deliveryOwner===""||r.deliveryOwner!==void 0&&u.deliveryOwner===r.deliveryOwner),l=o.filter(u=>!c(u));if(l.length)return{conflict:u7t(r.branch,l)};try{let u=l7t(e,a,r.branch,r.deliveryOwner);if(u)return{conflict:u}}catch{return{pushFlags:[]}}return{pushFlags:[`--force-with-lease=${n}:${i}`]}}var d7t=50;function W5e(e=process.env){let t=e.GITHUB_REPOSITORY,r=e.GITHUB_RUN_ID;return!t||!r?void 0:`${(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,"")}/${t}/actions/runs/${r}`}var p7t=6e4,f7t=12e4,Wie=(e,t,r)=>(0,V5e.execFileSync)(e,t,{cwd:r.cwd,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:r.env??process.env,timeout:f7t}).trim();function os(e){return wE(e)}var Nx=/\b(401|403|unauthori[sz]ed|forbidden|permission denied|authentication failed|not logged in(to)?|could not read Username|TF401027|TF401019)\b|not accessible by (integration|personal access token)|not permitted to create/i,h7t=/already exists/i,m7t=/no commits between/i,g7t=/base (ref|sha|branch)|Base ref must be a branch|field.{0,3}base|invalid base/i,A7t=/^Merge pull request #\d+ from [^/]+\/skyramp-testbot\//;function Vie(e){if(!e)return!1;let t=s4.replace(/\[bot\]$/,"");return e===s4||e===t||e===`app/${t}`}var H5e="@skyramp-testbot",y7t=/(^|[^\w@])@skyramp-testbot\b/i,E7t=new Set(["admin","maintain","write"]),DB="<!-- skyramp-testbot-no-changes-banner -->";function Qq(e){return[DB,`> \u26A0\uFE0F The latest push on ${e} did not require any new test changes.`,"> This PR still reflects Skyramp Testbot's analysis from an earlier push; regenerate if the change warrants it, or merge as-is if still relevant.",""].join(`
|
|
341
|
-
`)}function Mq(e){return e.replace(new RegExp(`${DB}\\r?\\n(?:> [^\\n]*\\r?\\n){2}\\r?\\n?`,"g"),"")}function w7t(e,t){let r=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n={...e,GIT_CONFIG_COUNT:String(r+t.length)};return t.forEach(([s,i],o)=>{n[`GIT_CONFIG_KEY_${r+o}`]=s,n[`GIT_CONFIG_VALUE_${r+o}`]=i}),n}async function Jie(){let{DefaultArtifactClient:e}=await Promise.resolve().then(()=>(vq(),xq)),t=new e;return{uploadArtifact:(r,n,s,i)=>t.uploadArtifact(r,n,s,i),downloadArtifact:async(r,n)=>{if(n?.findBy&&!n.findBy.token)throw new Error("the workflow gives Testbot no githubToken to download it with");return t.downloadArtifact(r,n)}}}function _B(e,t){try{e("git",["cherry-pick","--abort"],{cwd:t.repositoryPath})}catch{}try{e("git",["checkout","-q","-B",t.branch,t.commitSha],{cwd:t.repositoryPath})}catch{}}function Yie(e,t){let r=t.at(-1);return r?[`--force-with-lease=refs/heads/${e}:${r}`]:[]}function Pq(e,t,r,n){n.commit=void 0;try{let s=e("git",["rev-parse","HEAD"],{cwd:t}).trim();s&&r.push(s),n.commit=s||void 0}catch{}}var PB=class{constructor(t){this.opts=t;this.log=t.log??(r=>console.log(r)),this.run=t.run??Wie,this.runUrl=t.runUrl??W5e(),this.startedAtMs=t.startedAtMs??Date.now()}opts;name="github";supportsRemote=!0;runUrl;log;run;resolvedSlug;startedAtMs;warnedExpiry=!1;checkRun;async uploadArtifact(t,r,n){if(!(!this.runUrl||!r.length))try{let s=await F5e(t,r,n,{retentionDays:14});return s?`${this.runUrl}/artifacts/${s}`:void 0}catch(s){Ne(`could not upload artifact ${t}: ${s instanceof Error?s.message:String(s)}`);return}}artifactStore(){return Jie()}gh(t,r){return this.run("gh",t,{cwd:this.opts.repositoryPath,env:r?{...process.env,GH_TOKEN:r}:process.env})}ghPr(t,r,n=this.slug()){return this.gh(n?[...t,"-R",n]:t,r)}async token(){return this.opts.tokenProvider?this.opts.tokenProvider():this.opts.githubToken}git(t,r,n=this.opts.repositoryPath){return this.run("git",t,{cwd:n,env:r})}slug(){if(this.resolvedSlug===void 0){let t=(this.opts.repoSlug??process.env.GITHUB_REPOSITORY??"").trim();if(/^[^/\s]+\/[^/\s]+$/.test(t))this.resolvedSlug=t;else try{this.resolvedSlug=this.gh(["repo","view","--json","nameWithOwner","-q",".nameWithOwner"])||null}catch{this.resolvedSlug=null}}return this.resolvedSlug??void 0}warnIfTokenLikelyExpired(){if(this.opts.tokenProvider||this.warnedExpiry||(this.opts.inActions??process.env.GITHUB_ACTIONS)!=="true")return;let t=Math.round((Date.now()-this.startedAtMs)/6e4);t<d7t||(this.warnedExpiry=!0,this.log(`[warn] this run has been going for ${t} minutes \u2014 the workflow-minted GitHub token expires after 1 hour, so the push / PR / status calls may fail with 401. Set SKYRAMP_GITHUB_APP_ID and SKYRAMP_GITHUB_APP_PRIVATE_KEY so Skyramp Testbot can mint fresh tokens during long runs.`))}createProgressSink(){let t=this.slug();return this.opts.prNumber==null||!t?tT(this.log):eMe({repo:t,prNumber:this.opts.prNumber,cwd:this.opts.repositoryPath,getToken:()=>this.token(),onError:r=>this.log(`[warn] progress comment failed: ${r instanceof Error?r.message:String(r)}`)})}async resolveContext(){let t=this.slug(),r,n,s,i,o,a;if(this.opts.prNumber!=null)try{let c=await this.token().catch(()=>{}),l=JSON.parse(this.ghPr(["pr","view",String(this.opts.prNumber),"--json","headRefName,headRefOid,baseRefName,title,body,isCrossRepository"],c));r=l.headRefName||void 0,n=l.headRefOid||void 0,s=l.baseRefName||void 0,i=l.title||void 0,o=l.body||void 0,a=l.isCrossRepository}catch{}if(!r)try{let c=this.git(["rev-parse","--abbrev-ref","HEAD"]);c&&c!=="HEAD"&&(r=c)}catch{}return{repoSlug:t,prNumber:this.opts.prNumber,headBranch:r,headSha:n,baseBranch:s,prTitle:i,prBody:o,fromFork:a}}eventPayload(){let t=this.opts.eventPath??process.env.GITHUB_EVENT_PATH;if(!(!t||!Cd.existsSync(t)))try{let r=JSON.parse(Cd.readFileSync(t,"utf-8"));return typeof r=="object"&&r!==null?r:void 0}catch{return}}gitRead(t){try{return this.git(t)}catch{return""}}async admitRun(){let t=this.opts.eventName??process.env.GITHUB_EVENT_NAME,r=this.eventPayload(),n=r?.pull_request,s=r?.issue,i=await this.token().catch(()=>{}),o=n?.user?.login??s?.user?.login;if(!o&&this.opts.prNumber!=null)try{o=this.ghPr(["pr","view",String(this.opts.prNumber),"--json","author","-q",".author.login"],i)||void 0}catch{}if(o&&Vie(o))return{admit:!1,reason:`PR was opened by ${o} (a Testbot tests PR) \u2014 skipping to prevent recursion`};if(t==="issue_comment"){let c=r?.comment,l=c?.body??"",u=c?.user?.login??"";if(!s?.pull_request)return{admit:!1,reason:"comment is not on a pull request"};if(!y7t.test(l))return{admit:!1,reason:`comment does not mention ${H5e}`};if(Vie(u))return{admit:!1,reason:`comment was posted by ${u} (the bot itself)`};let d=this.permissionOf(u,i);if(!d)return{admit:!1,reason:`could not verify @${u}'s repository permission \u2014 refusing rather than assuming write access`};if(!E7t.has(d))return{admit:!1,reason:`@${u} has ${d} access; ${H5e} requires write access`};if(this.opts.allowedAuthors?.length){let p=o?.replace(/^app\//,"");if(!p)return{admit:!1,reason:"allowedAuthors is configured but the PR author could not be determined \u2014 refusing"};if(!this.opts.allowedAuthors.includes(p))return{admit:!1,reason:`PR author ${p} is not in allowedAuthors`}}}else if(this.opts.allowedAuthors?.length){let c=o?.replace(/^app\//,"");if(!c)return{admit:!1,reason:"allowedAuthors is configured but the PR author could not be determined \u2014 refusing"};if(!this.opts.allowedAuthors.includes(c))return{admit:!1,reason:`PR author ${c} is not in allowedAuthors`}}if(t==="pull_request"&&r?.action==="synchronize"){let c=n?.head?.sha||"HEAD",l=r?.head_commit,u=l?.author?.name||this.gitRead(["log","-1","--pretty=format:%an",c]),d=l?.author?.email||this.gitRead(["log","-1","--pretty=format:%ae",c]),p=this.gitRead(["log","-1","--pretty=format:%s",c]);if(!u&&!d&&!p)return{admit:!1,reason:"could not resolve the head commit's author on this synchronize \u2014 refusing rather than risking a recursive run"};if(u===pi&&d===$o)return{admit:!1,reason:`head commit is ${pi}'s own (synchronize) \u2014 skipping to prevent recursion`};if(A7t.test(p)||Vie(u))return{admit:!1,reason:`head commit merges a Testbot tests PR ("${p}") \u2014 tests already generated`}}return{admit:!0}}permissionOf(t,r){let n=this.slug();if(!(!n||!t))try{let s=JSON.parse(this.gh(["api",`repos/${n}/collaborators/${t}/permission`],r));return s.role_name??s.permission}catch{return}}watchRun(t){let r=!1,n=(l,u)=>{r||(r=!0,t(l,u))},s=null,i=!1,o=this.opts.prNumber;if(o!=null){let l=async()=>{if(!(i||r)){i=!0;try{let u=await this.token().catch(()=>{}),d=this.ghPr(["pr","view",String(o),"--json","state,mergedAt"],u),p=JSON.parse(d);p.state==="CLOSED"&&!p.mergedAt&&n("pr-closed",`PR #${o} was closed without merging`)}catch{}finally{i=!1}}};s=setInterval(()=>{l()},this.opts.prPollMs??p7t),s.unref?.()}let a=this.opts.watchSignals===!1?[]:["SIGTERM","SIGINT"],c=l=>{for(let u of a)process.removeListener(u,c);n("cancelled",`received ${l} (workflow cancelled or runner shutting down)`)};for(let l of a)process.on(l,c);return{stop:()=>{s&&clearInterval(s),s=null;for(let l of a)process.removeListener(l,c)}}}checkName(){let t=this.opts.eventName??process.env.GITHUB_EVENT_NAME;return t==="workflow_dispatch"||t==="issue_comment"?`${pi} (retrigger)`:pi}async beginRun(){let t=this.slug();if(this.opts.prNumber==null||!t)return;let r=this.checkName();try{let n=await this.token(),s=this.gh(["pr","view",String(this.opts.prNumber),"--json","headRefOid","-q",".headRefOid"],n);if(!s)return;let i=["api",`repos/${t}/check-runs`,"-X","POST","-f",`name=${r}`,"-f",`head_sha=${s}`,"-f","status=in_progress","-f",`started_at=${new Date().toISOString()}`];this.runUrl&&i.push("-f",`details_url=${this.runUrl}`);try{let o=Number(this.gh([...i,"-q",".id"],n));if(Number.isFinite(o)&&o>0){this.checkRun={id:o,sha:s};return}}catch(o){if(!Nx.test(os(o)))throw o}this.checkRun={fallbackSha:s},this.commitStatus(t,s,"pending",r,"Skyramp Testbot is running",n)}catch(n){this.log(`[warn] could not report run start: ${ko(n)}`)}}async endRun(t){let r=this.slug();if(!this.checkRun||!r)return;this.warnIfTokenLikelyExpired();let n=this.checkName();try{let s=await this.token();if("id"in this.checkRun){let i=t.status==="success"?"success":t.status==="neutral"?"neutral":t.status==="cancelled"?"cancelled":"failure",o=["api",`repos/${r}/check-runs/${this.checkRun.id}`,"-X","PATCH","-f","status=completed","-f",`conclusion=${i}`,"-f",`completed_at=${new Date().toISOString()}`];o.push("-f",`output[title]=${n}`,"-f",`output[summary]=${t.summary.slice(0,6e4)}`),this.gh(o,s)}else{let i=t.status==="success"||t.status==="neutral"?"success":t.status==="cancelled"?"error":"failure";this.commitStatus(r,this.checkRun.fallbackSha,i,n,t.summary,s)}}catch(s){this.log(`[warn] could not report run end (${t.status}): ${ko(s)}`)}finally{this.checkRun=void 0}}async listCommitChecks(t){try{let r=await this.token(),n=[],s=JSON.parse(this.gh(["api",`repos/${t.repository}/commits/${t.revision}/check-runs?per_page=100`],r));for(let o of s.check_runs??[])o.name&&o.head_sha&&n.push({repository:t.repository,name:o.name,headSha:o.head_sha,status:o.status??"completed",conclusion:o.conclusion??null,url:o.html_url,summary:o.output?.title??void 0});let i={};try{i=JSON.parse(this.gh(["api",`repos/${t.repository}/commits/${t.revision}/status`],r))}catch(o){this.log(`[warn] could not read commit statuses for ${t.repository}@${t.revision.slice(0,12)}: ${ko(o)}`)}for(let o of i.statuses??[])o.context&&n.push({repository:t.repository,name:o.context,headSha:i.sha??t.revision,status:o.state==="pending"?"pending":"completed",conclusion:o.state==="pending"?null:o.state??null,url:o.target_url??void 0,summary:o.description??void 0});return{records:n}}catch(r){this.log(`[warn] could not read CI results for ${t.repository}@${t.revision.slice(0,12)}: ${ko(r)}`);return}}async commitContains(t){try{let r=await this.token(),n=JSON.parse(this.gh(["api",`repos/${t.repository}/compare/${t.ancestor}...${t.descendant}`,"--jq","{status: .status}"],r));return n.status==="identical"||n.status==="ahead"?"contained":n.status==="behind"||n.status==="diverged"?"not_contained":"unknown"}catch(r){return this.log(`[warn] could not compare ${t.repository} ${Rr(t.ancestor)}...${Rr(t.descendant)}: ${ko(r)}`),"unknown"}}commitStatus(t,r,n,s,i,o){let a=["api",`repos/${t}/statuses/${r}`,"-X","POST","-f",`state=${n}`,"-f",`context=${s}`,"-f",`description=${i.slice(0,140)}`];this.runUrl&&a.push("-f",`target_url=${this.runUrl}`),this.gh(a,o)}async markTestsPrUnchanged(t){let r=t.repoSlug??this.slug(),n=i=>({action:"skipped",pushed:!1,base:"",url:"",detail:i}),s;try{let i=await this.token(),o=JSON.parse(this.ghPr(["pr","view",t.branch,"--json","number,url,state,body,baseRefName"],i,r));if(o.state!=="OPEN"||!o.number)return n(`no open tests PR for ${t.branch} \u2014 nothing to annotate`);let a=t.devPr===void 0?this.opts.prNumber:t.devPr,c=a!=null?`#${a}`:"the dev branch",l=Qq(c)+Mq(o.body??"");s=Cd.mkdtempSync(_x.join(z5e.tmpdir(),"staged-stale-"));let u=_x.join(s,"body.md");return Cd.writeFileSync(u,l),this.ghPr(["pr","edit",String(o.number),"--body-file",u],i,r),{action:"unchanged",pushed:!1,base:o.baseRefName??"",url:o.url??"",detail:"no new test changes this run \u2014 existing tests PR annotated"}}catch(i){return n(`could not annotate the tests PR: ${ko(i)}`)}finally{s&&Cd.rmSync(s,{recursive:!0,force:!0})}}async closeTestsPr(t){try{let r=await this.token(),n=JSON.parse(this.ghPr(["pr","view",t.branch,"--json","number,url,state"],r));return n.state!=="OPEN"||!n.number?{closed:!1,url:n.url}:(this.ghPr(["pr","close",String(n.number),"--comment",t.reason],r),{closed:!0,url:n.url})}catch(r){return this.log(`[warn] could not close the tests PR for ${t.branch}: ${ko(r)}`),{closed:!1}}}hasPersistedGitCredential(t){try{return!!this.git(["config","--get-regexp","^http(\\..*)?\\.extraheader$"],void 0,t).trim()}catch{return!1}}push(t,r,n=["--force"]){let s=`HEAD:refs/heads/${t.branch}`;this.remoteGit(["push",...n,t.remote,s],r,t.repositoryPath)}checkoutAuthHeader;adoptCheckoutAuthHeader(t){this.checkoutAuthHeader=t}remoteGit(t,r,n=this.opts.repositoryPath){let s=this.opts.tokenProvider?r:void 0,i=this.opts.githubToken,o=s??r??i,a=_x.resolve(n)===_x.resolve(this.opts.repositoryPath)?this.checkoutAuthHeader:void 0;if(!a&&!o||this.hasPersistedGitCredential(n))return this.git(t,void 0,n);let c=h=>{let m=Buffer.from(`x-access-token:${h}`).toString("base64");return En(m),`AUTHORIZATION: basic ${m}`},l=a!==void 0&&i!==void 0&&a===c(i),u=s?c(s):a&&!l?a:c(o),d=(process.env.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),p=[[`http.${d}/.extraheader`,u]];if(process.env.GITHUB_ACTIONS==="true"){let h=new URL(d).hostname;p.push([`url.${d}/.insteadOf`,`git@${h}:`],[`url.${d}/.insteadOf`,`ssh://git@${h}/`])}return this.git(t,w7t(process.env,p),n)}testsPrBody(t,r,n){try{return this.ghPr(["pr","view",t,"--json","body","-q",".body"],r,n)}catch(s){this.log(`[warn] could not read the tests PR for ${t}: ${os(s)}`);return}}noteReplaced(t,r,n,s,i){let o=Rq({runUrl:t.runUrl,previousBody:r,commit:n});if(o)try{this.ghPr(["pr","comment",t.branch,"--body",o],s,i)}catch(a){this.log(`[warn] could not comment on the tests PR for ${t.branch}: ${os(a)}`)}}pushFailure(t,r){let n=os(t);return{action:"failed",pushed:!1,base:r,url:"",failure:Nx.test(n)?"auth":"push",detail:`push failed: ${n}`}}async publishTestsPr(t){let r=[],n={};return{...await this.publish(t,r,n),pushedCommits:r,...n.commit?{deliveredCommit:n.commit}:{}}}async publish(t,r,n){this.warnIfTokenLikelyExpired();let s=t.repositoryPath,i=t.repoSlug??this.slug(),o=t.devPr===void 0?this.opts.prNumber:t.devPr,a=(g,y,A,w=t.base)=>({action:"failed",pushed:A,base:w,url:"",failure:g,detail:y}),c;try{c=await this.token()}catch(g){return a("auth",`could not mint a GitHub App token: ${os(g)}`,!1)}let l=["--force"];if(t.mode==="append"){let g=!1;try{g=!!this.remoteGit(["ls-remote","--heads",t.remote,t.branch],c,s).trim()}catch{l=[]}if(g){try{this.remoteGit(["fetch",t.remote,t.branch],c,s);let A=NB(w=>this.git(w,void 0,s),`${t.remote}/${t.branch}`);this.git(["checkout","-B",t.branch,`${t.remote}/${t.branch}`],void 0,s),this.git(["-c",`user.name=${pi}`,"-c",`user.email=${$o}`,"cherry-pick","--keep-redundant-commits",t.commitSha],void 0,s),Mm(w=>this.git(w,void 0,s),A)}catch(A){return _B(this.run,t),a("conflict",`append onto the existing tests branch failed (tests kept on the local branch): ${os(A)}`,!1)}let y=!1;try{this.git(["diff","--quiet",`${t.remote}/${t.branch}`,"HEAD"],void 0,s),y=!0}catch{y=!1}if(y)return this.markTestsPrUnchanged({branch:t.branch,repositoryPath:s,repoSlug:t.repoSlug,devPr:t.devPr});l=[]}}else{let g=await _q(y=>this.git(y,void 0,s),y=>this.remoteGit(y,c,s),t);if("conflict"in g)return a("conflict",g.conflict,!1);l=g.pushFlags}try{this.push(t,c,l)}catch(g){return this.pushFailure(g,t.base)}Pq(this.run,s,r,n);let u=g=>this.ghPr(["pr","create","--head",t.branch,"--base",g,"--title",t.title,"--body-file",t.bodyFile],c,i),d=g=>{let y=t.mode!=="append"&&t.runUrl?{body:this.testsPrBody(t.branch,c,i)}:void 0;this.ghPr(["pr","edit",t.branch,"--base",g,"--title",t.title,"--body-file",t.bodyFile],c,i);let A=this.ghPr(["pr","view",t.branch,"--json","url","-q",".url"],c,i);return y&&this.noteReplaced(t,y.body,n.commit,c,i),{action:"updated",pushed:!0,base:g,url:A}},p=(g,y)=>{if(h7t.test(g))try{return d(y)}catch(A){return a("unknown",`tests PR exists but could not be updated: ${os(A)}`,!0,y)}if(m7t.test(g))return{action:"skipped",pushed:!0,base:y,url:"",detail:`no commits between ${y} and ${t.branch} \u2014 the tests are already on the base`};if(Nx.test(g))return a("auth",g,!0,y)},h;try{return{action:"created",pushed:!0,base:t.base,url:u(t.base)}}catch(g){h=os(g)}let m=p(h,t.base);if(m)return m;if(g7t.test(h)){if(t.mode==="append")return a("unknown",`the dev branch '${t.base}' no longer exists (dev PR merged) and append mode cannot re-cut the tests branch \u2014 re-run in replace mode`,!0);if(o==null)return a("unknown",`the base branch '${t.base}' no longer exists and no dev PR number is known to retarget from`,!0);let g={};try{g=JSON.parse(this.ghPr(["pr","view",String(o),"--json","state,baseRefName"],c,i))}catch{}if(g.state!=="MERGED"||!g.baseRefName)return{action:"skipped",pushed:!0,base:t.base,url:"",detail:`the dev branch '${t.base}' no longer exists and PR #${o} is ${g.state??"unknown"} (not merged) \u2014 nothing to target; tests are on branch ${t.branch}`};let y=g.baseRefName;this.log(`[deliver] tests PR base '${t.base}' no longer exists (dev PR merged) \u2014 re-cutting onto '${y}'`);try{this.remoteGit(["fetch",t.remote,y],c,s),this.git(["checkout","-B",t.branch,`${t.remote}/${y}`],void 0,s),this.git(["-c",`user.name=${pi}`,"-c",`user.email=${$o}`,"cherry-pick","--keep-redundant-commits",t.commitSha],void 0,s),Mm(A=>this.git(A,void 0,s),this.git(["rev-parse","HEAD^"],void 0,s).trim())}catch(A){return _B(this.run,t),a("conflict",`re-cut onto '${y}' failed (tests kept on the local branch): ${os(A)}`,!0)}try{this.push(t,c,Yie(t.branch,r))}catch(A){return this.pushFailure(A,y)}Pq(this.run,s,r,n);try{return{action:"retargeted",retargetedAs:"created",pushed:!0,base:y,url:u(y)}}catch(A){let w=os(A),S=p(w,y);return S?S.action==="updated"?{...S,action:"retargeted",retargetedAs:"updated"}:S:a("unknown",`re-cut onto '${y}' pushed, but PR create failed: ${w}`,!0,y)}}return a("unknown",h,!0)}};var za=Y(require("fs")),toe=Y(require("os")),ti=Y(require("path"));var J5e=Y(require("fs")),OB="SKYRAMP_AZURE_SUPERVISED",Kie=3;function Fq(e){return e.replace(/##(?=(?:vso)?\[)/gi,"#\u200B#")}function Xie(e,t=process.env){t[OB]==="1"?J5e.writeSync(Kie,`${JSON.stringify(e)}
|
|
341
|
+
`)}function Mq(e){return e.replace(new RegExp(`${DB}\\r?\\n(?:> [^\\n]*\\r?\\n){2}\\r?\\n?`,"g"),"")}function w7t(e,t){let r=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n={...e,GIT_CONFIG_COUNT:String(r+t.length)};return t.forEach(([s,i],o)=>{n[`GIT_CONFIG_KEY_${r+o}`]=s,n[`GIT_CONFIG_VALUE_${r+o}`]=i}),n}async function Jie(){let{DefaultArtifactClient:e}=await Promise.resolve().then(()=>(vq(),xq)),t=new e;return{uploadArtifact:(r,n,s,i)=>t.uploadArtifact(r,n,s,i),downloadArtifact:async(r,n)=>{if(n?.findBy&&!n.findBy.token)throw new Error("the workflow gives Testbot no githubToken to download it with");return t.downloadArtifact(r,n)}}}function _B(e,t){try{e("git",["cherry-pick","--abort"],{cwd:t.repositoryPath})}catch{}try{e("git",["checkout","-q","-B",t.branch,t.commitSha],{cwd:t.repositoryPath})}catch{}}function Yie(e,t){let r=t.at(-1);return r?[`--force-with-lease=refs/heads/${e}:${r}`]:[]}function Pq(e,t,r,n){n.commit=void 0;try{let s=e("git",["rev-parse","HEAD"],{cwd:t}).trim();s&&r.push(s),n.commit=s||void 0}catch{}}var PB=class{constructor(t){this.opts=t;this.log=t.log??(r=>console.log(r)),this.run=t.run??Wie,this.runUrl=t.runUrl??W5e(),this.startedAtMs=t.startedAtMs??Date.now()}opts;name="github";supportsRemote=!0;runUrl;log;run;resolvedSlug;startedAtMs;warnedExpiry=!1;checkRun;async uploadArtifact(t,r,n){if(!(!this.runUrl||!r.length))try{let s=await F5e(t,r,n,{retentionDays:14});return s?`${this.runUrl}/artifacts/${s}`:void 0}catch(s){Ne(`could not upload artifact ${t}: ${s instanceof Error?s.message:String(s)}`);return}}artifactStore(){return Jie()}gh(t,r){return this.run("gh",t,{cwd:this.opts.repositoryPath,env:r?{...process.env,GH_TOKEN:r}:process.env})}ghPr(t,r,n=this.slug()){return this.gh(n?[...t,"-R",n]:t,r)}async token(){return this.opts.tokenProvider?this.opts.tokenProvider():this.opts.githubToken}git(t,r,n=this.opts.repositoryPath){return this.run("git",t,{cwd:n,env:r})}slug(){if(this.resolvedSlug===void 0){let t=(this.opts.repoSlug??process.env.GITHUB_REPOSITORY??"").trim();if(/^[^/\s]+\/[^/\s]+$/.test(t))this.resolvedSlug=t;else try{this.resolvedSlug=this.gh(["repo","view","--json","nameWithOwner","-q",".nameWithOwner"])||null}catch{this.resolvedSlug=null}}return this.resolvedSlug??void 0}warnIfTokenLikelyExpired(){if(this.opts.tokenProvider||this.warnedExpiry||(this.opts.inActions??process.env.GITHUB_ACTIONS)!=="true")return;let t=Math.round((Date.now()-this.startedAtMs)/6e4);t<d7t||(this.warnedExpiry=!0,this.log(`[warn] this run has been going for ${t} minutes \u2014 the workflow-minted GitHub token expires after 1 hour, so the push / PR / status calls may fail with 401. Set SKYRAMP_GITHUB_APP_ID and SKYRAMP_GITHUB_APP_PRIVATE_KEY so Skyramp Testbot can mint fresh tokens during long runs.`))}createProgressSink(){let t=this.slug();return this.opts.prNumber==null||!t?tT(this.log):eMe({repo:t,prNumber:this.opts.prNumber,cwd:this.opts.repositoryPath,getToken:()=>this.token(),onError:r=>this.log(`[warn] progress comment failed: ${r instanceof Error?r.message:String(r)}`)})}async resolveContext(){let t=this.slug(),r,n,s,i,o,a;if(this.opts.prNumber!=null)try{let c=await this.token().catch(()=>{}),l=JSON.parse(this.ghPr(["pr","view",String(this.opts.prNumber),"--json","headRefName,headRefOid,baseRefName,title,body,isCrossRepository"],c));r=l.headRefName||void 0,n=l.headRefOid||void 0,s=l.baseRefName||void 0,i=l.title||void 0,o=l.body||void 0,a=l.isCrossRepository}catch{}if(!r)try{let c=this.git(["rev-parse","--abbrev-ref","HEAD"]);c&&c!=="HEAD"&&(r=c)}catch{}return{repoSlug:t,prNumber:this.opts.prNumber,headBranch:r,headSha:n,baseBranch:s,prTitle:i,prBody:o,fromFork:a}}eventPayload(){let t=this.opts.eventPath??process.env.GITHUB_EVENT_PATH;if(!(!t||!Cd.existsSync(t)))try{let r=JSON.parse(Cd.readFileSync(t,"utf-8"));return typeof r=="object"&&r!==null?r:void 0}catch{return}}gitRead(t){try{return this.git(t)}catch{return""}}async admitRun(){let t=this.opts.eventName??process.env.GITHUB_EVENT_NAME,r=this.eventPayload(),n=r?.pull_request,s=r?.issue,i=await this.token().catch(()=>{}),o=n?.user?.login??s?.user?.login;if(!o&&this.opts.prNumber!=null)try{o=this.ghPr(["pr","view",String(this.opts.prNumber),"--json","author","-q",".author.login"],i)||void 0}catch{}if(o&&Vie(o))return{admit:!1,reason:`PR was opened by ${o} (a Testbot tests PR) \u2014 skipping to prevent recursion`};if(t==="issue_comment"){let c=r?.comment,l=c?.body??"",u=c?.user?.login??"";if(!s?.pull_request)return{admit:!1,reason:"comment is not on a pull request"};if(!y7t.test(l))return{admit:!1,reason:`comment does not mention ${H5e}`};if(Vie(u))return{admit:!1,reason:`comment was posted by ${u} (the bot itself)`};let d=this.permissionOf(u,i);if(!d)return{admit:!1,reason:`could not verify @${u}'s repository permission \u2014 refusing rather than assuming write access`};if(!E7t.has(d))return{admit:!1,reason:`@${u} has ${d} access; ${H5e} requires write access`};if(this.opts.allowedAuthors?.length){let p=o?.replace(/^app\//,"");if(!p)return{admit:!1,reason:"allowedAuthors is configured but the PR author could not be determined \u2014 refusing"};if(!this.opts.allowedAuthors.includes(p))return{admit:!1,reason:`PR author ${p} is not in allowedAuthors`}}}else if(this.opts.allowedAuthors?.length){let c=o?.replace(/^app\//,"");if(!c)return{admit:!1,reason:"allowedAuthors is configured but the PR author could not be determined \u2014 refusing"};if(!this.opts.allowedAuthors.includes(c))return{admit:!1,reason:`PR author ${c} is not in allowedAuthors`}}if(t==="pull_request"&&r?.action==="synchronize"){let c=n?.head?.sha||"HEAD",l=r?.head_commit,u=l?.author?.name||this.gitRead(["log","-1","--pretty=format:%an",c]),d=l?.author?.email||this.gitRead(["log","-1","--pretty=format:%ae",c]),p=this.gitRead(["log","-1","--pretty=format:%s",c]);if(!u&&!d&&!p)return{admit:!1,reason:"could not resolve the head commit's author on this synchronize \u2014 refusing rather than risking a recursive run"};if(u===pi&&d===$o)return{admit:!1,reason:`head commit is ${pi}'s own (synchronize) \u2014 skipping to prevent recursion`};if(A7t.test(p)||Vie(u))return{admit:!1,reason:`head commit merges a Testbot tests PR ("${p}") \u2014 tests already generated`}}return{admit:!0}}permissionOf(t,r){let n=this.slug();if(!(!n||!t))try{let s=JSON.parse(this.gh(["api",`repos/${n}/collaborators/${t}/permission`],r));return s.role_name??s.permission}catch{return}}watchRun(t){let r=!1,n=(l,u)=>{r||(r=!0,t(l,u))},s=null,i=!1,o=this.opts.prNumber;if(o!=null){let l=async()=>{if(!(i||r)){i=!0;try{let u=await this.token().catch(()=>{}),d=this.ghPr(["pr","view",String(o),"--json","state,mergedAt"],u),p=JSON.parse(d);p.state==="CLOSED"&&!p.mergedAt&&n("pr-closed",`PR #${o} was closed without merging`)}catch{}finally{i=!1}}};s=setInterval(()=>{l()},this.opts.prPollMs??p7t),s.unref?.()}let a=this.opts.watchSignals===!1?[]:["SIGTERM","SIGINT"],c=l=>{for(let u of a)process.removeListener(u,c);n("cancelled",`received ${l} (workflow cancelled or runner shutting down)`)};for(let l of a)process.on(l,c);return{stop:()=>{s&&clearInterval(s),s=null;for(let l of a)process.removeListener(l,c)}}}checkName(){let t=this.opts.eventName??process.env.GITHUB_EVENT_NAME;return t==="workflow_dispatch"||t==="issue_comment"?`${pi} (retrigger)`:pi}async beginRun(){let t=this.slug();if(this.opts.prNumber==null||!t)return;let r=this.checkName();try{let n=await this.token(),s=this.gh(["pr","view",String(this.opts.prNumber),"--json","headRefOid","-q",".headRefOid"],n);if(!s)return;let i=["api",`repos/${t}/check-runs`,"-X","POST","-f",`name=${r}`,"-f",`head_sha=${s}`,"-f","status=in_progress","-f",`started_at=${new Date().toISOString()}`];this.runUrl&&i.push("-f",`details_url=${this.runUrl}`);try{let o=Number(this.gh([...i,"-q",".id"],n));if(Number.isFinite(o)&&o>0){this.checkRun={id:o,sha:s};return}}catch(o){if(!Nx.test(os(o)))throw o}this.checkRun={fallbackSha:s},this.commitStatus(t,s,"pending",r,"Skyramp Testbot is running",n)}catch(n){this.log(`[warn] could not report run start: ${ko(n)}`)}}async endRun(t){let r=this.slug();if(!this.checkRun||!r)return;this.warnIfTokenLikelyExpired();let n=this.checkName();try{let s=await this.token();if("id"in this.checkRun){let i=t.status==="success"?"success":t.status==="neutral"?"neutral":t.status==="cancelled"?"cancelled":"failure",o=["api",`repos/${r}/check-runs/${this.checkRun.id}`,"-X","PATCH","-f","status=completed","-f",`conclusion=${i}`,"-f",`completed_at=${new Date().toISOString()}`];o.push("-f",`output[title]=${n}`,"-f",`output[summary]=${t.summary.slice(0,6e4)}`),this.gh(o,s)}else{let i=t.status==="success"||t.status==="neutral"?"success":t.status==="cancelled"?"error":"failure";this.commitStatus(r,this.checkRun.fallbackSha,i,n,t.summary,s)}}catch(s){this.log(`[warn] could not report run end (${t.status}): ${ko(s)}`)}finally{this.checkRun=void 0}}async listCommitChecks(t){try{let r=await this.token(),n=[],s=JSON.parse(this.gh(["api",`repos/${t.repository}/commits/${t.revision}/check-runs?per_page=100`],r));for(let a of s.check_runs??[])a.name&&a.head_sha&&n.push({repository:t.repository,name:a.name,headSha:a.head_sha,status:a.status??"completed",conclusion:a.conclusion??null,url:a.html_url,summary:a.output?.title??void 0});let i=[],o={};try{o=JSON.parse(this.gh(["api",`repos/${t.repository}/commits/${t.revision}/status`],r))}catch(a){i.push("commit statuses"),this.log(`[warn] could not read commit statuses for ${t.repository}@${t.revision.slice(0,12)}: ${ko(a)}`)}for(let a of o.statuses??[])a.context&&n.push({repository:t.repository,name:a.context,headSha:o.sha??t.revision,status:a.state==="pending"?"pending":"completed",conclusion:a.state==="pending"?null:a.state??null,url:a.target_url??void 0,summary:a.description??void 0});return{records:n,...i.length?{unreadSources:i}:{}}}catch(r){this.log(`[warn] could not read CI results for ${t.repository}@${t.revision.slice(0,12)}: ${ko(r)}`);return}}async commitContains(t){try{let r=await this.token(),n=JSON.parse(this.gh(["api",`repos/${t.repository}/compare/${t.ancestor}...${t.descendant}`,"--jq","{status: .status}"],r));return n.status==="identical"||n.status==="ahead"?"contained":n.status==="behind"||n.status==="diverged"?"not_contained":"unknown"}catch(r){return this.log(`[warn] could not compare ${t.repository} ${Rr(t.ancestor)}...${Rr(t.descendant)}: ${ko(r)}`),"unknown"}}commitStatus(t,r,n,s,i,o){let a=["api",`repos/${t}/statuses/${r}`,"-X","POST","-f",`state=${n}`,"-f",`context=${s}`,"-f",`description=${i.slice(0,140)}`];this.runUrl&&a.push("-f",`target_url=${this.runUrl}`),this.gh(a,o)}async markTestsPrUnchanged(t){let r=t.repoSlug??this.slug(),n=i=>({action:"skipped",pushed:!1,base:"",url:"",detail:i}),s;try{let i=await this.token(),o=JSON.parse(this.ghPr(["pr","view",t.branch,"--json","number,url,state,body,baseRefName"],i,r));if(o.state!=="OPEN"||!o.number)return n(`no open tests PR for ${t.branch} \u2014 nothing to annotate`);let a=t.devPr===void 0?this.opts.prNumber:t.devPr,c=a!=null?`#${a}`:"the dev branch",l=Qq(c)+Mq(o.body??"");s=Cd.mkdtempSync(_x.join(z5e.tmpdir(),"staged-stale-"));let u=_x.join(s,"body.md");return Cd.writeFileSync(u,l),this.ghPr(["pr","edit",String(o.number),"--body-file",u],i,r),{action:"unchanged",pushed:!1,base:o.baseRefName??"",url:o.url??"",detail:"no new test changes this run \u2014 existing tests PR annotated"}}catch(i){return n(`could not annotate the tests PR: ${ko(i)}`)}finally{s&&Cd.rmSync(s,{recursive:!0,force:!0})}}async closeTestsPr(t){try{let r=await this.token(),n=JSON.parse(this.ghPr(["pr","view",t.branch,"--json","number,url,state"],r));return n.state!=="OPEN"||!n.number?{closed:!1,url:n.url}:(this.ghPr(["pr","close",String(n.number),"--comment",t.reason],r),{closed:!0,url:n.url})}catch(r){return this.log(`[warn] could not close the tests PR for ${t.branch}: ${ko(r)}`),{closed:!1}}}hasPersistedGitCredential(t){try{return!!this.git(["config","--get-regexp","^http(\\..*)?\\.extraheader$"],void 0,t).trim()}catch{return!1}}push(t,r,n=["--force"]){let s=`HEAD:refs/heads/${t.branch}`;this.remoteGit(["push",...n,t.remote,s],r,t.repositoryPath)}checkoutAuthHeader;adoptCheckoutAuthHeader(t){this.checkoutAuthHeader=t}remoteGit(t,r,n=this.opts.repositoryPath){let s=this.opts.tokenProvider?r:void 0,i=this.opts.githubToken,o=s??r??i,a=_x.resolve(n)===_x.resolve(this.opts.repositoryPath)?this.checkoutAuthHeader:void 0;if(!a&&!o||this.hasPersistedGitCredential(n))return this.git(t,void 0,n);let c=h=>{let m=Buffer.from(`x-access-token:${h}`).toString("base64");return En(m),`AUTHORIZATION: basic ${m}`},l=a!==void 0&&i!==void 0&&a===c(i),u=s?c(s):a&&!l?a:c(o),d=(process.env.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),p=[[`http.${d}/.extraheader`,u]];if(process.env.GITHUB_ACTIONS==="true"){let h=new URL(d).hostname;p.push([`url.${d}/.insteadOf`,`git@${h}:`],[`url.${d}/.insteadOf`,`ssh://git@${h}/`])}return this.git(t,w7t(process.env,p),n)}testsPrBody(t,r,n){try{return this.ghPr(["pr","view",t,"--json","body","-q",".body"],r,n)}catch(s){this.log(`[warn] could not read the tests PR for ${t}: ${os(s)}`);return}}noteReplaced(t,r,n,s,i){let o=Rq({runUrl:t.runUrl,previousBody:r,commit:n});if(o)try{this.ghPr(["pr","comment",t.branch,"--body",o],s,i)}catch(a){this.log(`[warn] could not comment on the tests PR for ${t.branch}: ${os(a)}`)}}pushFailure(t,r){let n=os(t);return{action:"failed",pushed:!1,base:r,url:"",failure:Nx.test(n)?"auth":"push",detail:`push failed: ${n}`}}async publishTestsPr(t){let r=[],n={};return{...await this.publish(t,r,n),pushedCommits:r,...n.commit?{deliveredCommit:n.commit}:{}}}async publish(t,r,n){this.warnIfTokenLikelyExpired();let s=t.repositoryPath,i=t.repoSlug??this.slug(),o=t.devPr===void 0?this.opts.prNumber:t.devPr,a=(g,y,A,w=t.base)=>({action:"failed",pushed:A,base:w,url:"",failure:g,detail:y}),c;try{c=await this.token()}catch(g){return a("auth",`could not mint a GitHub App token: ${os(g)}`,!1)}let l=["--force"];if(t.mode==="append"){let g=!1;try{g=!!this.remoteGit(["ls-remote","--heads",t.remote,t.branch],c,s).trim()}catch{l=[]}if(g){try{this.remoteGit(["fetch",t.remote,t.branch],c,s);let A=NB(w=>this.git(w,void 0,s),`${t.remote}/${t.branch}`);this.git(["checkout","-B",t.branch,`${t.remote}/${t.branch}`],void 0,s),this.git(["-c",`user.name=${pi}`,"-c",`user.email=${$o}`,"cherry-pick","--keep-redundant-commits",t.commitSha],void 0,s),Mm(w=>this.git(w,void 0,s),A)}catch(A){return _B(this.run,t),a("conflict",`append onto the existing tests branch failed (tests kept on the local branch): ${os(A)}`,!1)}let y=!1;try{this.git(["diff","--quiet",`${t.remote}/${t.branch}`,"HEAD"],void 0,s),y=!0}catch{y=!1}if(y)return this.markTestsPrUnchanged({branch:t.branch,repositoryPath:s,repoSlug:t.repoSlug,devPr:t.devPr});l=[]}}else{let g=await _q(y=>this.git(y,void 0,s),y=>this.remoteGit(y,c,s),t);if("conflict"in g)return a("conflict",g.conflict,!1);l=g.pushFlags}try{this.push(t,c,l)}catch(g){return this.pushFailure(g,t.base)}Pq(this.run,s,r,n);let u=g=>this.ghPr(["pr","create","--head",t.branch,"--base",g,"--title",t.title,"--body-file",t.bodyFile],c,i),d=g=>{let y=t.mode!=="append"&&t.runUrl?{body:this.testsPrBody(t.branch,c,i)}:void 0;this.ghPr(["pr","edit",t.branch,"--base",g,"--title",t.title,"--body-file",t.bodyFile],c,i);let A=this.ghPr(["pr","view",t.branch,"--json","url","-q",".url"],c,i);return y&&this.noteReplaced(t,y.body,n.commit,c,i),{action:"updated",pushed:!0,base:g,url:A}},p=(g,y)=>{if(h7t.test(g))try{return d(y)}catch(A){return a("unknown",`tests PR exists but could not be updated: ${os(A)}`,!0,y)}if(m7t.test(g))return{action:"skipped",pushed:!0,base:y,url:"",detail:`no commits between ${y} and ${t.branch} \u2014 the tests are already on the base`};if(Nx.test(g))return a("auth",g,!0,y)},h;try{return{action:"created",pushed:!0,base:t.base,url:u(t.base)}}catch(g){h=os(g)}let m=p(h,t.base);if(m)return m;if(g7t.test(h)){if(t.mode==="append")return a("unknown",`the dev branch '${t.base}' no longer exists (dev PR merged) and append mode cannot re-cut the tests branch \u2014 re-run in replace mode`,!0);if(o==null)return a("unknown",`the base branch '${t.base}' no longer exists and no dev PR number is known to retarget from`,!0);let g={};try{g=JSON.parse(this.ghPr(["pr","view",String(o),"--json","state,baseRefName"],c,i))}catch{}if(g.state!=="MERGED"||!g.baseRefName)return{action:"skipped",pushed:!0,base:t.base,url:"",detail:`the dev branch '${t.base}' no longer exists and PR #${o} is ${g.state??"unknown"} (not merged) \u2014 nothing to target; tests are on branch ${t.branch}`};let y=g.baseRefName;this.log(`[deliver] tests PR base '${t.base}' no longer exists (dev PR merged) \u2014 re-cutting onto '${y}'`);try{this.remoteGit(["fetch",t.remote,y],c,s),this.git(["checkout","-B",t.branch,`${t.remote}/${y}`],void 0,s),this.git(["-c",`user.name=${pi}`,"-c",`user.email=${$o}`,"cherry-pick","--keep-redundant-commits",t.commitSha],void 0,s),Mm(A=>this.git(A,void 0,s),this.git(["rev-parse","HEAD^"],void 0,s).trim())}catch(A){return _B(this.run,t),a("conflict",`re-cut onto '${y}' failed (tests kept on the local branch): ${os(A)}`,!0)}try{this.push(t,c,Yie(t.branch,r))}catch(A){return this.pushFailure(A,y)}Pq(this.run,s,r,n);try{return{action:"retargeted",retargetedAs:"created",pushed:!0,base:y,url:u(y)}}catch(A){let w=os(A),S=p(w,y);return S?S.action==="updated"?{...S,action:"retargeted",retargetedAs:"updated"}:S:a("unknown",`re-cut onto '${y}' pushed, but PR create failed: ${w}`,!0,y)}}return a("unknown",h,!0)}};var za=Y(require("fs")),toe=Y(require("os")),ti=Y(require("path"));var J5e=Y(require("fs")),OB="SKYRAMP_AZURE_SUPERVISED",Kie=3;function Fq(e){return e.replace(/##(?=(?:vso)?\[)/gi,"#\u200B#")}function Xie(e,t=process.env){t[OB]==="1"?J5e.writeSync(Kie,`${JSON.stringify(e)}
|
|
342
342
|
`):process.stdout.write(e.command!==void 0?`${e.command}
|
|
343
343
|
`:e.text??"")}function QB(e){Xie({command:e})}function Y5e(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function b7t(e){return Y5e(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}function Dx(e,t,r){let n=Object.entries(t).map(([s,i])=>`${s}=${b7t(i)}`).join(";");return`##vso[${e}${n?` ${n}`:""}]${Y5e(r)}`}function K5e(e){if(!e)return[];let t=e.split(/\r?\n/).filter(r=>r.trim()&&r!==e);return[e,...t].map(r=>Dx("task.setsecret",{},r))}function X5e(e,t=QB){for(let r of K5e(e))t(r)}function S7t(e){return e.replace(/%0D/g,"\r").replace(/%0A/g,`
|
|
344
344
|
`).replace(/%25/g,"%")}function Z5e(e){let t=/^::([a-z-]+)(?: [^:]*)?::(.*)$/s.exec(e.replace(/\r?\n$/,""));if(!t)return;let[,r,n]=t,s=S7t(n),i=Fq(s);switch(r){case"add-mask":return K5e(s);case"warning":case"error":return[Dx("task.logissue",{type:r},i)];case"notice":return[i];case"debug":return i.split(`
|
|
@@ -349,7 +349,7 @@ ${Bx}: ${t}`:n;e(["-c",`user.name=${pi}`,"-c",`user.email=${$o}`,"commit","--ame
|
|
|
349
349
|
`),o=B7t(i),a=n?/\]\(([^\s)]+)\)_$/.exec(n[0])?.[1]:t?.replace(/[\s()]/g,d=>`%${d.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`),c=d=>{let p=s===void 0?void 0:s+o.slice(d).filter(Boolean).length;return[`<!-- skyramp-testbot-cut:${p??"?"} -->`,_e().staged.descriptionCut(r,p,a)].join(`
|
|
350
350
|
`)};for(let d=i.length;d>=1;d--){let p=i.slice(0,d),h=[...p,...n9e(p),"",c(d)].join(`
|
|
351
351
|
`);if(h.length<=r)return h}let l=["",...n9e(i.slice(0,1)),"",c(1)].join(`
|
|
352
|
-
`),u="";for(let d of i[0]){if(u.length+d.length+l.length>r)break;u+=d}return(u+l).slice(0,r)}var i9e=18e4,N7t=5e3,eoe=100,_7t=8;function roe(e=process.env){let t=Fm(e.SYSTEM_COLLECTIONURI??""),r=e.SYSTEM_TEAMPROJECT,n=e.BUILD_BUILDID;return t&&r&&n?{server:t,project:r,buildId:n}:void 0}var $B=class{constructor(t){this.opts=t;this.log=t.log??(i=>console.log(i)),this.run=t.run??Wie,this.command=t.command??QB;let{server:r,project:n,buildId:s}=t.pipelineRun;this.runUrl=`${r}/${encodeURIComponent(n)}/_build/results?buildId=${encodeURIComponent(s)}`}opts;name="azure";supportsRemote=!0;runUrl;log;run;command;repositoryIds=new Map;repository(t=this.opts.repoSlug){return FB(t)}api(t){return LB(this.opts.pipelineRun.server,this.repository(t))}async rest(t,r,n,s){return UB({token:await this.opts.tokenProvider(),url:r,method:t,body:n,accept:s,fetch:this.opts.fetch})}prUrl(t,r){let n=this.repository(t);return`${this.opts.pipelineRun.server}/${encodeURIComponent(n.project)}/_git/${encodeURIComponent(n.name)}/pullrequest/${r}`}async activePr(t,r){let n=new URL(`${this.api(t)}/pullrequests`);return n.searchParams.set("searchCriteria.sourceRefName",`refs/heads/${r}`),n.searchParams.set("searchCriteria.status","active"),(await this.rest("GET",n.toString())).value?.find(i=>typeof i.pullRequestId=="number")}git(t,r,n=this.opts.repositoryPath){return this.run("git",t,{cwd:n,env:r})}async remoteGit(t,r){let n=await this.opts.tokenProvider();return this.git(t,{...process.env,GIT_TERMINAL_PROMPT:"0",...Uq(this.opts.pipelineRun.server,n)},r)}adoptCheckoutAuthHeader(t){}async admitRun(){return{admit:!0}}async resolveContext(){let t;try{let r=this.git(["rev-parse","--abbrev-ref","HEAD"]);r&&r!=="HEAD"&&(t=r)}catch{}return{repoSlug:this.opts.repoSlug,headBranch:t}}createProgressSink(){return tT(this.log)}async beginRun(){}watchRun(t){let r=!1,n=this.opts.watchSignals===!1?[]:["SIGTERM","SIGINT"],s=i=>{for(let o of n)process.removeListener(o,s);r||(r=!0,t("cancelled",`received ${i} (pipeline run cancelled or agent shutting down)`))};for(let i of n)process.on(i,s);return{stop:()=>{for(let i of n)process.removeListener(i,s)}}}stageArtifact(t,r,n){if(!/^[A-Za-z0-9._-]{1,200}$/.test(t))throw new Error(`"${t}" is not an artifact name`);let s=this.opts.stagingDir??ti.join(process.env.AGENT_TEMPDIRECTORY||toe.tmpdir(),"skyramp-artifacts"),i=ti.join(s,t);za.rmSync(i,{recursive:!0,force:!0});for(let o of r){let a=ti.relative(n,o);if(!a||a.startsWith("..")||ti.isAbsolute(a))throw new Error(`${o} is not under ${n}`);za.mkdirSync(ti.dirname(ti.join(i,a)),{recursive:!0}),za.copyFileSync(o,ti.join(i,a))}return this.command(Dx("artifact.upload",{containerfolder:t,artifactname:t},i)),i}async uploadArtifact(t,r,n){if(r.length)try{return this.stageArtifact(t,r,n),`${this.runUrl}&view=artifacts&pathAsName=false&type=publishedArtifacts`}catch(s){this.log(`[warn] could not upload artifact ${t}: ${os(s)}`);return}}async uploadRunFiles(t,r,n){return await this.uploadArtifact(t,r,n)!==void 0}async artifactStore(){let{server:t,project:r,buildId:n}=this.opts.pipelineRun,s=(i,o)=>`${t}/${encodeURIComponent(i)}/_apis/build/builds/${encodeURIComponent(o)}/artifacts`;return{uploadArtifact:async(i,o,a)=>{this.stageArtifact(i,o,a);let c=new URL(s(r,n));c.searchParams.set("artifactName",i);let l=Date.now()+(this.opts.artifactWaitMs??i9e);for(;;){let u=await this.rest("GET",c.toString()).catch(()=>{});if(typeof u?.id=="number")return{id:u.id};if(Date.now()>=l)throw new Error(`Azure DevOps listed no artifact ${i} within ${Math.round((this.opts.artifactWaitMs??i9e)/1e3)} s`);await new Promise(d=>setTimeout(d,this.opts.artifactPollMs??N7t))}},downloadArtifact:async(i,o)=>{let a=o?.path??za.mkdtempSync(ti.join(toe.tmpdir(),"skyramp-artifact-")),c=o?.findBy?.repositoryOwner,l=c?.includes("/")?c.slice(c.indexOf("/")+1):r,u=String(o?.findBy?.workflowRunId??n),p=(await this.rest("GET",s(l,u))).value?.find(w=>w.id===i),h=/^#\/(\d+)\/(.+)$/.exec(p?.resource?.data??"");if(!p||p.resource?.type?.toLowerCase()!=="container"||!h)throw new Error(`build ${u} has no artifact ${i} the engine can read`);let[,m,g]=h,y=new URL(`${t}/_apis/resources/Containers/${m}`);y.searchParams.set("itemPath",g),y.searchParams.set("api-version","7.1-preview.4");let A=await this.rest("GET",y.toString());for(let w of A.value??[]){if(w.itemType!=="file"||!w.path?.startsWith(`${g}/`))continue;let S=w.path.slice(g.length+1),v=ti.resolve(a,S);if(!v.startsWith(ti.resolve(a)+ti.sep))throw new Error(`the artifact names a path outside its place: ${w.path}`);let I=new URL(y.toString());I.searchParams.set("itemPath",w.path);let R=await this.rest("GET",I.toString(),void 0,"application/octet-stream");za.mkdirSync(ti.dirname(v),{recursive:!0}),za.writeFileSync(v,R)}return{downloadPath:a}}}}async publishTestsPr(t){let r=[],n={};return{...await this.publish(t,r,n),pushedCommits:r,...n.commit?{deliveredCommit:n.commit}:{}}}description(t){return s9e(za.readFileSync(t,"utf-8"),this.opts.reportUrl)}async publish(t,r,n){let s=t.repositoryPath,i=t.repoSlug??this.opts.repoSlug,o=(d,p,h,m=t.base)=>({action:"failed",pushed:h,base:m,url:"",failure:d,detail:p});try{this.api(i)}catch(d){return o("unknown",os(d),!1)}let a=["--force"];if(t.mode==="append"){let d=!1;try{d=!!(await this.remoteGit(["ls-remote","--heads",t.remote,t.branch],s)).trim()}catch{a=[]}if(d){try{await this.remoteGit(["fetch",t.remote,t.branch],s);let h=NB(m=>this.git(m,void 0,s),`${t.remote}/${t.branch}`);this.git(["checkout","-B",t.branch,`${t.remote}/${t.branch}`],void 0,s),this.git(["-c",`user.name=${pi}`,"-c",`user.email=${$o}`,"cherry-pick","--keep-redundant-commits",t.commitSha],void 0,s),Mm(m=>this.git(m,void 0,s),h)}catch(h){return _B(this.run,t),o("conflict",`append onto the existing tests branch failed (tests kept on the local branch): ${os(h)}`,!1)}let p=!1;try{this.git(["diff","--quiet",`${t.remote}/${t.branch}`,"HEAD"],void 0,s),p=!0}catch{p=!1}if(p)return this.markTestsPrUnchanged({branch:t.branch,repositoryPath:s,repoSlug:t.repoSlug,devPr:t.devPr});a=[]}}else{let d=await _q(p=>this.git(p,void 0,s),p=>this.remoteGit(p,s),t);if("conflict"in d)return o("conflict",d.conflict,!1);a=d.pushFlags}let c=async d=>{await this.remoteGit(["push",...d,t.remote,`HEAD:refs/heads/${t.branch}`],s),Pq(this.run,s,r,n)};try{await c(a)}catch(d){let p=os(d);return o(Nx.test(p)?"auth":"push",`push failed: ${p}`,!1)}let l=this.description(t.bodyFile),u=async d=>{let p=await this.activePr(i,t.branch);if(p?.pullRequestId!==void 0){let m=p.pullRequestId;return await this.rest("PATCH",`${this.api(i)}/pullrequests/${m}`,{title:t.title,description:l}),p.targetRefName&&p.targetRefName!==`refs/heads/${d}`&&await this.rest("PATCH",`${this.api(i)}/pullrequests/${m}`,{targetRefName:`refs/heads/${d}`}).catch(g=>this.log(`[warn] could not move tests PR ${m} to ${d}: ${os(g)}`)),t.mode!=="append"&&await this.noteReplaced(i,m,t,p.description,n.commit),{action:"updated",pushed:!0,base:d,url:this.prUrl(i,m)}}let h=await this.rest("POST",`${this.api(i)}/pullrequests`,{sourceRefName:`refs/heads/${t.branch}`,targetRefName:`refs/heads/${d}`,title:t.title,description:l});if(typeof h.pullRequestId!="number")throw new Error("Azure DevOps created no pull request");return{action:"created",pushed:!0,base:d,url:this.prUrl(i,h.pullRequestId)}};try{return await u(t.base)}catch(d){let p=os(d);return Nx.test(p)?o("auth",p,!0):await this.branchExists(i,t.base).catch(()=>!0)?o("unknown",p,!0):this.retarget(t,i,u,o,()=>c(Yie(t.branch,r)))}}async noteReplaced(t,r,n,s,i){let o=Rq({runUrl:n.runUrl,previousBody:s,commit:i});o&&await this.rest("POST",`${this.api(t)}/pullRequests/${r}/threads`,{comments:[{parentCommentId:0,content:o,commentType:1}],status:"closed"}).catch(a=>this.log(`[warn] could not comment on tests PR ${r}: ${os(a)}`))}async branchExists(t,r){let n=new URL(`${this.api(t)}/refs`);return n.searchParams.set("filter",`heads/${r}`),((await this.rest("GET",n.toString())).value??[]).some(i=>i.name===`refs/heads/${r}`)}async retarget(t,r,n,s,i){let o=t.devPr;if(t.mode==="append")return s("unknown",`the dev branch '${t.base}' no longer exists and append mode cannot re-cut the tests branch \u2014 re-run in replace mode`,!0);if(o==null)return s("unknown",`the base branch '${t.base}' no longer exists and no dev PR number is known to retarget from`,!0);let a=await this.rest("GET",`${this.api(r)}/pullrequests/${o}`).catch(()=>{}),c=a?.targetRefName?.replace(/^refs\/heads\//,"");if(a?.status!=="completed"||!c)return{action:"skipped",pushed:!0,base:t.base,url:"",detail:`the dev branch '${t.base}' no longer exists and PR ${o} is ${a?.status??"unknown"} (not completed) \u2014 nothing to target; tests are on branch ${t.branch}`};this.log(`[deliver] tests PR base '${t.base}' no longer exists (dev PR completed) \u2014 re-cutting onto '${c}'`);try{await this.remoteGit(["fetch",t.remote,c],t.repositoryPath),this.git(["checkout","-B",t.branch,`${t.remote}/${c}`],void 0,t.repositoryPath),this.git(["-c",`user.name=${pi}`,"-c",`user.email=${$o}`,"cherry-pick","--keep-redundant-commits",t.commitSha],void 0,t.repositoryPath),Mm(l=>this.git(l,void 0,t.repositoryPath),this.git(["rev-parse","HEAD^"],void 0,t.repositoryPath).trim())}catch(l){return _B(this.run,t),s("conflict",`re-cut onto '${c}' failed (tests kept on the local branch): ${os(l)}`,!0)}try{await i()}catch(l){return s("push",`push failed: ${os(l)}`,!1,c)}try{let l=await n(c);return{...l,action:"retargeted",retargetedAs:l.action==="updated"?"updated":"created"}}catch(l){return s("unknown",`re-cut onto '${c}' pushed, but PR create failed: ${os(l)}`,!0,c)}}async markTestsPrUnchanged(t){let r=t.repoSlug??this.opts.repoSlug,n=s=>({action:"skipped",pushed:!1,base:"",url:"",detail:s});try{let s=await this.activePr(r,t.branch);if(s?.pullRequestId===void 0)return n(`no open tests PR for ${t.branch} \u2014 nothing to annotate`);let i=t.devPr!=null?`PR ${t.devPr}`:"the dev branch",o=Qq(i)+Mq(s.description??""),a=s9e(o);return a.startsWith(DB)?(await this.rest("PATCH",`${this.api(r)}/pullrequests/${s.pullRequestId}`,{description:a}),{action:"unchanged",pushed:!1,base:(s.targetRefName??"").replace(/^refs\/heads\//,""),url:this.prUrl(r,s.pullRequestId),detail:"no new test changes this run \u2014 existing tests PR annotated"}):n("the tests PR description has no room for the banner")}catch(s){return n(`could not annotate the tests PR: ${ko(s)}`)}}async closeTestsPr(t){try{let r=await this.activePr(void 0,t.branch);if(r?.pullRequestId===void 0)return{closed:!1};let n=r.pullRequestId;return await this.rest("POST",`${this.api()}/pullRequests/${n}/threads`,{comments:[{parentCommentId:0,content:t.reason,commentType:1}],status:"closed"}),await this.rest("PATCH",`${this.api()}/pullrequests/${n}`,{status:"abandoned"}),{closed:!0,url:this.prUrl(void 0,n)}}catch(r){return this.log(`[warn] could not close the tests PR for ${t.branch}: ${ko(r)}`),{closed:!1}}}async endRun(){}async listCommitChecks(t){let r=await this.commitStatuses(t),n=await this.commitBuilds(t);if(!r&&!n)return;let s=[...r?[]:["commit statuses"],...n?[]:["pipeline builds"],...n?.mergeUnread?["the merge commits of pull request builds"]:[]];return{records:[...r??[],...n?.records??[]],...s.length?{unread:s}:{}}}async repositoryId(t){let r=this.repositoryIds.get(t);if(r)return r;let n=await this.rest("GET",this.api(t));if(!n.id)throw new Error("Azure DevOps gave no repository id");return this.repositoryIds.set(t,n.id),n.id}async commitStatuses(t){try{return((await this.rest("GET",`${this.api(t.repository)}/commits/${encodeURIComponent(t.revision)}/statuses?latestOnly=true`)).value??[]).filter(n=>n.context?.name).map(n=>({repository:t.repository,name:n.context?.genre?`${n.context.genre}/${n.context.name}`:n.context.name,headSha:t.revision,status:n.state==="pending"?"pending":"completed",conclusion:n.state==="pending"?null:n.state==="succeeded"?"success":n.state==="failed"?"failure":n.state==="notApplicable"?"neutral":n.state??null,url:n.targetUrl,summary:n.description}))}catch(r){this.log(`[warn] could not read commit statuses for ${t.repository}@${t.revision.slice(0,12)}: ${ko(r)}`);return}}async commitBuilds(t){try{let r=await this.repositoryId(t.repository),n=new URL(`${Fm(this.opts.pipelineRun.server)}/${encodeURIComponent(this.repository(t.repository).project)}/_apis/build/builds`);for(let[h,m]of Object.entries({repositoryId:r,repositoryType:"TfsGit",queryOrder:"queueTimeDescending",$top:String(eoe)}))n.searchParams.set(h,m);let s=await this.rest("GET",n.toString()),i=t.revision.toLowerCase(),o=new Set,a=s.value??[],c=h=>!h.triggerInfo?.["pr.sourceSha"]&&h.reason==="pullRequest"?h.sourceVersion:void 0,l=new Map;for(let h of a){let m=c(h);m&&!l.has(m)&&l.set(m,{build:h._links?.web?.href??h.definition?.name??m})}let u=[...l];await Promise.all(Array.from({length:Math.min(_7t,u.length)},async()=>{for(let h=u.shift();h;h=u.shift()){let[m,g]=h;try{let y=await this.rest("GET",`${this.api(t.repository)}/commits/${encodeURIComponent(m)}`);g.head=y.parents&&y.parents.length>1?y.parents[1]:m}catch(y){this.log(`[warn] could not read the merge commit of pull request build ${g.build}: ${ko(y)}`),g.failed=!0}}}));let d=new Set,p=[];for(let h of a){let m=h.definition?.name;if(!m||o.has(m))continue;let g=c(h);if(g&&l.get(g)?.failed&&d.add(m),(h.triggerInfo?.["pr.sourceSha"]??(g?l.get(g)?.head:h.sourceVersion))?.toLowerCase()!==i)continue;o.add(m);let A=h.status==="completed";p.push({repository:t.repository,name:m,headSha:t.revision,status:A?"completed":h.status==="notStarted"||h.status==="postponed"?"queued":"in_progress",conclusion:A?h.result==="succeeded"?"success":h.result==="failed"?"failure":h.result==="canceled"?"cancelled":h.result??null:null,url:h._links?.web?.href,summary:void 0})}return!p.length&&(s.value?.length??0)>=eoe&&this.log(`[warn] no build of ${t.repository}@${t.revision.slice(0,12)} among its newest ${eoe} builds`),{records:p,mergeUnread:d.size>0}}catch(r){this.log(`[warn] could not read pipeline builds for ${t.repository}@${t.revision.slice(0,12)}: ${ko(r)}`);return}}async commitContains(t){try{let r=new URL(`${this.api(t.repository)}/diffs/commits`);for(let[s,i]of Object.entries({baseVersion:t.ancestor,baseVersionType:"commit",targetVersion:t.descendant,targetVersionType:"commit",$top:"1"}))r.searchParams.set(s,i);let n=await this.rest("GET",r.toString());return n.commonCommit?n.commonCommit.toLowerCase()===t.ancestor.toLowerCase()?"contained":"not_contained":"unknown"}catch(r){return this.log(`[warn] could not compare ${t.repository} ${Rr(t.ancestor)}...${Rr(t.descendant)}: ${ko(r)}`),"unknown"}}};var P7t="7.1-preview.1",D7t=".azure-pipelines/skyramp-testbot-v3.yml";function bE(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}var O7t={INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN"};function a9e(e=process.env){if(bE(e))for(let[t,r]of Object.entries(O7t))!e[t]&&e[r]!==void 0&&(e[t]=e[r])}function c9e(e,t={}){let r=d=>{let p=e[d];if(!p)throw new Error(`${d} is not set; the V3 runner handshake needs it`);return p},n=Fm(e.SYSTEM_COLLECTIONURI??""),s=()=>Zie(r("SYSTEM_COLLECTIONURI")),i=e.SYSTEM_TEAMPROJECT,o=e.BUILD_REPOSITORY_NAME,a=e.BUILD_REPOSITORY_ID?.toLowerCase(),c=e.SYSTEM_ACCESSTOKEN,l=t.mask??(d=>X5e(d)),u=d=>async()=>{if(!d)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let p=new URL(d);if(p.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");p.searchParams.set("api-version",P7t);let h=await(t.fetch??fetch)(p.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${h.status}`);let m=(await h.json().catch(()=>({}))).oidcToken;if(typeof m!="string"||!m)throw new Error("Azure DevOps's OIDC token response carried no token");return l(m),m};return{runnerPlatform:bE(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:n,apiUrl:n,repository:a&&i&&o&&n?{id:a,slug:`${s()}/${i}/${o}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let d=r("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(d))throw new Error(`SYSTEM_STAGEATTEMPT is "${d}", not a positive whole number`);let p=r("SYSTEM_COLLECTIONID").toLowerCase();if(!aS.test(p))throw new Error(`SYSTEM_COLLECTIONID is "${p}", not a GUID`);let h=r("BUILD_REPOSITORY_ID").toLowerCase();if(!aS.test(h))throw new Error(`BUILD_REPOSITORY_ID is "${h}", not a GUID`);let m=[s(),r("SYSTEM_TEAMPROJECT"),r("SYSTEM_DEFINITIONID"),r("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:p,providerRepositoryId:h},providerRunId:m,providerRunAttempt:Number(d),workflowRef:`${D7t}@${r("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let d=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let p=u(d);return()=>p()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let d=u(e.SYSTEM_OIDCREQUESTURI);return{token:()=>d(),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(d){Lq(d)},cloneUrl(d){return r9e(n,Lq(d))},gitAuthEnv(d){return Uq(n,d)},async pullRequest(d,p,h){let m=await UB({token:await h.token(),url:`${LB(n,Lq(d))}/pullrequests/${p}`,fetch:h.fetch}),g=m.status==="completed";return{...typeof m.title=="string"?{title:m.title}:{},...typeof m.description=="string"?{body:m.description}:{},...typeof m.status=="string"?{merged:g}:{},...g&&typeof m.lastMergeCommit?.commitId=="string"?{mergeCommit:m.lastMergeCommit.commitId}:{},...g&&typeof m.lastMergeSourceCommit?.commitId=="string"?{mergedHead:m.lastMergeSourceCommit.commitId}:{}}},async commit(d,p,h){let m;try{m=LB(n,FB(d))}catch{return{lookup:"unknown"}}try{let g=await UB({token:await h.token(),url:`${m}/commits/${encodeURIComponent(p)}`,fetch:h.fetch});return typeof g.commitId=="string"?{sha:g.commitId}:{lookup:"missing"}}catch(g){return{lookup:g instanceof MB&&(g.status===404||g.status===400)?"missing":"unknown"}}}}}Wt();var Q7t=5e3,soe=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function M7t(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return En(t),`AUTHORIZATION: basic ${t}`}function l9e(e,t={}){let r=c=>{let l=e[c];if(!l)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return l},n=e.GITHUB_REPOSITORY_ID,s=e.GITHUB_REPOSITORY,i=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,l)=>l.fetch(c,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)});return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:i,apiUrl:o,repository:n&&s?{id:n,slug:s}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let c=r("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(c))throw new Error(`GITHUB_RUN_ATTEMPT is "${c}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:r("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:r("GITHUB_REPOSITORY_ID")},providerRunId:r("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:r("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=e.ACTIONS_ID_TOKEN_REQUEST_URL,l=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async u=>{if(!c||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let d=new URL(c);d.searchParams.set("audience",u);let p=await fetch(d,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!p.ok)throw new Error(`GitHub refused the OIDC token request: ${p.status}`);let h=(await p.json().catch(()=>({}))).value;if(typeof h!="string"||!h)throw new Error("GitHub's OIDC token response carried no token");return En(h),h}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>sye(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(c){for(let l of[c.namespace,c.name])if(!soe.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(c){return`${i}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${i}/.extraheader`,GIT_CONFIG_VALUE_0:M7t(c)}:{}},async pullRequest({namespace:c,name:l},u,d){if(![c,l].every(m=>soe.test(m)))throw new Error("the repository name is not valid");let p=await a(`${o}/repos/${c}/${l}/pulls/${u}`,d);if(!p.ok)throw new Error(`GitHub answered ${p.status}`);let h=await p.json();return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.body=="string"?{body:h.body}:{},...typeof h.merged=="boolean"?{merged:h.merged}:{},...h.merged===!0&&typeof h.merge_commit_sha=="string"?{mergeCommit:h.merge_commit_sha}:{},...h.merged===!0&&typeof h.head?.sha=="string"?{mergedHead:h.head.sha}:{}}},async commit(c,l,u){let[d,p,...h]=c.split("/");if(h.length||![d,p].every(m=>m!==void 0&&soe.test(m)))return{lookup:"unknown"};try{let m=await a(`${o}/repos/${d}/${p}/commits/${encodeURIComponent(l)}`,u);if(m.status===404||m.status===422)return{lookup:"missing"};if(!m.ok)return{lookup:"unknown"};let g=await m.json();return typeof g.sha=="string"?{sha:g.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(c,l){let u=await l(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(Q7t)});if(!u.ok&&u.status!==401)throw new Error(`GitHub answered ${u.status}`)}}}function fn(e=process.env){return bE(e)?c9e(e):l9e(e)}function u9e(e){if(e!=="staged")return`This Testbot engine runs only the staged pipeline, not "${e}". Set the pipeline input to "staged", or pin skyramp/testbot@v0.11 for the classic pipeline.`}var ein=["local","github","azure"];function d9e(e,t,r=fn()){if(r.runnerPlatform!=="azure")return new PB(e);let n=roe();if(!t||!n||!e.repoSlug||!e.tokenProvider)throw new Error("On Azure Pipelines, Testbot runs only the Validation Runs and SUT setups the Skyramp app starts: the step needs INPUT_SKYRAMPRUNID and the job's predefined variables.");return new $B({repositoryPath:e.repositoryPath,repoSlug:e.repoSlug,pipelineRun:n,tokenProvider:e.tokenProvider,log:e.log,reportUrl:t})}var h9e=require("child_process"),sf=Y(require("fs")),Va=Y(require("path")),m9e=(e,t)=>(0,h9e.execFileSync)("git",["-c","safe.directory=*",...Fi,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"],env:Bt()}),g9e="^(http(\\..*)?\\.extraheader|core\\.sshcommand)$",U7t="core.sshcommand",$q=e=>e instanceof Error?e.message.split(`
|
|
352
|
+
`),u="";for(let d of i[0]){if(u.length+d.length+l.length>r)break;u+=d}return(u+l).slice(0,r)}var i9e=18e4,N7t=5e3,eoe=100,_7t=8;function roe(e=process.env){let t=Fm(e.SYSTEM_COLLECTIONURI??""),r=e.SYSTEM_TEAMPROJECT,n=e.BUILD_BUILDID;return t&&r&&n?{server:t,project:r,buildId:n}:void 0}var $B=class{constructor(t){this.opts=t;this.log=t.log??(i=>console.log(i)),this.run=t.run??Wie,this.command=t.command??QB;let{server:r,project:n,buildId:s}=t.pipelineRun;this.runUrl=`${r}/${encodeURIComponent(n)}/_build/results?buildId=${encodeURIComponent(s)}`}opts;name="azure";supportsRemote=!0;runUrl;log;run;command;repositoryIds=new Map;repository(t=this.opts.repoSlug){return FB(t)}api(t){return LB(this.opts.pipelineRun.server,this.repository(t))}async rest(t,r,n,s){return UB({token:await this.opts.tokenProvider(),url:r,method:t,body:n,accept:s,fetch:this.opts.fetch})}prUrl(t,r){let n=this.repository(t);return`${this.opts.pipelineRun.server}/${encodeURIComponent(n.project)}/_git/${encodeURIComponent(n.name)}/pullrequest/${r}`}async activePr(t,r){let n=new URL(`${this.api(t)}/pullrequests`);return n.searchParams.set("searchCriteria.sourceRefName",`refs/heads/${r}`),n.searchParams.set("searchCriteria.status","active"),(await this.rest("GET",n.toString())).value?.find(i=>typeof i.pullRequestId=="number")}git(t,r,n=this.opts.repositoryPath){return this.run("git",t,{cwd:n,env:r})}async remoteGit(t,r){let n=await this.opts.tokenProvider();return this.git(t,{...process.env,GIT_TERMINAL_PROMPT:"0",...Uq(this.opts.pipelineRun.server,n)},r)}adoptCheckoutAuthHeader(t){}async admitRun(){return{admit:!0}}async resolveContext(){let t;try{let r=this.git(["rev-parse","--abbrev-ref","HEAD"]);r&&r!=="HEAD"&&(t=r)}catch{}return{repoSlug:this.opts.repoSlug,headBranch:t}}createProgressSink(){return tT(this.log)}async beginRun(){}watchRun(t){let r=!1,n=this.opts.watchSignals===!1?[]:["SIGTERM","SIGINT"],s=i=>{for(let o of n)process.removeListener(o,s);r||(r=!0,t("cancelled",`received ${i} (pipeline run cancelled or agent shutting down)`))};for(let i of n)process.on(i,s);return{stop:()=>{for(let i of n)process.removeListener(i,s)}}}stageArtifact(t,r,n){if(!/^[A-Za-z0-9._-]{1,200}$/.test(t))throw new Error(`"${t}" is not an artifact name`);let s=this.opts.stagingDir??ti.join(process.env.AGENT_TEMPDIRECTORY||toe.tmpdir(),"skyramp-artifacts"),i=ti.join(s,t);za.rmSync(i,{recursive:!0,force:!0});for(let o of r){let a=ti.relative(n,o);if(!a||a.startsWith("..")||ti.isAbsolute(a))throw new Error(`${o} is not under ${n}`);za.mkdirSync(ti.dirname(ti.join(i,a)),{recursive:!0}),za.copyFileSync(o,ti.join(i,a))}return this.command(Dx("artifact.upload",{containerfolder:t,artifactname:t},i)),i}async uploadArtifact(t,r,n){if(r.length)try{return this.stageArtifact(t,r,n),`${this.runUrl}&view=artifacts&pathAsName=false&type=publishedArtifacts`}catch(s){this.log(`[warn] could not upload artifact ${t}: ${os(s)}`);return}}async uploadRunFiles(t,r,n){return await this.uploadArtifact(t,r,n)!==void 0}async artifactStore(){let{server:t,project:r,buildId:n}=this.opts.pipelineRun,s=(i,o)=>`${t}/${encodeURIComponent(i)}/_apis/build/builds/${encodeURIComponent(o)}/artifacts`;return{uploadArtifact:async(i,o,a)=>{this.stageArtifact(i,o,a);let c=new URL(s(r,n));c.searchParams.set("artifactName",i);let l=Date.now()+(this.opts.artifactWaitMs??i9e);for(;;){let u=await this.rest("GET",c.toString()).catch(()=>{});if(typeof u?.id=="number")return{id:u.id};if(Date.now()>=l)throw new Error(`Azure DevOps listed no artifact ${i} within ${Math.round((this.opts.artifactWaitMs??i9e)/1e3)} s`);await new Promise(d=>setTimeout(d,this.opts.artifactPollMs??N7t))}},downloadArtifact:async(i,o)=>{let a=o?.path??za.mkdtempSync(ti.join(toe.tmpdir(),"skyramp-artifact-")),c=o?.findBy?.repositoryOwner,l=c?.includes("/")?c.slice(c.indexOf("/")+1):r,u=String(o?.findBy?.workflowRunId??n),p=(await this.rest("GET",s(l,u))).value?.find(w=>w.id===i),h=/^#\/(\d+)\/(.+)$/.exec(p?.resource?.data??"");if(!p||p.resource?.type?.toLowerCase()!=="container"||!h)throw new Error(`build ${u} has no artifact ${i} the engine can read`);let[,m,g]=h,y=new URL(`${t}/_apis/resources/Containers/${m}`);y.searchParams.set("itemPath",g),y.searchParams.set("api-version","7.1-preview.4");let A=await this.rest("GET",y.toString());for(let w of A.value??[]){if(w.itemType!=="file"||!w.path?.startsWith(`${g}/`))continue;let S=w.path.slice(g.length+1),v=ti.resolve(a,S);if(!v.startsWith(ti.resolve(a)+ti.sep))throw new Error(`the artifact names a path outside its place: ${w.path}`);let I=new URL(y.toString());I.searchParams.set("itemPath",w.path);let R=await this.rest("GET",I.toString(),void 0,"application/octet-stream");za.mkdirSync(ti.dirname(v),{recursive:!0}),za.writeFileSync(v,R)}return{downloadPath:a}}}}async publishTestsPr(t){let r=[],n={};return{...await this.publish(t,r,n),pushedCommits:r,...n.commit?{deliveredCommit:n.commit}:{}}}description(t){return s9e(za.readFileSync(t,"utf-8"),this.opts.reportUrl)}async publish(t,r,n){let s=t.repositoryPath,i=t.repoSlug??this.opts.repoSlug,o=(d,p,h,m=t.base)=>({action:"failed",pushed:h,base:m,url:"",failure:d,detail:p});try{this.api(i)}catch(d){return o("unknown",os(d),!1)}let a=["--force"];if(t.mode==="append"){let d=!1;try{d=!!(await this.remoteGit(["ls-remote","--heads",t.remote,t.branch],s)).trim()}catch{a=[]}if(d){try{await this.remoteGit(["fetch",t.remote,t.branch],s);let h=NB(m=>this.git(m,void 0,s),`${t.remote}/${t.branch}`);this.git(["checkout","-B",t.branch,`${t.remote}/${t.branch}`],void 0,s),this.git(["-c",`user.name=${pi}`,"-c",`user.email=${$o}`,"cherry-pick","--keep-redundant-commits",t.commitSha],void 0,s),Mm(m=>this.git(m,void 0,s),h)}catch(h){return _B(this.run,t),o("conflict",`append onto the existing tests branch failed (tests kept on the local branch): ${os(h)}`,!1)}let p=!1;try{this.git(["diff","--quiet",`${t.remote}/${t.branch}`,"HEAD"],void 0,s),p=!0}catch{p=!1}if(p)return this.markTestsPrUnchanged({branch:t.branch,repositoryPath:s,repoSlug:t.repoSlug,devPr:t.devPr});a=[]}}else{let d=await _q(p=>this.git(p,void 0,s),p=>this.remoteGit(p,s),t);if("conflict"in d)return o("conflict",d.conflict,!1);a=d.pushFlags}let c=async d=>{await this.remoteGit(["push",...d,t.remote,`HEAD:refs/heads/${t.branch}`],s),Pq(this.run,s,r,n)};try{await c(a)}catch(d){let p=os(d);return o(Nx.test(p)?"auth":"push",`push failed: ${p}`,!1)}let l=this.description(t.bodyFile),u=async d=>{let p=await this.activePr(i,t.branch);if(p?.pullRequestId!==void 0){let m=p.pullRequestId;return await this.rest("PATCH",`${this.api(i)}/pullrequests/${m}`,{title:t.title,description:l}),p.targetRefName&&p.targetRefName!==`refs/heads/${d}`&&await this.rest("PATCH",`${this.api(i)}/pullrequests/${m}`,{targetRefName:`refs/heads/${d}`}).catch(g=>this.log(`[warn] could not move tests PR ${m} to ${d}: ${os(g)}`)),t.mode!=="append"&&await this.noteReplaced(i,m,t,p.description,n.commit),{action:"updated",pushed:!0,base:d,url:this.prUrl(i,m)}}let h=await this.rest("POST",`${this.api(i)}/pullrequests`,{sourceRefName:`refs/heads/${t.branch}`,targetRefName:`refs/heads/${d}`,title:t.title,description:l});if(typeof h.pullRequestId!="number")throw new Error("Azure DevOps created no pull request");return{action:"created",pushed:!0,base:d,url:this.prUrl(i,h.pullRequestId)}};try{return await u(t.base)}catch(d){let p=os(d);return Nx.test(p)?o("auth",p,!0):await this.branchExists(i,t.base).catch(()=>!0)?o("unknown",p,!0):this.retarget(t,i,u,o,()=>c(Yie(t.branch,r)))}}async noteReplaced(t,r,n,s,i){let o=Rq({runUrl:n.runUrl,previousBody:s,commit:i});o&&await this.rest("POST",`${this.api(t)}/pullRequests/${r}/threads`,{comments:[{parentCommentId:0,content:o,commentType:1}],status:"closed"}).catch(a=>this.log(`[warn] could not comment on tests PR ${r}: ${os(a)}`))}async branchExists(t,r){let n=new URL(`${this.api(t)}/refs`);return n.searchParams.set("filter",`heads/${r}`),((await this.rest("GET",n.toString())).value??[]).some(i=>i.name===`refs/heads/${r}`)}async retarget(t,r,n,s,i){let o=t.devPr;if(t.mode==="append")return s("unknown",`the dev branch '${t.base}' no longer exists and append mode cannot re-cut the tests branch \u2014 re-run in replace mode`,!0);if(o==null)return s("unknown",`the base branch '${t.base}' no longer exists and no dev PR number is known to retarget from`,!0);let a=await this.rest("GET",`${this.api(r)}/pullrequests/${o}`).catch(()=>{}),c=a?.targetRefName?.replace(/^refs\/heads\//,"");if(a?.status!=="completed"||!c)return{action:"skipped",pushed:!0,base:t.base,url:"",detail:`the dev branch '${t.base}' no longer exists and PR ${o} is ${a?.status??"unknown"} (not completed) \u2014 nothing to target; tests are on branch ${t.branch}`};this.log(`[deliver] tests PR base '${t.base}' no longer exists (dev PR completed) \u2014 re-cutting onto '${c}'`);try{await this.remoteGit(["fetch",t.remote,c],t.repositoryPath),this.git(["checkout","-B",t.branch,`${t.remote}/${c}`],void 0,t.repositoryPath),this.git(["-c",`user.name=${pi}`,"-c",`user.email=${$o}`,"cherry-pick","--keep-redundant-commits",t.commitSha],void 0,t.repositoryPath),Mm(l=>this.git(l,void 0,t.repositoryPath),this.git(["rev-parse","HEAD^"],void 0,t.repositoryPath).trim())}catch(l){return _B(this.run,t),s("conflict",`re-cut onto '${c}' failed (tests kept on the local branch): ${os(l)}`,!0)}try{await i()}catch(l){return s("push",`push failed: ${os(l)}`,!1,c)}try{let l=await n(c);return{...l,action:"retargeted",retargetedAs:l.action==="updated"?"updated":"created"}}catch(l){return s("unknown",`re-cut onto '${c}' pushed, but PR create failed: ${os(l)}`,!0,c)}}async markTestsPrUnchanged(t){let r=t.repoSlug??this.opts.repoSlug,n=s=>({action:"skipped",pushed:!1,base:"",url:"",detail:s});try{let s=await this.activePr(r,t.branch);if(s?.pullRequestId===void 0)return n(`no open tests PR for ${t.branch} \u2014 nothing to annotate`);let i=t.devPr!=null?`PR ${t.devPr}`:"the dev branch",o=Qq(i)+Mq(s.description??""),a=s9e(o);return a.startsWith(DB)?(await this.rest("PATCH",`${this.api(r)}/pullrequests/${s.pullRequestId}`,{description:a}),{action:"unchanged",pushed:!1,base:(s.targetRefName??"").replace(/^refs\/heads\//,""),url:this.prUrl(r,s.pullRequestId),detail:"no new test changes this run \u2014 existing tests PR annotated"}):n("the tests PR description has no room for the banner")}catch(s){return n(`could not annotate the tests PR: ${ko(s)}`)}}async closeTestsPr(t){try{let r=await this.activePr(void 0,t.branch);if(r?.pullRequestId===void 0)return{closed:!1};let n=r.pullRequestId;return await this.rest("POST",`${this.api()}/pullRequests/${n}/threads`,{comments:[{parentCommentId:0,content:t.reason,commentType:1}],status:"closed"}),await this.rest("PATCH",`${this.api()}/pullrequests/${n}`,{status:"abandoned"}),{closed:!0,url:this.prUrl(void 0,n)}}catch(r){return this.log(`[warn] could not close the tests PR for ${t.branch}: ${ko(r)}`),{closed:!1}}}async endRun(){}async listCommitChecks(t){let r=await this.commitStatuses(t),n=await this.commitBuilds(t);if(!r&&!n)return;let s=[...r?[]:["commit statuses"],...n?[]:["pipeline builds"],...n?.mergeUnread?["the merge commits of pull request builds"]:[]];return{records:[...r??[],...n?.records??[]],...s.length?{unreadSources:s}:{}}}async repositoryId(t){let r=this.repositoryIds.get(t);if(r)return r;let n=await this.rest("GET",this.api(t));if(!n.id)throw new Error("Azure DevOps gave no repository id");return this.repositoryIds.set(t,n.id),n.id}async commitStatuses(t){try{return((await this.rest("GET",`${this.api(t.repository)}/commits/${encodeURIComponent(t.revision)}/statuses?latestOnly=true`)).value??[]).filter(n=>n.context?.name).map(n=>({repository:t.repository,name:n.context?.genre?`${n.context.genre}/${n.context.name}`:n.context.name,headSha:t.revision,status:n.state==="pending"?"pending":"completed",conclusion:n.state==="pending"?null:n.state==="succeeded"?"success":n.state==="failed"?"failure":n.state==="notApplicable"?"neutral":n.state??null,url:n.targetUrl,summary:n.description}))}catch(r){this.log(`[warn] could not read commit statuses for ${t.repository}@${t.revision.slice(0,12)}: ${ko(r)}`);return}}async commitBuilds(t){try{let r=await this.repositoryId(t.repository),n=new URL(`${Fm(this.opts.pipelineRun.server)}/${encodeURIComponent(this.repository(t.repository).project)}/_apis/build/builds`);for(let[h,m]of Object.entries({repositoryId:r,repositoryType:"TfsGit",queryOrder:"queueTimeDescending",$top:String(eoe)}))n.searchParams.set(h,m);let s=await this.rest("GET",n.toString()),i=t.revision.toLowerCase(),o=new Set,a=s.value??[],c=h=>!h.triggerInfo?.["pr.sourceSha"]&&h.reason==="pullRequest"?h.sourceVersion:void 0,l=new Map;for(let h of a){let m=c(h);m&&!l.has(m)&&l.set(m,{build:h._links?.web?.href??h.definition?.name??m})}let u=[...l];await Promise.all(Array.from({length:Math.min(_7t,u.length)},async()=>{for(let h=u.shift();h;h=u.shift()){let[m,g]=h;try{let y=await this.rest("GET",`${this.api(t.repository)}/commits/${encodeURIComponent(m)}`);g.head=y.parents&&y.parents.length>1?y.parents[1]:m}catch(y){this.log(`[warn] could not read the merge commit of pull request build ${g.build}: ${ko(y)}`),g.failed=!0}}}));let d=new Set,p=[];for(let h of a){let m=h.definition?.name;if(!m||o.has(m))continue;let g=c(h);if(g&&l.get(g)?.failed&&d.add(m),(h.triggerInfo?.["pr.sourceSha"]??(g?l.get(g)?.head:h.sourceVersion))?.toLowerCase()!==i)continue;o.add(m);let A=h.status==="completed";p.push({repository:t.repository,name:m,headSha:t.revision,status:A?"completed":h.status==="notStarted"||h.status==="postponed"?"queued":"in_progress",conclusion:A?h.result==="succeeded"?"success":h.result==="failed"?"failure":h.result==="canceled"?"cancelled":h.result??null:null,url:h._links?.web?.href,summary:void 0})}return!p.length&&(s.value?.length??0)>=eoe&&this.log(`[warn] no build of ${t.repository}@${t.revision.slice(0,12)} among its newest ${eoe} builds`),{records:p,mergeUnread:d.size>0}}catch(r){this.log(`[warn] could not read pipeline builds for ${t.repository}@${t.revision.slice(0,12)}: ${ko(r)}`);return}}async commitContains(t){try{let r=new URL(`${this.api(t.repository)}/diffs/commits`);for(let[s,i]of Object.entries({baseVersion:t.ancestor,baseVersionType:"commit",targetVersion:t.descendant,targetVersionType:"commit",$top:"1"}))r.searchParams.set(s,i);let n=await this.rest("GET",r.toString());return n.commonCommit?n.commonCommit.toLowerCase()===t.ancestor.toLowerCase()?"contained":"not_contained":"unknown"}catch(r){return this.log(`[warn] could not compare ${t.repository} ${Rr(t.ancestor)}...${Rr(t.descendant)}: ${ko(r)}`),"unknown"}}};var P7t="7.1-preview.1",D7t=".azure-pipelines/skyramp-testbot-v3.yml";function bE(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}var O7t={INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN"};function a9e(e=process.env){if(bE(e))for(let[t,r]of Object.entries(O7t))!e[t]&&e[r]!==void 0&&(e[t]=e[r])}function c9e(e,t={}){let r=d=>{let p=e[d];if(!p)throw new Error(`${d} is not set; the V3 runner handshake needs it`);return p},n=Fm(e.SYSTEM_COLLECTIONURI??""),s=()=>Zie(r("SYSTEM_COLLECTIONURI")),i=e.SYSTEM_TEAMPROJECT,o=e.BUILD_REPOSITORY_NAME,a=e.BUILD_REPOSITORY_ID?.toLowerCase(),c=e.SYSTEM_ACCESSTOKEN,l=t.mask??(d=>X5e(d)),u=d=>async()=>{if(!d)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let p=new URL(d);if(p.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");p.searchParams.set("api-version",P7t);let h=await(t.fetch??fetch)(p.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${h.status}`);let m=(await h.json().catch(()=>({}))).oidcToken;if(typeof m!="string"||!m)throw new Error("Azure DevOps's OIDC token response carried no token");return l(m),m};return{runnerPlatform:bE(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:n,apiUrl:n,repository:a&&i&&o&&n?{id:a,slug:`${s()}/${i}/${o}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let d=r("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(d))throw new Error(`SYSTEM_STAGEATTEMPT is "${d}", not a positive whole number`);let p=r("SYSTEM_COLLECTIONID").toLowerCase();if(!aS.test(p))throw new Error(`SYSTEM_COLLECTIONID is "${p}", not a GUID`);let h=r("BUILD_REPOSITORY_ID").toLowerCase();if(!aS.test(h))throw new Error(`BUILD_REPOSITORY_ID is "${h}", not a GUID`);let m=[s(),r("SYSTEM_TEAMPROJECT"),r("SYSTEM_DEFINITIONID"),r("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:p,providerRepositoryId:h},providerRunId:m,providerRunAttempt:Number(d),workflowRef:`${D7t}@${r("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let d=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let p=u(d);return()=>p()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let d=u(e.SYSTEM_OIDCREQUESTURI);return{token:()=>d(),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(d){Lq(d)},cloneUrl(d){return r9e(n,Lq(d))},gitAuthEnv(d){return Uq(n,d)},async pullRequest(d,p,h){let m=await UB({token:await h.token(),url:`${LB(n,Lq(d))}/pullrequests/${p}`,fetch:h.fetch}),g=m.status==="completed";return{...typeof m.title=="string"?{title:m.title}:{},...typeof m.description=="string"?{body:m.description}:{},...typeof m.status=="string"?{merged:g}:{},...g&&typeof m.lastMergeCommit?.commitId=="string"?{mergeCommit:m.lastMergeCommit.commitId}:{},...g&&typeof m.lastMergeSourceCommit?.commitId=="string"?{mergedHead:m.lastMergeSourceCommit.commitId}:{}}},async commit(d,p,h){let m;try{m=LB(n,FB(d))}catch{return{lookup:"unknown"}}try{let g=await UB({token:await h.token(),url:`${m}/commits/${encodeURIComponent(p)}`,fetch:h.fetch});return typeof g.commitId=="string"?{sha:g.commitId}:{lookup:"missing"}}catch(g){return{lookup:g instanceof MB&&(g.status===404||g.status===400)?"missing":"unknown"}}}}}Wt();var Q7t=5e3,soe=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function M7t(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return En(t),`AUTHORIZATION: basic ${t}`}function l9e(e,t={}){let r=c=>{let l=e[c];if(!l)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return l},n=e.GITHUB_REPOSITORY_ID,s=e.GITHUB_REPOSITORY,i=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,l)=>l.fetch(c,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)});return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:i,apiUrl:o,repository:n&&s?{id:n,slug:s}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let c=r("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(c))throw new Error(`GITHUB_RUN_ATTEMPT is "${c}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:r("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:r("GITHUB_REPOSITORY_ID")},providerRunId:r("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:r("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=e.ACTIONS_ID_TOKEN_REQUEST_URL,l=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async u=>{if(!c||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let d=new URL(c);d.searchParams.set("audience",u);let p=await fetch(d,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!p.ok)throw new Error(`GitHub refused the OIDC token request: ${p.status}`);let h=(await p.json().catch(()=>({}))).value;if(typeof h!="string"||!h)throw new Error("GitHub's OIDC token response carried no token");return En(h),h}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>sye(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(c){for(let l of[c.namespace,c.name])if(!soe.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(c){return`${i}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${i}/.extraheader`,GIT_CONFIG_VALUE_0:M7t(c)}:{}},async pullRequest({namespace:c,name:l},u,d){if(![c,l].every(m=>soe.test(m)))throw new Error("the repository name is not valid");let p=await a(`${o}/repos/${c}/${l}/pulls/${u}`,d);if(!p.ok)throw new Error(`GitHub answered ${p.status}`);let h=await p.json();return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.body=="string"?{body:h.body}:{},...typeof h.merged=="boolean"?{merged:h.merged}:{},...h.merged===!0&&typeof h.merge_commit_sha=="string"?{mergeCommit:h.merge_commit_sha}:{},...h.merged===!0&&typeof h.head?.sha=="string"?{mergedHead:h.head.sha}:{}}},async commit(c,l,u){let[d,p,...h]=c.split("/");if(h.length||![d,p].every(m=>m!==void 0&&soe.test(m)))return{lookup:"unknown"};try{let m=await a(`${o}/repos/${d}/${p}/commits/${encodeURIComponent(l)}`,u);if(m.status===404||m.status===422)return{lookup:"missing"};if(!m.ok)return{lookup:"unknown"};let g=await m.json();return typeof g.sha=="string"?{sha:g.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(c,l){let u=await l(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(Q7t)});if(!u.ok&&u.status!==401)throw new Error(`GitHub answered ${u.status}`)}}}function fn(e=process.env){return bE(e)?c9e(e):l9e(e)}function u9e(e){if(e!=="staged")return`This Testbot engine runs only the staged pipeline, not "${e}". Set the pipeline input to "staged", or pin skyramp/testbot@v0.11 for the classic pipeline.`}var ein=["local","github","azure"];function d9e(e,t,r=fn()){if(r.runnerPlatform!=="azure")return new PB(e);let n=roe();if(!t||!n||!e.repoSlug||!e.tokenProvider)throw new Error("On Azure Pipelines, Testbot runs only the Validation Runs and SUT setups the Skyramp app starts: the step needs INPUT_SKYRAMPRUNID and the job's predefined variables.");return new $B({repositoryPath:e.repositoryPath,repoSlug:e.repoSlug,pipelineRun:n,tokenProvider:e.tokenProvider,log:e.log,reportUrl:t})}var h9e=require("child_process"),sf=Y(require("fs")),Va=Y(require("path")),m9e=(e,t)=>(0,h9e.execFileSync)("git",["-c","safe.directory=*",...Fi,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"],env:Bt()}),g9e="^(http(\\..*)?\\.extraheader|core\\.sshcommand)$",U7t="core.sshcommand",$q=e=>e instanceof Error?e.message.split(`
|
|
353
353
|
`)[0]:String(e);function $7t(e){let t=e.split("\0"),r=[];for(let n=0;n+2<t.length;n+=3)r.push({scope:t[n],origin:t[n+1],key:t[n+2]});return r}function p9e(e,t){let r;try{r=t(["config","--show-scope","--show-origin","--name-only","-z","--get-regexp",g9e],e)}catch(i){if(i.status===1)return[];throw new Error(`could not list persisted git credentials in ${e}: ${$q(i)}`)}let n=[],s=new Set;for(let{scope:i,origin:o,key:a}of $7t(r)){if(i!=="local"&&i!=="worktree"||!o.startsWith("file:")||!a)continue;let c=o.slice(5),l=Va.isAbsolute(c)?c:Va.join(e,c);s.has(`${a}\0${l}`)||(s.add(`${a}\0${l}`),n.push({key:a,file:l}))}return n}function A9e(e,t=m9e,r){let n=q7t(e,t);return[...f9e(e,t,r),...n.flatMap(s=>f9e(s,t))]}function q7t(e,t){let r=!1;try{r=t(["rev-parse","--is-inside-work-tree"],e).trim()==="true"}catch{r=!1}if(!r){if(sf.existsSync(Va.join(e,".git")))throw new Error(`could not read the git repository at ${e}`);return[]}let n;try{n=t(["submodule","foreach","--recursive","--quiet",'printf "%s\\0" "$displaypath"'],e)}catch(s){throw new Error(`could not list the submodules of ${e}: ${$q(s)}`)}return n.split("\0").filter(s=>s.length>0).map(s=>Va.resolve(e,s))}function G7t(e,t=process.env.RUNNER_TEMP){if(!t)return;let r=/(?:^|\s)-i\s*(?:"([^"]+)"|'([^']+)'|(\S+))/.exec(e),n=r?.[1]??r?.[2]??r?.[3];if(!n)return;let s=Va.resolve(n.replace(/^\$\{?RUNNER_TEMP\}?/,t)),i=Va.resolve(t);return s.startsWith(i+Va.sep)?s:void 0}function f9e(e,t,r){let n=[],s=[],i=[];for(let{key:a,file:c}of p9e(e,t)){let l=a===U7t;if(l||r)try{for(let u of t(["config","--file",c,"--get-all",a],e).split(`
|
|
354
354
|
`).filter(Boolean)){l||r?.(u);let d=l?G7t(u):void 0;d&&s.push(d)}}catch{l&&i.push(`${a} (${c})`)}try{t(["config","--file",c,"--unset-all",a],e),n.push(`${a} (${c})`)}catch{}}for(let a of new Set(s))try{sf.rmSync(a,{force:!0}),n.push(`ssh key (${a})`)}catch{}let o=[...p9e(e,t).map(a=>`${a.key} (${a.file})`),...[...new Set(s)].filter(a=>sf.existsSync(a)).map(a=>`ssh key (${a})`),...i.map(a=>`${a}: could not read which key it names`)];if(o.length)throw new Error(`could not remove the persisted git credential from ${o.join(", ")}`);return n}function y9e(e=process.env.RUNNER_TEMP,t=m9e){if(!e||!sf.existsSync(e))return[];let r=[],n=[];for(let s of sf.readdirSync(e)){if(!/^git-credentials-.*\.config$/.test(s))continue;let i=Va.join(e,s),o=()=>{try{return t(["config","--file",i,"--name-only","-z","--get-regexp",g9e],e).split("\0").filter(Boolean)}catch(a){if(a.status===1)return[];throw new Error(`could not read the checkout credential file ${i}: ${$q(a)}`)}};for(let a of new Set(o()))try{t(["config","--file",i,"--unset-all",a],e),r.push(`${a} (${i})`)}catch{}n.push(...o().map(a=>`${a} (${i})`))}if(n.length)throw new Error(`could not remove the persisted git credential from ${n.join(", ")}`);return r}function E9e(e){let t=[],r=n=>{let s;try{s=sf.readdirSync(n,{withFileTypes:!0})}catch(i){throw new Error(`could not search ${n} for checkouts: ${$q(i)}`)}s.some(i=>i.name===".git")&&t.push(n);for(let i of s)i.isDirectory()&&i.name!==".git"&&i.name!=="node_modules"&&r(Va.join(n,i.name))};return r(e),t}var Wc=Y(require("fs")),Zi=Y(require("path"));var xd=Y(require("fs")),w9e=Y(require("path")),ioe=Y(require("crypto"));function qq(){return new Date().toISOString()}function j7t(){return{runId:ioe.randomUUID(),createdAt:qq(),updatedAt:qq(),stages:{}}}function Gq(e,t={}){if(!t.fresh&&xd.existsSync(e))try{let r=JSON.parse(xd.readFileSync(e,"utf-8"));if(r&&typeof r=="object"&&r.stages&&typeof r.stages=="object"&&!Array.isArray(r.stages))return r;t.onWarn?.(`State file ${e} malformed \u2014 starting fresh`)}catch(r){t.onWarn?.(`State file ${e} unreadable (${r instanceof Error?r.message:String(r)}) \u2014 starting fresh`)}return j7t()}function vd(e,t){t.updatedAt=qq(),xd.mkdirSync(w9e.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${ioe.randomUUID()}.tmp`;xd.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
355
355
|
`),xd.renameSync(r,e)}function ri(e,t,r){e.stages[t]={...r,updatedAt:qq()}}var qB="review",jq="judge";var Id=Y(require("fs")),Mx=Y(require("path"));var $c=Y(require("fs")),Lm=Y(require("path"));var ooe="change-inputs",H7t=(e,t)=>`${t}-${e.replace(/[^\w.-]+/g,r=>r==="/"?"__":"-")}.md`;function b9e(e){return[...(e.pullRequests??[]).map(t=>({label:`${t.repository}#${t.number}`,body:t.body?.trim()??""})),...(e.relatedRepos??[]).map(t=>({label:t.slug,body:t.prDescription?.trim()??""}))].map((t,r)=>({...t,file:H7t(t.label,r)})).filter(t=>t.body.length>hp)}function S9e(e,t,r){let n=Lm.join(t,ooe);$c.rmSync(n,{recursive:!0,force:!0}),$c.mkdirSync(n,{recursive:!0}),$c.writeFileSync(Lm.join(n,fp),r,{mode:292});for(let s of b9e(e))$c.writeFileSync(Lm.join(n,s.file),`${s.body}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skyramp/testbot-core",
|
|
3
|
-
"version": "0.13.0-v3.
|
|
3
|
+
"version": "0.13.0-v3.238",
|
|
4
4
|
"description": "Skyramp Testbot engine: AI-powered deterministic test generation, execution and maintenance",
|
|
5
5
|
"main": "dist/main.js",
|
|
6
6
|
"//files": "An explicit allowlist, never a glob. `dist/` is gitignored, so without this key npm's .gitignore fallback would publish a package with no engine in it; with a glob it would publish the sourcemaps, whose sourcesContent embeds every src/*.ts verbatim. dist/VERSION.json exists only in a release-engine.yml build.",
|