@conterra/vuln-scan 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,23 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var rr=Object.create;var it=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var ir=Object.getOwnPropertyNames;var or=Object.getPrototypeOf,sr=Object.prototype.hasOwnProperty;var ot=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}};var ar=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ir(e))!sr.call(t,i)&&i!==r&&it(t,i,{get:()=>e[i],enumerable:!(n=nr(e,i))||n.enumerable});return t};var z=(t,e,r)=>(r=t!=null?rr(or(t)):{},ar(e||!t||!t.__esModule?it(r,"default",{value:t,enumerable:!0}):r,t));var Et=ot((zn,vt)=>{"use strict";vt.exports=Rr;function Pr(t){let e={defaultWidth:0,output:process.stdout,tty:require("tty")};return t?(Object.keys(e).forEach(function(r){t[r]||(t[r]=e[r])}),t):e}function Rr(t){let e=Pr(t);if(e.output.getWindowSize)return e.output.getWindowSize()[0]||e.defaultWidth;if(e.tty.getWindowSize)return e.tty.getWindowSize()[1]||e.defaultWidth;if(e.output.columns)return e.output.columns;if(process.env.CLI_WIDTH){let r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return e.defaultWidth}});var $t=ot((ui,Vt)=>{var Kr=require("stream"),$e=class extends Kr{#r=null;constructor(e={}){super(e),this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,r){return this._dest?this._dest[e]:this._src?this._src[e]:r}#e(e,...r){typeof this._dest?.[e]=="function"&&this._dest[e](...r),typeof this._src?.[e]=="function"&&this._src[e](...r)}get isTTY(){return this.#r!==null?this.#r:this.#t("isTTY",!1)}set isTTY(e){this.#r=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,r){return this._dest=e,super.pipe(e,r)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/))return e.indexOf(this._prompt)===0&&(e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e),this._hadControl=!0,this.emit("data",e);this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0&&(this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length)),e=e.toString().replace(/./g,this.replace)}this.emit("data",e)}end(e){this.muted&&(e&&this.replace?e=e.toString().replace(/./g,this.replace):e=null),e&&this.emit("data",e),this.emit("end")}destroy(...e){return this.#e("destroy",...e)}destroySoon(...e){return this.#e("destroySoon",...e)}close(...e){return this.#e("close",...e)}};Vt.exports=$e});var q=z(require("path")),Be=require("fs/promises");var N=require("fs/promises");async function me(t){try{return await lr(t)?JSON.parse(await(0,N.readFile)(t,{encoding:"utf-8"})):void 0}catch(e){throw new Error(`Error reading JSON file ${t}: ${e}`,{cause:e})}}async function st(t,e){let r=JSON.stringify(e,null,4)+`
3
- `,n=await cr(t,r);await(0,N.writeFile)(t,n,{encoding:"utf-8"})}async function lr(t){try{return await(0,N.access)(t,N.constants.F_OK),!0}catch{return!1}}async function cr(t,e){let r=await fr();if(!r)return e;let n=await r.resolveConfig(t);return n?await r.format(e,{...n,filepath:t}):e}var ur;function fr(){return ur??=import("prettier").catch(()=>{})}var k=["UNKNOWN","LOW","MEDIUM","HIGH","CRITICAL"];var Fe=class t{constructor(e){this.workingDir=e}workingDir;static DEFAULT_MAVEN_REPO="https://repository.conterra.de/repository/maven-mirror-ct";static DEFAULT_VEX_SUBDIR="input/vex";static DEFAULT_OUT_SUBDIR="output";static DEFAULT_CACHE_SUBDIR="cache";static DEFAULT_SCANNERS=["grype","trivy","ossindex"];normalize(e,r){let n=e.findNoLongerDetectedVulnerabilitiesOnlyForSnapshots??!1;return{projectConfigFileLocation:r,onNewVulnerabilities:e.onNewVulnerabilities??(e.failOnNewVulnerabilities?"fail":"warn"),onNoLongerDetectedVulnerabilities:e.onNoLongerDetectedVulnerabilities??"ignore",reportNoLongerDetectedVulnerabilities:e.reportNoLongerDetectedVulnerabilities??!0,consoleReport:e.consoleReport??"BY_PROJECT_DETAILED",createSubDirsForProject:e.createSubDirsForProject??!0,mavenRepo:e.mavenRepo??t.DEFAULT_MAVEN_REPO,vexUrls:e.vexUrls??[],vexDir:this.resolvePath(e.vexDir)??(0,q.resolve)(this.workingDir,t.DEFAULT_VEX_SUBDIR),outDir:this.resolvePath(e.outDir)??(0,q.resolve)(this.workingDir,t.DEFAULT_OUT_SUBDIR),cacheDir:this.resolvePath(e.cacheDir)??(0,q.resolve)(this.workingDir,t.DEFAULT_CACHE_SUBDIR),scanners:this.normalizeScanners(e.scanners,r),projects:this.normalizeProjects(e.projects??[],n)}}normalizeScanners(e,r){return(e??t.DEFAULT_SCANNERS).map(i=>{if(typeof i!="string")throw new Error(`Invalid scanner name '${String(i)}' in configuration file '${r}'`);let o=i.split("@");if(o.length>2)throw new Error(`Invalid scanner name '${i}' in configuration file '${r}'`);return{name:o[0],version:o[1]??""}})}normalizeProjects(e,r){return e.map(n=>{let i=n;if(!i.name)throw new Error("Project name is missing on entry: "+JSON.stringify(i));if(!i.version)throw new Error("Project version is missing on entry: "+JSON.stringify(i));if(!i.purl)throw new Error("Project purl is missing on entry: "+JSON.stringify(i));let o={...i,purlAliases:i.purlAliases??[],enabled:i.enabled??!0,silent:i.silent??!1,minimumSeverity:i.minimumSeverity??"UNKNOWN"};return o.sbomFile?{...o,sbomFile:this.resolvePath(o.sbomFile)??o.sbomFile}:{...o,detectNoLongerUsedVulnerabilities:r?o.purl.endsWith("-SNAPSHOT"):!0}})}resolvePath(e){if(e)return q.default.isAbsolute(e)?e:(0,q.resolve)(this.workingDir,e)}},he=class{constructor(e){this.workingDir=e;this.normalizer=new Fe(e)}workingDir;normalizer;projectConfigCache;async loadProjectConfig(){return this.projectConfigCache??=this.doLoadProjectConfig(),this.projectConfigCache}async doLoadProjectConfig(){let e=(0,q.resolve)(this.workingDir,"vuln-scan-conf.json"),r=await me(e);if(!r)throw new Error(`Missing project configuration file '${e}'`);return this.normalizer.normalize(r,e)}async loadJiraConfig(e){let r=await(0,Be.readFile)(e,"utf8"),n=JSON.parse(r);if(!n.issues&&n.issue&&(n.issues=n.issue),!n.jiraUrl||typeof n.jiraUrl!="string")throw new Error("jira-conf.json: missing or invalid 'jiraUrl' field");if(!Array.isArray(n.issues))throw new Error("jira-conf.json: missing or invalid 'issues' array");this.validateAutoCloseSeverity(n.autoCloseBelowSeverity,"jira-conf.json: invalid 'autoCloseBelowSeverity'");for(let[i,o]of n.issues.entries())o&&typeof o=="object"&&this.validateAutoCloseSeverity(o.autoCloseBelowSeverity,`jira-conf.json: invalid 'issues[${i}].autoCloseBelowSeverity'`);return n}validateAutoCloseSeverity(e,r){if(e!==void 0&&!k.includes(e))throw new Error(`${r} value '${String(e)}'. Must be one of: ${k.join(", ")}`)}async loadAutoVexConfig(e){let r=await(0,Be.readFile)(e,"utf8"),n=JSON.parse(r);if(!n.impactStatement||typeof n.impactStatement!="string")throw new Error("auto-vex-conf.json: missing or invalid 'impactStatement' field (must be a non-empty string)");if(n.maxSeverity!==void 0&&!k.includes(n.maxSeverity))throw new Error(`auto-vex-conf.json: invalid 'maxSeverity' value '${String(n.maxSeverity)}'. Must be one of: ${k.join(", ")}`);if(n.projectOverrides!==void 0){if(!Array.isArray(n.projectOverrides))throw new Error("auto-vex-conf.json: 'projectOverrides' must be an array");for(let[i,o]of n.projectOverrides.entries()){if(!o||typeof o!="object")throw new Error(`auto-vex-conf.json: 'projectOverrides[${i}]' must be an object`);let s=o;if(!Array.isArray(s.projects)||s.projects.length===0||!s.projects.every(a=>typeof a=="string"&&a.length>0))throw new Error(`auto-vex-conf.json: 'projectOverrides[${i}].projects' must be a non-empty array of non-empty strings`);if(!k.includes(s.maxSeverity))throw new Error(`auto-vex-conf.json: invalid 'projectOverrides[${i}].maxSeverity' value '${String(s.maxSeverity)}'. Must be one of: ${k.join(", ")}`)}}return n}};var tr=require("path");var at=require("crypto");var Ue="auto_vex_max_severity=";function dr(t){return`${Ue}${t}`}function ge(t){let e=t.status_notes;if(!e||!e.startsWith(Ue))return;let r=e.slice(Ue.length).trim();return k.includes(r)?r:void 0}function lt(t){let{cveName:e,purls:r,status:n,impactStatement:i,actionStatement:o,statusNotes:s,justification:a,timestamp:p=new Date().toISOString(),autoVexMaxSeverity:d}=t,h={vulnerability:{name:e},timestamp:p,products:r.map(l=>({"@id":l})),status:n};return i&&(h.impact_statement=i),o&&(h.action_statement=o),d?h.status_notes=dr(d):s&&(h.status_notes=s),a&&(h.justification=a),h}var pr="https://openvex.dev/ns/v0.2.0";function ct(t,e="conterra"){let n=`https://openvex.dev/docs/public/vex-${(0,at.randomUUID)()}`,i=t.timestamp??new Date().toISOString();return{"@context":pr,"@id":n,author:e,timestamp:i,last_updated:i,version:1,statements:[t]}}function ut(t,e){let r=e.timestamp??new Date().toISOString();return{...t,last_updated:r,version:t.version+1,statements:[...t.statements,e]}}var Se=require("fs/promises"),we=require("path");function ft(t){let e=t.vulnerability.name;return new Set([e,...t.vulnerability.aliases??[]])}var se=class{constructor(e){this.location=e}location;_content=void 0;_exists=!1;get exists(){return this._exists}get content(){return this._content}set content(e){this._content=e,this._exists=e!==void 0}async read(){let e=await me(this.location);this._content=e??void 0,this._exists=this._content!==void 0}async write(){if(this._content===void 0)throw new Error(`Cannot write VexFile: content is undefined (${this.location})`);await(0,Se.mkdir)((0,we.dirname)((0,we.resolve)(this.location)),{recursive:!0}),await st(this.location,this._content)}async delete(){await(0,Se.unlink)(this.location),this._exists=!1}upsert(e,r){if(this._content===void 0)return this._content=ct(e,r),this._exists=!0,{created:!0,changed:!0};let n=ge(e);if(n!==void 0){let i=this._content.statements.findIndex(o=>o.vulnerability.name===e.vulnerability.name&&o.status===e.status&&ge(o)===n);if(i!==-1){let o=this._content.statements[i];return mr(o,e)?{created:!1,changed:!1}:(o.products=e.products,o.impact_statement=e.impact_statement,o.action_statement=e.action_statement,o.justification=e.justification,o.status_notes=e.status_notes,o.timestamp=e.timestamp,this._content.version+=1,this._content.last_updated=e.timestamp??new Date().toISOString(),{created:!1,changed:!0})}}return this._content=ut(this._content,e),{created:!1,changed:!0}}addProductId(e,r){this.assertContentLoaded("addProductId");let n=!1;for(let i of this._content.statements){if(!i.products||i.products.some(s=>s["@id"]===r))continue;let o=i.products.findIndex(s=>s["@id"]===e);o!==-1&&(i.products.splice(o+1,0,{"@id":r}),n=!0)}return n}removeProductId(e,r){this.assertContentLoaded("removeProductId");let n=this._content.statements,i=[],o=!1;for(let s of n){if(r&&!ft(s).has(r)||!s.products)continue;let a=s.products.findIndex(p=>p["@id"]===e);a!==-1&&(s.products.splice(a,1),o=!0,s.products.length===0&&i.push(s))}if(!o)return"unchanged";for(let s of i)n.splice(n.indexOf(s),1);return n.length===0?"emptied":"changed"}hasStatementForProduct(e){return this.assertContentLoaded("hasStatementForProduct"),this._content.statements.some(r=>r.products?.some(n=>n["@id"]===e)??!1)}assertContentLoaded(e){if(this._content===void 0)throw new Error(`VexFile.${e}(): content is not loaded. Call read() first (${this.location})`)}};function mr(t,e){return t.impact_statement!==e.impact_statement||t.action_statement!==e.action_statement||t.justification!==e.justification||t.status_notes!==e.status_notes?!1:hr(t.products,e.products)}function hr(t,e){let r=o=>Array.from(new Set((o??[]).map(s=>s["@id"]).filter(s=>typeof s=="string"))).sort(),n=r(t),i=r(e);return n.length!==i.length?!1:n.every((o,s)=>o===i[s])}var gr=["emacs","vim"],Sr=new Set(gr);function wr(t){return Sr.has(t)}function dt(){let t=process.env.INQUIRER_KEYBINDINGS;return t?Array.from(new Set(t.toLowerCase().split(/[\s,]+/).filter(wr))):[]}var V=(t,e=[])=>t.name==="up"||e.includes("vim")&&t.name==="k"||e.includes("emacs")&&t.ctrl&&t.name==="p",Y=(t,e=[])=>t.name==="down"||e.includes("vim")&&t.name==="j"||e.includes("emacs")&&t.ctrl&&t.name==="n",Ne=t=>t.name==="space",ae=t=>t.name==="backspace",le=t=>t.name==="tab",ce=t=>"1234567890".includes(t.name),$=t=>t.name==="enter"||t.name==="return";var xe=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super(),this.cause=e?.cause}},be=class extends Error{name="CancelPromptError";message="Prompt was canceled"},ue=class extends Error{name="ExitPromptError"},ye=class extends Error{name="HookError"},J=class extends Error{name="ValidationError"};var gt=require("node:async_hooks");var ve=require("node:async_hooks");var pt=new ve.AsyncLocalStorage;function xr(t){return{rl:t,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function mt(t,e){let r=xr(t);return pt.run(r,()=>{function n(i){r.handleChange=()=>{r.index=0,i()},r.handleChange()}return e(n)})}function Q(){let t=pt.getStore();if(!t)throw new ye("[Inquirer] Hook functions can only be called from within a prompt");return t}function Oe(){return Q().rl}function je(t){let e=(...r)=>{let n=Q(),i=!1,o=n.handleChange;n.handleChange=()=>{i=!0};let s=t(...r);return i&&o(),n.handleChange=o,s};return ve.AsyncResource.bind(e)}function ne(t){let e=Q(),{index:r}=e,n={get(){return e.hooks[r]},set(o){e.hooks[r]=o},initialized:r in e.hooks},i=t(n);return e.index++,i}function ht(){Q().handleChange()}var Z={queue(t){let e=Q(),{index:r}=e;e.hooksEffect.push(()=>{e.hooksCleanup[r]?.();let n=t(Oe());if(n!=null&&typeof n!="function")throw new J("useEffect return value must be a cleanup function or nothing.");e.hooksCleanup[r]=n})},run(){let t=Q();je(()=>{t.hooksEffect.forEach(e=>{e()}),t.hooksEffect.length=0})()},clearAll(){let t=Q();t.hooksCleanup.forEach(e=>{e?.()}),t.hooksEffect.length=0,t.hooksCleanup.length=0}};function br(t){return typeof t=="function"}function D(t){return ne(e=>{let r=gt.AsyncResource.bind(function(o){e.get()!==o&&(e.set(o),ht())});if(e.initialized)return[e.get(),r];let n=br(t)?t():t;return e.set(n),[n,r]})}function M(t,e){ne(r=>{let n=r.get();(!Array.isArray(n)||e.some((o,s)=>!Object.is(o,n[s])))&&Z.queue(t),r.set(e)})}var F=require("node:util");var B=z(require("node:process"),1);function yr(){return B.default.platform.startsWith("win")?!!B.default.env.CI||!!B.default.env.WT_SESSION||!!B.default.env.TERMINUS_SUBLIME||B.default.env.ConEmuTask==="{cmd::Cmder}"||B.default.env.TERM_PROGRAM==="Terminus-Sublime"||B.default.env.TERM_PROGRAM==="vscode"||B.default.env.TERM==="xterm-256color"||B.default.env.TERM==="alacritty"||B.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm":B.default.env.TERM!=="linux"}var St={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},wt={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},vr={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},Er={...St,...wt},Dr={...St,...vr},Lr=yr(),Ir=Lr?Er:Dr,O=Ir,Cn=Object.entries(wt);var _r={prefix:{idle:(0,F.styleText)("blue","?"),done:(0,F.styleText)("green",O.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(t=>(0,F.styleText)("yellow",t))},keybindings:[],style:{answer:t=>(0,F.styleText)("cyan",t),message:t=>(0,F.styleText)("bold",t),error:t=>(0,F.styleText)("red",`> ${t}`),defaultAnswer:t=>(0,F.styleText)("dim",`(${t})`),help:t=>(0,F.styleText)("dim",t),highlight:t=>(0,F.styleText)("cyan",t),key:t=>(0,F.styleText)("cyan",(0,F.styleText)("bold",`<${t}>`))}};function xt(){return{..._r,keybindings:dt()}}function bt(t){if(typeof t!="object"||t===null)return!1;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function yt(...t){let e={};for(let r of t)for(let[n,i]of Object.entries(r)){let o=e[n];e[n]=bt(o)&&bt(i)?yt(o,i):i}return e}function j(...t){let e=[xt(),...t.filter(r=>r!=null)];return yt(...e)}function W({status:t="idle",theme:e}){let[r,n]=D(!1),[i,o]=D(0),{prefix:s,spinner:a}=j(e);return M(()=>{if(t==="loading"){let d,h=-1,l=setTimeout(()=>{n(!0),d=setInterval(()=>{h=h+1,o(h%a.frames.length)},a.interval)},300);return()=>{clearTimeout(l),clearInterval(d)}}else n(!1)},[t]),r?a.frames[i]:typeof s=="string"?s:s[t==="loading"?"idle":t]??s.idle}function ee(t,e){return ne(r=>{let n=r.get();if(!n||n.dependencies.length!==e.length||n.dependencies.some((i,o)=>i!==e[o])){let i=t();return r.set({value:i,dependencies:e}),i}return n.value})}function te(t){return D({current:t})[0]}function K(t){let e=te(t);e.current=t,M(r=>{let n=!1,i=je((o,s)=>{n||e.current(s,r)});return r.input.on("keypress",i),()=>{n=!0,r.input.removeListener("keypress",i)}},[])}var kt=z(Et(),1);var Dt=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let r=0;for(t.lastIndex=0;t.test(e);)r+=1;return e.length-r}})(),Lt=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,It=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var Tr=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Cr=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,_t=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Br=/\t{1,1000}/y,Pt=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),Fr=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ur=new RegExp("\\p{M}+","gu"),Nr={limit:1/0,ellipsis:""},Rt=(t,e={},r={})=>{let n=e.limit??1/0,i=e.ellipsis??"",o=e?.ellipsisWidth??(i?Rt(i,Nr,r).width:0),s=0,a=r.controlWidth??0,p=r.tabWidth??8,d=r.emojiWidth??2,h=2,l=r.regularWidth??1,u=r.wideWidth??h,g=[[Fr,l],[Tr,s],[Cr,a],[Br,p],[Pt,d],[_t,u]],f=0,m=0,S=t.length,b=0,w=!1,v=S,L=Math.max(0,n-o),P=0,I=0,R=0,T=0;e:for(;;){if(I>P||m>=S&&m>f){let c=t.slice(P,I)||t.slice(f,m);b=0;for(let x of c.replaceAll(Ur,"")){let y=x.codePointAt(0)||0;if(Lt(y)?T=h:It(y)?T=u:T=l,R+T>L&&(v=Math.min(v,Math.max(P,f)+b)),R+T>n){w=!0;break e}b+=x.length,R+=T}P=I=0}if(m>=S)break e;for(let c=0,x=g.length;c<x;c++){let[y,E]=g[c];if(y.lastIndex=m,y.test(t)){if(b=y===_t?Dt(t.slice(m,y.lastIndex)):y===Pt?1:y.lastIndex-m,T=b*E,R+T>L&&(v=Math.min(v,m+Math.floor((L-R)/E))),R+T>n){w=!0;break e}R+=T,P=f,I=m,m=f=y.lastIndex;continue e}}m+=1}return{width:w?L:R,index:w?v:S,truncated:w,ellipsed:w&&n>=o}},Tt=Rt;var Or={limit:1/0,ellipsis:"",ellipsisWidth:0},jr=(t,e={})=>Tt(t,Or,e).width,H=jr;var Ee="\x1B",Nt="\x9B",Ar=39,ke="\x07",Ot="[",kr="]",jt="m",Ve=`${kr}8;;`,Ct=new RegExp(`(?:\\${Ot}(?<code>\\d+)m|\\${Ve}(?<uri>.*)${ke})`,"y"),Bt=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},Ft=t=>`${Ee}${Ot}${t}${jt}`,Ut=t=>`${Ee}${Ve}${t}${ke}`,Ae=(t,e,r)=>{let n=e[Symbol.iterator](),i=!1,o=!1,s=t.at(-1),a=s===void 0?0:H(s),p=n.next(),d=n.next(),h=0;for(;!p.done;){let l=p.value,u=H(l);a+u<=r?t[t.length-1]+=l:(t.push(l),a=0),(l===Ee||l===Nt)&&(i=!0,o=e.startsWith(Ve,h+1)),i?o?l===ke&&(i=!1,o=!1):l===jt&&(i=!1):(a+=u,a===r&&!d.done&&(t.push(""),a=0)),p=d,d=n.next(),h+=l.length}s=t.at(-1),!a&&s!==void 0&&s.length&&t.length>1&&(t[t.length-2]+=t.pop())},Vr=t=>{let e=t.split(" "),r=e.length;for(;r&&!H(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},$r=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",i,o,s=t.split(" "),a=[""],p=0;for(let l=0;l<s.length;l++){let u=s[l];if(r.trim!==!1){let f=a.at(-1)??"",m=f.trimStart();f.length!==m.length&&(a[a.length-1]=m,p=H(m))}l!==0&&(p>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),p=0),(p||r.trim===!1)&&(a[a.length-1]+=" ",p++));let g=H(u);if(r.hard&&g>e){let f=e-p,m=1+Math.floor((g-f-1)/e);Math.floor((g-1)/e)<m&&a.push(""),Ae(a,u,e),p=H(a.at(-1)??"");continue}if(p+g>e&&p&&g){if(r.wordWrap===!1&&p<e){Ae(a,u,e),p=H(a.at(-1)??"");continue}a.push(""),p=0}if(p+g>e&&r.wordWrap===!1){Ae(a,u,e),p=H(a.at(-1)??"");continue}a[a.length-1]+=u,p+=g}r.trim!==!1&&(a=a.map(l=>Vr(l)));let d=a.join(`
4
- `),h=!1;for(let l=0;l<d.length;l++){let u=d[l];if(n+=u,h)h=!1;else if(h=u>="\uD800"&&u<="\uDBFF",h)continue;if(u===Ee||u===Nt){Ct.lastIndex=l+1;let f=Ct.exec(d)?.groups;if(f?.code!==void 0){let m=Number.parseFloat(f.code);i=m===Ar?void 0:m}else f?.uri!==void 0&&(o=f.uri.length===0?void 0:f.uri)}if(d[l+1]===`
5
- `){o&&(n+=Ut(""));let g=i?Bt(i):void 0;i&&g&&(n+=Ft(g))}else u===`
6
- `&&(i&&Bt(i)&&(n+=Ft(i)),o&&(n+=Ut(o)))}return n},Mr=/\r?\n/;function At(t,e,r){return String(t).normalize().split(Mr).map(n=>$r(n,e,r)).join(`
2
+ "use strict";var er=Object.create;var rt=Object.defineProperty;var tr=Object.getOwnPropertyDescriptor;var rr=Object.getOwnPropertyNames;var nr=Object.getPrototypeOf,ir=Object.prototype.hasOwnProperty;var nt=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}};var or=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of rr(e))!ir.call(t,i)&&i!==r&&rt(t,i,{get:()=>e[i],enumerable:!(n=tr(e,i))||n.enumerable});return t};var z=(t,e,r)=>(r=t!=null?er(nr(t)):{},or(e||!t||!t.__esModule?rt(r,"default",{value:t,enumerable:!0}):r,t));var yt=nt((zn,xt)=>{"use strict";xt.exports=_r;function Pr(t){let e={defaultWidth:0,output:process.stdout,tty:require("tty")};return t?(Object.keys(e).forEach(function(r){t[r]||(t[r]=e[r])}),t):e}function _r(t){let e=Pr(t);if(e.output.getWindowSize)return e.output.getWindowSize()[0]||e.defaultWidth;if(e.tty.getWindowSize)return e.tty.getWindowSize()[1]||e.defaultWidth;if(e.output.columns)return e.output.columns;if(process.env.CLI_WIDTH){let r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return e.defaultWidth}});var kt=nt((ui,Ot)=>{var Wr=require("stream"),ke=class extends Wr{#r=null;constructor(e={}){super(e),this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,r){return this._dest?this._dest[e]:this._src?this._src[e]:r}#e(e,...r){typeof this._dest?.[e]=="function"&&this._dest[e](...r),typeof this._src?.[e]=="function"&&this._src[e](...r)}get isTTY(){return this.#r!==null?this.#r:this.#t("isTTY",!1)}set isTTY(e){this.#r=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,r){return this._dest=e,super.pipe(e,r)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/))return e.indexOf(this._prompt)===0&&(e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e),this._hadControl=!0,this.emit("data",e);this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0&&(this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length)),e=e.toString().replace(/./g,this.replace)}this.emit("data",e)}end(e){this.muted&&(e&&this.replace?e=e.toString().replace(/./g,this.replace):e=null),e&&this.emit("data",e),this.emit("end")}destroy(...e){return this.#e("destroy",...e)}destroySoon(...e){return this.#e("destroySoon",...e)}close(...e){return this.#e("close",...e)}};Ot.exports=ke});var q=z(require("path")),Te=require("fs/promises");var F=require("fs/promises");async function me(t){try{return await sr(t)?JSON.parse(await(0,F.readFile)(t,{encoding:"utf-8"})):void 0}catch(e){throw new Error(`Error reading JSON file ${t}: ${e}`,{cause:e})}}async function it(t,e){let r=JSON.stringify(e,null,4)+`
3
+ `,n=await ar(t,r);await(0,F.writeFile)(t,n,{encoding:"utf-8"})}async function sr(t){try{return await(0,F.access)(t,F.constants.F_OK),!0}catch{return!1}}async function ar(t,e){let r=await cr();if(!r)return e;let n=await r.resolveConfig(t);return n?await r.format(e,{...n,filepath:t}):e}var lr;function cr(){return lr??=import("prettier").catch(()=>{})}var G=["UNKNOWN","LOW","MEDIUM","HIGH","CRITICAL"];var Be=class t{constructor(e){this.workingDir=e}workingDir;static DEFAULT_MAVEN_REPO="https://repository.conterra.de/repository/maven-mirror-ct";static DEFAULT_VEX_SUBDIR="input/vex";static DEFAULT_OUT_SUBDIR="output";static DEFAULT_CACHE_SUBDIR="cache";static DEFAULT_SCANNERS=["grype","trivy","ossindex"];normalize(e,r){let n=e.findNoLongerDetectedVulnerabilitiesOnlyForSnapshots??!1;return{projectConfigFileLocation:r,onNewVulnerabilities:e.onNewVulnerabilities??(e.failOnNewVulnerabilities?"fail":"warn"),onNoLongerDetectedVulnerabilities:e.onNoLongerDetectedVulnerabilities??"ignore",reportNoLongerDetectedVulnerabilities:e.reportNoLongerDetectedVulnerabilities??!0,consoleReport:e.consoleReport??"BY_PROJECT_DETAILED",createSubDirsForProject:e.createSubDirsForProject??!0,mavenRepo:e.mavenRepo??t.DEFAULT_MAVEN_REPO,vexUrls:e.vexUrls??[],vexDir:this.resolvePath(e.vexDir)??(0,q.resolve)(this.workingDir,t.DEFAULT_VEX_SUBDIR),outDir:this.resolvePath(e.outDir)??(0,q.resolve)(this.workingDir,t.DEFAULT_OUT_SUBDIR),cacheDir:this.resolvePath(e.cacheDir)??(0,q.resolve)(this.workingDir,t.DEFAULT_CACHE_SUBDIR),scanners:this.normalizeScanners(e.scanners,r),projects:this.normalizeProjects(e.projects??[],n)}}normalizeScanners(e,r){return(e??t.DEFAULT_SCANNERS).map(i=>{if(typeof i!="string")throw new Error(`Invalid scanner name '${String(i)}' in configuration file '${r}'`);let s=i.split("@");if(s.length>2)throw new Error(`Invalid scanner name '${i}' in configuration file '${r}'`);return{name:s[0],version:s[1]??""}})}normalizeProjects(e,r){let n=e.map(i=>{let s=i;if(!s.name)throw new Error("Project name is missing on entry: "+JSON.stringify(s));if(!s.version)throw new Error("Project version is missing on entry: "+JSON.stringify(s));if(!s.purl)throw new Error("Project purl is missing on entry: "+JSON.stringify(s));let o={...s,purlAliases:s.purlAliases??[],enabled:s.enabled??!0,silent:s.silent??!1,minimumSeverity:s.minimumSeverity??"UNKNOWN"};return o.sbomFile?{...o,sbomFile:this.resolvePath(o.sbomFile)??o.sbomFile}:{...o,detectNoLongerUsedVulnerabilities:r?o.purl.endsWith("-SNAPSHOT"):!0}});return this.assertUniqueProjectIds(n),this.assertUniqueProjectPurls(n),n}assertUniqueProjectIds(e){let r=new Set;for(let n of e){let i=`${n.name}@${n.version}`;if(r.has(i))throw new Error(`Duplicate project id '${i}' in vuln-scan-conf.json: each 'name@version' pair must be unique across the projects array.`);r.add(i)}}assertUniqueProjectPurls(e){let r=new Map;for(let n of e){let i=`${n.name}@${n.version}`,s=r.get(n.purl);if(s!==void 0)throw new Error(`Duplicate project purl '${n.purl}' in vuln-scan-conf.json: used by '${s}' and '${i}'. Each project must have a unique purl; use 'purlAliases' when two projects should be matched by the same VEX statement.`);r.set(n.purl,i)}}resolvePath(e){if(e)return q.default.isAbsolute(e)?e:(0,q.resolve)(this.workingDir,e)}},he=class{constructor(e){this.workingDir=e;this.normalizer=new Be(e)}workingDir;normalizer;projectConfigCache;async loadProjectConfig(){return this.projectConfigCache??=this.doLoadProjectConfig(),this.projectConfigCache}async doLoadProjectConfig(){let e=(0,q.resolve)(this.workingDir,"vuln-scan-conf.json"),r=await me(e);if(!r)throw new Error(`Missing project configuration file '${e}'`);return this.normalizer.normalize(r,e)}async loadJiraConfig(e){let r=await(0,Te.readFile)(e,"utf8"),n=JSON.parse(r);if(!n.issues&&n.issue&&(n.issues=n.issue),!n.jiraUrl||typeof n.jiraUrl!="string")throw new Error("jira-conf.json: missing or invalid 'jiraUrl' field");if(!Array.isArray(n.issues))throw new Error("jira-conf.json: missing or invalid 'issues' array");this.validateAutoCloseSeverity(n.autoCloseBelowSeverity,"jira-conf.json: invalid 'autoCloseBelowSeverity'");for(let[i,s]of n.issues.entries())if(s&&typeof s=="object"){let o=s;this.validateAutoCloseSeverity(o.autoCloseBelowSeverity,`jira-conf.json: invalid 'issues[${i}].autoCloseBelowSeverity'`),this.validateAutoCloseProjectOverrides(o.projectOverrides,`jira-conf.json: invalid 'issues[${i}].projectOverrides'`)}return n}validateAutoCloseSeverity(e,r){if(e!==void 0&&!G.includes(e))throw new Error(`${r} value '${String(e)}'. Must be one of: ${G.join(", ")}`)}validateAutoCloseProjectOverrides(e,r){if(e!==void 0){if(!Array.isArray(e))throw new Error(`${r}: must be an array`);for(let n=0;n<e.length;n++){let i=e[n],s=`${r}[${n}]`;if(i==null||typeof i!="object")throw new Error(`${s}: must be an object`);let o=i,a=o.projects;if(!Array.isArray(a)||a.length===0)throw new Error(`${s}.projects: must be a non-empty array of strings`);for(let c=0;c<a.length;c++){let f=a[c];if(typeof f!="string"||f.length===0)throw new Error(`${s}.projects[${c}]: must be a non-empty string`)}if(o.autoCloseBelowSeverity===void 0)throw new Error(`${s}.autoCloseBelowSeverity: is required`);if(this.validateAutoCloseSeverity(o.autoCloseBelowSeverity,`${s}.autoCloseBelowSeverity`),o.comment!==void 0&&typeof o.comment!="string")throw new Error(`${s}.comment: must be a string`)}}}async loadAutoVexConfig(e){let r=await(0,Te.readFile)(e,"utf8"),n=JSON.parse(r);if(!n.impactStatement||typeof n.impactStatement!="string")throw new Error("auto-vex-conf.json: missing or invalid 'impactStatement' field (must be a non-empty string)");if(n.maxSeverity!==void 0&&!G.includes(n.maxSeverity))throw new Error(`auto-vex-conf.json: invalid 'maxSeverity' value '${String(n.maxSeverity)}'. Must be one of: ${G.join(", ")}`);if(n.projectOverrides!==void 0){if(!Array.isArray(n.projectOverrides))throw new Error("auto-vex-conf.json: 'projectOverrides' must be an array");for(let[i,s]of n.projectOverrides.entries()){if(!s||typeof s!="object")throw new Error(`auto-vex-conf.json: 'projectOverrides[${i}]' must be an object`);let o=s;if(!Array.isArray(o.projects)||o.projects.length===0||!o.projects.every(a=>typeof a=="string"&&a.length>0))throw new Error(`auto-vex-conf.json: 'projectOverrides[${i}].projects' must be a non-empty array of non-empty strings`);if(!G.includes(o.maxSeverity))throw new Error(`auto-vex-conf.json: invalid 'projectOverrides[${i}].maxSeverity' value '${String(o.maxSeverity)}'. Must be one of: ${G.join(", ")}`)}}return n}};var Zt=require("path");var ot=require("crypto");var ur="auto_vex_max_severity=";function fr(t){return`${ur}${t}`}function st(t){let{cveName:e,purls:r,status:n,impactStatement:i,actionStatement:s,statusNotes:o,justification:a,timestamp:c=new Date().toISOString(),autoVexMaxSeverity:f}=t,m={vulnerability:{name:e},timestamp:c,products:r.map(l=>({"@id":l})),status:n};return i&&(m.impact_statement=i),s&&(m.action_statement=s),f?m.status_notes=fr(f):o&&(m.status_notes=o),a&&(m.justification=a),m}var dr="https://openvex.dev/ns/v0.2.0";function at(t,e="conterra"){let n=`https://openvex.dev/docs/public/vex-${(0,ot.randomUUID)()}`,i=t.timestamp??new Date().toISOString();return{"@context":dr,"@id":n,author:e,timestamp:i,last_updated:i,version:1,statements:[t]}}var ge=require("fs/promises"),Se=require("path");function lt(t){let e=t.vulnerability.name;return new Set([e,...t.vulnerability.aliases??[]])}var se=class{constructor(e){this.location=e}location;_content=void 0;_exists=!1;get exists(){return this._exists}get content(){return this._content}set content(e){this._content=e,this._exists=e!==void 0}async read(){let e=await me(this.location);this._content=e??void 0,this._exists=this._content!==void 0}async write(){if(this._content===void 0)throw new Error(`Cannot write VexFile: content is undefined (${this.location})`);await(0,ge.mkdir)((0,Se.dirname)((0,Se.resolve)(this.location)),{recursive:!0}),await it(this.location,this._content)}async delete(){await(0,ge.unlink)(this.location),this._exists=!1}upsert(e,r){if(this._content===void 0)return this._content=at(e,r),this._exists=!0,{created:!0,changed:!0};let n=ct(e.products),i=this._content.statements,s=[];for(let o=0;o<i.length;o++){let a=i[o];a.vulnerability.name===e.vulnerability.name&&a.status===e.status&&mr(ct(a.products),n)&&s.push(o)}if(s.length>0){let o=s[0],a=i[o],c=s.slice(1),f=!pr(a,e);if(c.length===0&&!f)return{created:!1,changed:!1};f&&(a.impact_statement=e.impact_statement,a.action_statement=e.action_statement,a.justification=e.justification,a.status_notes=e.status_notes,a.timestamp=e.timestamp);for(let m=c.length-1;m>=0;m--)i.splice(c[m],1);return this._content.version+=1,this._content.last_updated=e.timestamp??new Date().toISOString(),{created:!1,changed:!0}}for(let o=i.length-1;o>=0;o--){let a=i[o];if(a.vulnerability.name!==e.vulnerability.name||a.status!==e.status||!a.products||a.products.length===0)continue;let c=a.products.filter(f=>{let m=f["@id"];return typeof m!="string"||!n.has(m)});c.length!==a.products.length&&(c.length===0?i.splice(o,1):a.products=c)}return i.push(e),this._content.version+=1,this._content.last_updated=e.timestamp??new Date().toISOString(),{created:!1,changed:!0}}addProductId(e,r){this.assertContentLoaded("addProductId");let n=!1;for(let i of this._content.statements){if(!i.products||i.products.some(o=>o["@id"]===r))continue;let s=i.products.findIndex(o=>o["@id"]===e);s!==-1&&(i.products.splice(s+1,0,{"@id":r}),n=!0)}return n}removeProductId(e,r){this.assertContentLoaded("removeProductId");let n=this._content.statements,i=[],s=!1;for(let o of n){if(r&&!lt(o).has(r)||!o.products)continue;let a=o.products.findIndex(c=>c["@id"]===e);a!==-1&&(o.products.splice(a,1),s=!0,o.products.length===0&&i.push(o))}if(!s)return"unchanged";for(let o of i)n.splice(n.indexOf(o),1);return n.length===0?"emptied":"changed"}hasStatementForProduct(e){return this.assertContentLoaded("hasStatementForProduct"),this._content.statements.some(r=>r.products?.some(n=>n["@id"]===e)??!1)}assertContentLoaded(e){if(this._content===void 0)throw new Error(`VexFile.${e}(): content is not loaded. Call read() first (${this.location})`)}};function pr(t,e){return t.impact_statement===e.impact_statement&&t.action_statement===e.action_statement&&t.justification===e.justification&&t.status_notes===e.status_notes}function ct(t){let e=new Set;if(!t)return e;for(let r of t){let n=r["@id"];typeof n=="string"&&e.add(n)}return e}function mr(t,e){if(t.size!==e.size)return!1;for(let r of t)if(!e.has(r))return!1;return!0}var hr=["emacs","vim"],gr=new Set(hr);function Sr(t){return gr.has(t)}function ut(){let t=process.env.INQUIRER_KEYBINDINGS;return t?Array.from(new Set(t.toLowerCase().split(/[\s,]+/).filter(Sr))):[]}var k=(t,e=[])=>t.name==="up"||e.includes("vim")&&t.name==="k"||e.includes("emacs")&&t.ctrl&&t.name==="p",Y=(t,e=[])=>t.name==="down"||e.includes("vim")&&t.name==="j"||e.includes("emacs")&&t.ctrl&&t.name==="n",je=t=>t.name==="space",ae=t=>t.name==="backspace",le=t=>t.name==="tab",ce=t=>"1234567890".includes(t.name),$=t=>t.name==="enter"||t.name==="return";var we=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super(),this.cause=e?.cause}},be=class extends Error{name="CancelPromptError";message="Prompt was canceled"},ue=class extends Error{name="ExitPromptError"},xe=class extends Error{name="HookError"},J=class extends Error{name="ValidationError"};var mt=require("node:async_hooks");var ye=require("node:async_hooks");var ft=new ye.AsyncLocalStorage;function wr(t){return{rl:t,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function dt(t,e){let r=wr(t);return ft.run(r,()=>{function n(i){r.handleChange=()=>{r.index=0,i()},r.handleChange()}return e(n)})}function Q(){let t=ft.getStore();if(!t)throw new xe("[Inquirer] Hook functions can only be called from within a prompt");return t}function Ue(){return Q().rl}function Fe(t){let e=(...r)=>{let n=Q(),i=!1,s=n.handleChange;n.handleChange=()=>{i=!0};let o=t(...r);return i&&s(),n.handleChange=s,o};return ye.AsyncResource.bind(e)}function ne(t){let e=Q(),{index:r}=e,n={get(){return e.hooks[r]},set(s){e.hooks[r]=s},initialized:r in e.hooks},i=t(n);return e.index++,i}function pt(){Q().handleChange()}var Z={queue(t){let e=Q(),{index:r}=e;e.hooksEffect.push(()=>{e.hooksCleanup[r]?.();let n=t(Ue());if(n!=null&&typeof n!="function")throw new J("useEffect return value must be a cleanup function or nothing.");e.hooksCleanup[r]=n})},run(){let t=Q();Fe(()=>{t.hooksEffect.forEach(e=>{e()}),t.hooksEffect.length=0})()},clearAll(){let t=Q();t.hooksCleanup.forEach(e=>{e?.()}),t.hooksEffect.length=0,t.hooksCleanup.length=0}};function br(t){return typeof t=="function"}function D(t){return ne(e=>{let r=mt.AsyncResource.bind(function(s){e.get()!==s&&(e.set(s),pt())});if(e.initialized)return[e.get(),r];let n=br(t)?t():t;return e.set(n),[n,r]})}function V(t,e){ne(r=>{let n=r.get();(!Array.isArray(n)||e.some((s,o)=>!Object.is(s,n[o])))&&Z.queue(t),r.set(e)})}var j=require("node:util");var B=z(require("node:process"),1);function xr(){return B.default.platform.startsWith("win")?!!B.default.env.CI||!!B.default.env.WT_SESSION||!!B.default.env.TERMINUS_SUBLIME||B.default.env.ConEmuTask==="{cmd::Cmder}"||B.default.env.TERM_PROGRAM==="Terminus-Sublime"||B.default.env.TERM_PROGRAM==="vscode"||B.default.env.TERM==="xterm-256color"||B.default.env.TERM==="alacritty"||B.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm":B.default.env.TERM!=="linux"}var ht={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},gt={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},yr={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},vr={...ht,...gt},Er={...ht,...yr},Dr=xr(),Lr=Dr?vr:Er,N=Lr,Tn=Object.entries(gt);var Ir={prefix:{idle:(0,j.styleText)("blue","?"),done:(0,j.styleText)("green",N.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(t=>(0,j.styleText)("yellow",t))},keybindings:[],style:{answer:t=>(0,j.styleText)("cyan",t),message:t=>(0,j.styleText)("bold",t),error:t=>(0,j.styleText)("red",`> ${t}`),defaultAnswer:t=>(0,j.styleText)("dim",`(${t})`),help:t=>(0,j.styleText)("dim",t),highlight:t=>(0,j.styleText)("cyan",t),key:t=>(0,j.styleText)("cyan",(0,j.styleText)("bold",`<${t}>`))}};function St(){return{...Ir,keybindings:ut()}}function wt(t){if(typeof t!="object"||t===null)return!1;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function bt(...t){let e={};for(let r of t)for(let[n,i]of Object.entries(r)){let s=e[n];e[n]=wt(s)&&wt(i)?bt(s,i):i}return e}function A(...t){let e=[St(),...t.filter(r=>r!=null)];return bt(...e)}function M({status:t="idle",theme:e}){let[r,n]=D(!1),[i,s]=D(0),{prefix:o,spinner:a}=A(e);return V(()=>{if(t==="loading"){let f,m=-1,l=setTimeout(()=>{n(!0),f=setInterval(()=>{m=m+1,s(m%a.frames.length)},a.interval)},300);return()=>{clearTimeout(l),clearInterval(f)}}else n(!1)},[t]),r?a.frames[i]:typeof o=="string"?o:o[t==="loading"?"idle":t]??o.idle}function ee(t,e){return ne(r=>{let n=r.get();if(!n||n.dependencies.length!==e.length||n.dependencies.some((i,s)=>i!==e[s])){let i=t();return r.set({value:i,dependencies:e}),i}return n.value})}function te(t){return D({current:t})[0]}function W(t){let e=te(t);e.current=t,V(r=>{let n=!1,i=Fe((s,o)=>{n||e.current(o,r)});return r.input.on("keypress",i),()=>{n=!0,r.input.removeListener("keypress",i)}},[])}var At=z(yt(),1);var vt=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let r=0;for(t.lastIndex=0;t.test(e);)r+=1;return e.length-r}})(),Et=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Dt=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var Rr=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Cr=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Lt=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Tr=/\t{1,1000}/y,It=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),Br=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,jr=new RegExp("\\p{M}+","gu"),Ur={limit:1/0,ellipsis:""},Pt=(t,e={},r={})=>{let n=e.limit??1/0,i=e.ellipsis??"",s=e?.ellipsisWidth??(i?Pt(i,Ur,r).width:0),o=0,a=r.controlWidth??0,c=r.tabWidth??8,f=r.emojiWidth??2,m=2,l=r.regularWidth??1,d=r.wideWidth??m,g=[[Br,l],[Rr,o],[Cr,a],[Tr,c],[It,f],[Lt,d]],p=0,h=0,S=t.length,x=0,w=!1,v=S,L=Math.max(0,n-s),_=0,I=0,R=0,C=0;e:for(;;){if(I>_||h>=S&&h>p){let u=t.slice(_,I)||t.slice(p,h);x=0;for(let b of u.replaceAll(jr,"")){let y=b.codePointAt(0)||0;if(Et(y)?C=m:Dt(y)?C=d:C=l,R+C>L&&(v=Math.min(v,Math.max(_,p)+x)),R+C>n){w=!0;break e}x+=b.length,R+=C}_=I=0}if(h>=S)break e;for(let u=0,b=g.length;u<b;u++){let[y,E]=g[u];if(y.lastIndex=h,y.test(t)){if(x=y===Lt?vt(t.slice(h,y.lastIndex)):y===It?1:y.lastIndex-h,C=x*E,R+C>L&&(v=Math.min(v,h+Math.floor((L-R)/E))),R+C>n){w=!0;break e}R+=C,_=p,I=h,h=p=y.lastIndex;continue e}}h+=1}return{width:w?L:R,index:w?v:S,truncated:w,ellipsed:w&&n>=s}},_t=Pt;var Fr={limit:1/0,ellipsis:"",ellipsisWidth:0},Nr=(t,e={})=>_t(t,Fr,e).width,K=Nr;var ve="\x1B",jt="\x9B",Ar=39,Ae="\x07",Ut="[",Or="]",Ft="m",Oe=`${Or}8;;`,Rt=new RegExp(`(?:\\${Ut}(?<code>\\d+)m|\\${Oe}(?<uri>.*)${Ae})`,"y"),Ct=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},Tt=t=>`${ve}${Ut}${t}${Ft}`,Bt=t=>`${ve}${Oe}${t}${Ae}`,Ne=(t,e,r)=>{let n=e[Symbol.iterator](),i=!1,s=!1,o=t.at(-1),a=o===void 0?0:K(o),c=n.next(),f=n.next(),m=0;for(;!c.done;){let l=c.value,d=K(l);a+d<=r?t[t.length-1]+=l:(t.push(l),a=0),(l===ve||l===jt)&&(i=!0,s=e.startsWith(Oe,m+1)),i?s?l===Ae&&(i=!1,s=!1):l===Ft&&(i=!1):(a+=d,a===r&&!f.done&&(t.push(""),a=0)),c=f,f=n.next(),m+=l.length}o=t.at(-1),!a&&o!==void 0&&o.length&&t.length>1&&(t[t.length-2]+=t.pop())},kr=t=>{let e=t.split(" "),r=e.length;for(;r&&!K(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},$r=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",i,s,o=t.split(" "),a=[""],c=0;for(let l=0;l<o.length;l++){let d=o[l];if(r.trim!==!1){let p=a.at(-1)??"",h=p.trimStart();p.length!==h.length&&(a[a.length-1]=h,c=K(h))}l!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let g=K(d);if(r.hard&&g>e){let p=e-c,h=1+Math.floor((g-p-1)/e);Math.floor((g-1)/e)<h&&a.push(""),Ne(a,d,e),c=K(a.at(-1)??"");continue}if(c+g>e&&c&&g){if(r.wordWrap===!1&&c<e){Ne(a,d,e),c=K(a.at(-1)??"");continue}a.push(""),c=0}if(c+g>e&&r.wordWrap===!1){Ne(a,d,e),c=K(a.at(-1)??"");continue}a[a.length-1]+=d,c+=g}r.trim!==!1&&(a=a.map(l=>kr(l)));let f=a.join(`
4
+ `),m=!1;for(let l=0;l<f.length;l++){let d=f[l];if(n+=d,m)m=!1;else if(m=d>="\uD800"&&d<="\uDBFF",m)continue;if(d===ve||d===jt){Rt.lastIndex=l+1;let p=Rt.exec(f)?.groups;if(p?.code!==void 0){let h=Number.parseFloat(p.code);i=h===Ar?void 0:h}else p?.uri!==void 0&&(s=p.uri.length===0?void 0:p.uri)}if(f[l+1]===`
5
+ `){s&&(n+=Bt(""));let g=i?Ct(i):void 0;i&&g&&(n+=Tt(g))}else d===`
6
+ `&&(i&&Ct(i)&&(n+=Tt(i)),s&&(n+=Bt(s)))}return n},Vr=/\r?\n/;function Nt(t,e,r){return String(t).normalize().split(Vr).map(n=>$r(n,e,r)).join(`
7
7
  `)}function fe(t,e){return t.split(`
8
- `).flatMap(r=>At(r,e,{trim:!1,wordWrap:!1}).split(`
8
+ `).flatMap(r=>Nt(r,e,{trim:!1,wordWrap:!1}).split(`
9
9
  `).map(n=>n.trimEnd())).join(`
10
- `)}function De(){return(0,kt.default)({defaultWidth:80,output:Oe().output})}function Wr({active:t,renderedItems:e,pageSize:r,loop:n}){let i=te({lastPointer:t,lastActive:void 0}),{lastPointer:o,lastActive:s}=i.current,a=Math.floor(r/2),p=e.reduce((l,u)=>l+u.length,0),d=e.slice(0,t).reduce((l,u)=>l+u.length,0),h=d;if(p>r)if(n)h=o,s!=null&&s<t&&t-s<r&&(h=Math.min(a,Math.abs(t-s)===1?Math.min(o+(e[s]?.length??0),Math.max(d,o)):o+t-s));else{let l=e.slice(t).reduce((u,g)=>u+g.length,0);h=l<r-a?r-l:Math.min(d,a)}return i.current.lastPointer=h,i.current.lastActive=t,h}function de({items:t,active:e,renderItem:r,pageSize:n,loop:i=!0}){let o=De(),s=b=>(b%t.length+t.length)%t.length,a=t.map((b,w)=>b==null?[]:fe(r({item:b,index:w,isActive:w===e}),o).split(`
11
- `)),p=a.reduce((b,w)=>b+w.length,0),d=b=>a[b]??[],h=Wr({active:e,renderedItems:a,pageSize:n,loop:i}),l=d(e).slice(0,n),u=h+l.length<=n?h:n-l.length,g=Array.from({length:n});g.splice(u,l.length,...l);let f=new Set([e]),m=u+l.length,S=s(e+1);for(;m<n&&!f.has(S)&&(i&&p>n?S!==e:S>e);){let w=d(S).slice(0,n-m);g.splice(m,w.length,...w),f.add(S),m+=w.length,S=s(S+1)}for(m=u-1,S=s(e-1);m>=0&&!f.has(S)&&(i&&p>n?S!==e:S<e);){let b=d(S),w=b.slice(Math.max(0,b.length-m-1));g.splice(m-w.length+1,w.length,...w),f.add(S),m-=w.length,S=s(S-1)}return g.filter(b=>typeof b=="string").join(`
12
- `)}var qt=z(require("node:readline"),1),Jt=require("node:async_hooks"),Xt=z($t(),1);var re=[];re.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&re.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&re.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Le=t=>!!t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function",Me=Symbol.for("signal-exit emitter"),We=globalThis,Hr=Object.defineProperty.bind(Object),Ke=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(We[Me])return We[Me];Hr(We,Me,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,r){this.listeners[e].push(r)}removeListener(e,r){let n=this.listeners[e],i=n.indexOf(r);i!==-1&&(i===0&&n.length===1?n.length=0:n.splice(i,1))}emit(e,r,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let o of this.listeners[e])i=o(r,n)===!0||i;return e==="exit"&&(i=this.emit("afterExit",r,n)||i),i}},Ie=class{},Gr=t=>({onExit(e,r){return t.onExit(e,r)},load(){return t.load()},unload(){return t.unload()}}),He=class extends Ie{onExit(){return()=>{}}load(){}unload(){}},Ge=class extends Ie{#r=qe.platform==="win32"?"SIGINT":"SIGHUP";#t=new Ke;#e;#o;#s;#i={};#n=!1;constructor(e){super(),this.#e=e,this.#i={};for(let r of re)this.#i[r]=()=>{let n=this.#e.listeners(r),{count:i}=this.#t,o=e;if(typeof o.__signal_exit_emitter__=="object"&&typeof o.__signal_exit_emitter__.count=="number"&&(i+=o.__signal_exit_emitter__.count),n.length===i){this.unload();let s=this.#t.emit("exit",null,r),a=r==="SIGHUP"?this.#r:r;s||e.kill(e.pid,a)}};this.#s=e.reallyExit,this.#o=e.emit}onExit(e,r){if(!Le(this.#e))return()=>{};this.#n===!1&&this.load();let n=r?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#n){this.#n=!0,this.#t.count+=1;for(let e of re)try{let r=this.#i[e];r&&this.#e.on(e,r)}catch{}this.#e.emit=(e,...r)=>this.#l(e,...r),this.#e.reallyExit=e=>this.#a(e)}}unload(){this.#n&&(this.#n=!1,re.forEach(e=>{let r=this.#i[e];if(!r)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,r)}catch{}}),this.#e.emit=this.#o,this.#e.reallyExit=this.#s,this.#t.count-=1)}#a(e){return Le(this.#e)?(this.#e.exitCode=e||0,this.#t.emit("exit",this.#e.exitCode,null),this.#s.call(this.#e,this.#e.exitCode)):0}#l(e,...r){let n=this.#o;if(e==="exit"&&Le(this.#e)){typeof r[0]=="number"&&(this.#e.exitCode=r[0]);let i=n.call(this.#e,e,...r);return this.#t.emit("exit",this.#e.exitCode,null),i}else return n.call(this.#e,e,...r)}},qe=globalThis.process,{onExit:Mt,load:pi,unload:mi}=Gr(Le(qe)?new Ge(qe):new He);var Gt=require("node:util");var _e="\x1B[?25l",Kt="\x1B[?25h",Je=(t=1)=>t>0?`\x1B[${t}A`:"",Xe=(t=1)=>t>0?`\x1B[${t}B`:"",ze=(t,e)=>typeof e=="number"&&!Number.isNaN(e)?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`,Wt="\x1B[2K",Ye=t=>t>0?(Wt+Je(1)).repeat(t-1)+Wt+"\x1B[G":"";var Ht=t=>t.split(`
13
- `).length,Jr=t=>t.split(`
14
- `).pop()??"",pe=class{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,r=""){let n=Jr(e),i=(0,Gt.stripVTControlCharacters)(n),o=i;this.rl.line.length>0&&(o=o.slice(0,-this.rl.line.length)),this.rl.setPrompt(o),this.cursorPos=this.rl.getCursorPos();let s=De();e=fe(e,s),r=fe(r,s),i.length%s===0&&(e+=`
10
+ `)}function Ee(){return(0,At.default)({defaultWidth:80,output:Ue().output})}function Mr({active:t,renderedItems:e,pageSize:r,loop:n}){let i=te({lastPointer:t,lastActive:void 0}),{lastPointer:s,lastActive:o}=i.current,a=Math.floor(r/2),c=e.reduce((l,d)=>l+d.length,0),f=e.slice(0,t).reduce((l,d)=>l+d.length,0),m=f;if(c>r)if(n)m=s,o!=null&&o<t&&t-o<r&&(m=Math.min(a,Math.abs(t-o)===1?Math.min(s+(e[o]?.length??0),Math.max(f,s)):s+t-o));else{let l=e.slice(t).reduce((d,g)=>d+g.length,0);m=l<r-a?r-l:Math.min(f,a)}return i.current.lastPointer=m,i.current.lastActive=t,m}function de({items:t,active:e,renderItem:r,pageSize:n,loop:i=!0}){let s=Ee(),o=x=>(x%t.length+t.length)%t.length,a=t.map((x,w)=>x==null?[]:fe(r({item:x,index:w,isActive:w===e}),s).split(`
11
+ `)),c=a.reduce((x,w)=>x+w.length,0),f=x=>a[x]??[],m=Mr({active:e,renderedItems:a,pageSize:n,loop:i}),l=f(e).slice(0,n),d=m+l.length<=n?m:n-l.length,g=Array.from({length:n});g.splice(d,l.length,...l);let p=new Set([e]),h=d+l.length,S=o(e+1);for(;h<n&&!p.has(S)&&(i&&c>n?S!==e:S>e);){let w=f(S).slice(0,n-h);g.splice(h,w.length,...w),p.add(S),h+=w.length,S=o(S+1)}for(h=d-1,S=o(e-1);h>=0&&!p.has(S)&&(i&&c>n?S!==e:S<e);){let x=f(S),w=x.slice(Math.max(0,x.length-h-1));g.splice(h-w.length+1,w.length,...w),p.add(S),h-=w.length,S=o(S-1)}return g.filter(x=>typeof x=="string").join(`
12
+ `)}var Ht=z(require("node:readline"),1),Gt=require("node:async_hooks"),qt=z(kt(),1);var re=[];re.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&re.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&re.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var De=t=>!!t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function",$e=Symbol.for("signal-exit emitter"),Ve=globalThis,Kr=Object.defineProperty.bind(Object),Me=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ve[$e])return Ve[$e];Kr(Ve,$e,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,r){this.listeners[e].push(r)}removeListener(e,r){let n=this.listeners[e],i=n.indexOf(r);i!==-1&&(i===0&&n.length===1?n.length=0:n.splice(i,1))}emit(e,r,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let s of this.listeners[e])i=s(r,n)===!0||i;return e==="exit"&&(i=this.emit("afterExit",r,n)||i),i}},Le=class{},Hr=t=>({onExit(e,r){return t.onExit(e,r)},load(){return t.load()},unload(){return t.unload()}}),We=class extends Le{onExit(){return()=>{}}load(){}unload(){}},Ke=class extends Le{#r=He.platform==="win32"?"SIGINT":"SIGHUP";#t=new Me;#e;#o;#s;#i={};#n=!1;constructor(e){super(),this.#e=e,this.#i={};for(let r of re)this.#i[r]=()=>{let n=this.#e.listeners(r),{count:i}=this.#t,s=e;if(typeof s.__signal_exit_emitter__=="object"&&typeof s.__signal_exit_emitter__.count=="number"&&(i+=s.__signal_exit_emitter__.count),n.length===i){this.unload();let o=this.#t.emit("exit",null,r),a=r==="SIGHUP"?this.#r:r;o||e.kill(e.pid,a)}};this.#s=e.reallyExit,this.#o=e.emit}onExit(e,r){if(!De(this.#e))return()=>{};this.#n===!1&&this.load();let n=r?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#n){this.#n=!0,this.#t.count+=1;for(let e of re)try{let r=this.#i[e];r&&this.#e.on(e,r)}catch{}this.#e.emit=(e,...r)=>this.#l(e,...r),this.#e.reallyExit=e=>this.#a(e)}}unload(){this.#n&&(this.#n=!1,re.forEach(e=>{let r=this.#i[e];if(!r)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,r)}catch{}}),this.#e.emit=this.#o,this.#e.reallyExit=this.#s,this.#t.count-=1)}#a(e){return De(this.#e)?(this.#e.exitCode=e||0,this.#t.emit("exit",this.#e.exitCode,null),this.#s.call(this.#e,this.#e.exitCode)):0}#l(e,...r){let n=this.#o;if(e==="exit"&&De(this.#e)){typeof r[0]=="number"&&(this.#e.exitCode=r[0]);let i=n.call(this.#e,e,...r);return this.#t.emit("exit",this.#e.exitCode,null),i}else return n.call(this.#e,e,...r)}},He=globalThis.process,{onExit:$t,load:pi,unload:mi}=Hr(De(He)?new Ke(He):new We);var Kt=require("node:util");var Ie="\x1B[?25l",Mt="\x1B[?25h",Ge=(t=1)=>t>0?`\x1B[${t}A`:"",qe=(t=1)=>t>0?`\x1B[${t}B`:"",Je=(t,e)=>typeof e=="number"&&!Number.isNaN(e)?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`,Vt="\x1B[2K",Xe=t=>t>0?(Vt+Ge(1)).repeat(t-1)+Vt+"\x1B[G":"";var Wt=t=>t.split(`
13
+ `).length,qr=t=>t.split(`
14
+ `).pop()??"",pe=class{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,r=""){let n=qr(e),i=(0,Kt.stripVTControlCharacters)(n),s=i;this.rl.line.length>0&&(s=s.slice(0,-this.rl.line.length)),this.rl.setPrompt(s),this.cursorPos=this.rl.getCursorPos();let o=Ee();e=fe(e,o),r=fe(r,o),i.length%o===0&&(e+=`
15
15
  `);let a=e+(r?`
16
- `+r:""),d=Math.floor(i.length/s)-this.cursorPos.rows+(r?Ht(r):0);d>0&&(a+=Je(d)),a+=ze(this.cursorPos.cols),this.write(Xe(this.extraLinesUnderPrompt)+Ye(this.height)+a),this.extraLinesUnderPrompt=d,this.height=Ht(a)}checkCursorPos(){let e=this.rl.getCursorPos();e.cols!==this.cursorPos.cols&&(this.write(ze(e.cols)),this.cursorPos=e)}done({clearContent:e}){this.rl.setPrompt("");let r=Xe(this.extraLinesUnderPrompt);r+=e?Ye(this.height):`
17
- `,r+="\x1B[G",r+=Kt,this.write(r),this.rl.close()}};var Pe=class extends Promise{static withResolver(){let e,r;return{promise:new Promise((i,o)=>{e=i,r=o}),resolve:e,reject:r}}};var zt=z(require("node:path"),1),Xr=globalThis.setImmediate;function zr(){let t=Error.prepareStackTrace,e=[];try{Error.prepareStackTrace=(r,n)=>{let i=n.slice(1);return e=i,i},new Error().stack}catch{return e}return Error.prepareStackTrace=t,e}function G(t){let e=zr();return(n,i={})=>{let{input:o=process.stdin,signal:s}=i,a=new Set,p=new Xt.default;p.pipe(i.output??process.stdout);let d=qt.createInterface({terminal:!0,input:o,output:p});p.mute();let h=new pe(d),{promise:l,resolve:u,reject:g}=Pe.withResolver(),f=()=>g(new be);if(s){let S=()=>g(new xe({cause:s.reason}));if(s.aborted)return S(),Object.assign(l,{cancel:f});s.addEventListener("abort",S),a.add(()=>s.removeEventListener("abort",S))}a.add(Mt((S,b)=>{g(new ue(`User force closed the prompt with ${S} ${b}`))}));let m=()=>g(new ue("User force closed the prompt with SIGINT"));return d.on("SIGINT",m),a.add(()=>d.removeListener("SIGINT",m)),mt(d,S=>{let b=Jt.AsyncResource.bind(()=>Z.clearAll());d.on("close",b),a.add(()=>d.removeListener("close",b));let w=()=>{let v=()=>h.checkCursorPos();d.input.on("keypress",v),a.add(()=>d.input.removeListener("keypress",v));let L=null;S(()=>{let P=!1;try{let I=t(n,c=>{P?u(c):L={value:c}});if(I===void 0){let c=e[1]?.getFileName();throw c&&!c.startsWith("file://")&&(c=zt.default.resolve(c)),new Error(`Prompt functions must return a string.
18
- at ${c}`)}let[R,T]=typeof I=="string"?[I]:I;h.render(R,T),Z.run()}catch(I){g(I)}if(P=!0,L!==null){let{value:I}=L;L=null,u(I)}})};return"readableFlowing"in o?Xr(w):w(),Object.assign(l.then(v=>(Z.clearAll(),v),v=>{throw Z.clearAll(),v}).finally(()=>{a.forEach(v=>v()),h.done({clearContent:!!i.clearPromptOnDone}),p.end()}).then(()=>l),{cancel:f})})}}var Yt=require("node:util");var _=class{separator=(0,Yt.styleText)("dim",Array.from({length:15}).join(O.line));type="separator";constructor(e){e&&(this.separator=e)}static isSeparator(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="separator")}};var X=require("node:util");var Yr={icon:{checked:(0,X.styleText)("green",O.circleFilled),unchecked:O.circle,cursor:O.pointer,disabledChecked:(0,X.styleText)("green",O.circleDouble),disabledUnchecked:"-"},style:{disabled:t=>(0,X.styleText)("dim",t),renderSelectedChoices:t=>t.map(e=>e.short).join(", "),description:t=>(0,X.styleText)("cyan",t),keysHelpTip:t=>t.map(([e,r])=>`${(0,X.styleText)("bold",e)} ${(0,X.styleText)("dim",r)}`).join((0,X.styleText)("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be toggled."}};function Re(t){return!_.isSeparator(t)&&!t.disabled}function Qe(t){return!_.isSeparator(t)}function Qt(t){return!_.isSeparator(t)&&t.checked}function Ze(t){return Re(t)?{...t,checked:!t.checked}:t}function Qr(t){return function(e){return Re(e)?{...e,checked:t}:e}}function Zr(t){return t.map(e=>{if(_.isSeparator(e))return e;if(typeof e!="object"||e===null||!("value"in e)){let i=String(e);return{value:e,name:i,short:i,checkedName:i,disabled:!1,checked:!1}}let r=e.name??String(e.value),n={value:e.value,name:r,short:e.short??r,checkedName:e.checkedName??r,disabled:e.disabled??!1,checked:e.checked??!1};return e.description&&(n.description=e.description),n})}var et=G((t,e)=>{let{pageSize:r=7,loop:n=!0,required:i,validate:o=()=>!0}=t,s={all:"a",invert:"i",...t.shortcuts},a=j(Yr,t.theme),{keybindings:p}=a,[d,h]=D("idle"),l=W({status:d,theme:a}),[u,g]=D(Zr(t.choices)),f=ee(()=>{let c=u.findIndex(Qe),x=u.findLastIndex(Qe);if(c===-1)throw new J("[checkbox prompt] No selectable choices. All choices are disabled.");return{first:c,last:x}},[u]),[m,S]=D(f.first),[b,w]=D();K(async c=>{if($(c)){let x=u.filter(Qt),y=await o([...x]);i&&!x.length?w("At least one choice must be selected"):y===!0?(h("done"),e(x.map(E=>E.value))):w(y||"You must select a valid value")}else if(V(c,p)||Y(c,p)){if(b&&w(void 0),n||V(c,p)&&m!==f.first||Y(c,p)&&m!==f.last){let x=V(c,p)?-1:1,y=m;do y=(y+x+u.length)%u.length;while(!Qe(u[y]));S(y)}}else if(Ne(c)){let x=u[m];x&&!_.isSeparator(x)&&(x.disabled?w(a.i18n.disabledError):(w(void 0),g(u.map((y,E)=>E===m?Ze(y):y))))}else if(c.name===s.all){let x=u.some(y=>Re(y)&&!y.checked);g(u.map(Qr(x)))}else if(c.name===s.invert)g(u.map(Ze));else if(ce(c)){let x=Number(c.name)-1,y=-1,E=u.findIndex(A=>_.isSeparator(A)?!1:(y++,y===x)),C=u[E];C&&Re(C)&&(S(E),g(u.map((A,U)=>U===E?Ze(A):A)))}});let v=a.style.message(t.message,d),L,P=de({items:u,active:m,renderItem({item:c,isActive:x}){if(_.isSeparator(c))return` ${c.separator}`;let y=x?a.icon.cursor:" ";if(c.disabled){let U=typeof c.disabled=="string"?c.disabled:"(disabled)",Ce=c.checked?a.icon.disabledChecked:a.icon.disabledUnchecked;return a.style.disabled(`${y}${Ce} ${c.name} ${U}`)}x&&(L=c.description);let E=c.checked?a.icon.checked:a.icon.unchecked,C=c.checked?c.checkedName:c.name;return(x?a.style.highlight:U=>U)(`${y}${E} ${C}`)},pageSize:r,loop:n});if(d==="done"){let c=u.filter(Qt),x=a.style.answer(a.style.renderSelectedChoices(c,u));return[l,v,x].filter(Boolean).join(" ")}let I=[["\u2191\u2193","navigate"],["space","select"]];s.all&&I.push([s.all,"all"]),s.invert&&I.push([s.invert,"invert"]),I.push(["\u23CE","submit"]);let R=a.style.keysHelpTip(I);return`${[[l,v].filter(Boolean).join(" "),P," ",L?a.style.description(L):"",b?a.style.error(b):"",R].filter(Boolean).join(`
19
- `).trimEnd()}${_e}`});function Zt(t,e){let r=e!==!1;return/^(y|yes)/i.test(t)?r=!0:/^(n|no)/i.test(t)&&(r=!1),r}function er(t){return t?"Yes":"No"}var tt=G((t,e)=>{let{transformer:r=er}=t,[n,i]=D("idle"),[o,s]=D(""),a=j(t.theme),p=W({status:n,theme:a});K((u,g)=>{if(n==="idle")if($(u)){let f=Zt(o,t.default);s(r(f)),i("done"),e(f)}else if(le(u)){let f=er(!Zt(o,t.default));g.clearLine(0),g.write(f),s(f)}else s(g.line)});let d=o,h="";n==="done"?d=a.style.answer(o):h=` ${a.style.defaultAnswer(t.default===!1?"y/N":"Y/n")}`;let l=a.style.message(t.message,n);return`${p} ${l}${h} ${d}`});var en={validationFailureMode:"keep"},ie=G((t,e)=>{let{prefill:r="tab"}=t,n=j(en,t.theme),[i,o]=D("idle"),[s,a]=D(String(t.default??"")),[p,d]=D(),[h,l]=D(""),u=W({status:i,theme:n});async function g(w){let{required:v,pattern:L,patternError:P="Invalid input"}=t;return v&&!w?"You must provide a value":L&&!L.test(w)?P:typeof t.validate=="function"?await t.validate(w)||"You must provide a valid value":!0}K(async(w,v)=>{if(i==="idle")if($(w)){let L=h||s;o("loading");let P=await g(L);P===!0?(l(L),o("done"),e(L)):(n.validationFailureMode==="clear"?l(""):v.write(h),d(P),o("idle"))}else ae(w)&&!h?a(""):le(w)&&!h?(a(""),v.clearLine(0),v.write(s),l(s)):(l(v.line),d(void 0))}),M(w=>{r==="editable"&&s&&(w.write(s),l(s))},[]);let f=n.style.message(t.message,i),m=h;typeof t.transformer=="function"?m=t.transformer(h,{isFinal:i==="done"}):i==="done"&&(m=n.style.answer(h));let S;s&&i!=="done"&&!h&&(S=n.style.defaultAnswer(s));let b="";return p&&(b=n.style.error(p)),[[u,f,S,m].filter(w=>w!==void 0).join(" "),b]});var oe=require("node:util");var tn={icon:{cursor:O.pointer},style:{disabled:t=>(0,oe.styleText)("dim",t),description:t=>(0,oe.styleText)("cyan",t),keysHelpTip:t=>t.map(([e,r])=>`${(0,oe.styleText)("bold",e)} ${(0,oe.styleText)("dim",r)}`).join((0,oe.styleText)("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function rt(t){return!_.isSeparator(t)&&!t.disabled}function nt(t){return!_.isSeparator(t)}function rn(t){return t.map(e=>{if(_.isSeparator(e))return e;if(typeof e!="object"||e===null||!("value"in e)){let i=String(e);return{value:e,name:i,short:i,disabled:!1}}let r=e.name??String(e.value),n={value:e.value,name:r,short:e.short??r,disabled:e.disabled??!1};return e.description&&(n.description=e.description),n})}var Te=G((t,e)=>{let{loop:r=!0,pageSize:n=7}=t,i=j(tn,t.theme),{keybindings:o}=i,[s,a]=D("idle"),p=W({status:s,theme:i}),d=te(),h=!o.includes("vim"),l=ee(()=>rn(t.choices),[t.choices]),u=ee(()=>{let c=l.findIndex(nt),x=l.findLastIndex(nt);if(c===-1)throw new J("[select prompt] No selectable choices. All choices are disabled.");return{first:c,last:x}},[l]),g=ee(()=>"default"in t?l.findIndex(c=>rt(c)&&c.value===t.default):-1,[t.default,l]),[f,m]=D(g===-1?u.first:g),S=l[f];if(S==null||_.isSeparator(S))throw new Error("Active index does not point to a choice");let[b,w]=D();K((c,x)=>{if(clearTimeout(d.current),b&&w(void 0),$(c))S.disabled?w(i.i18n.disabledError):(a("done"),e(S.value));else if(V(c,o)||Y(c,o)){if(x.clearLine(0),r||V(c,o)&&f!==u.first||Y(c,o)&&f!==u.last){let y=V(c,o)?-1:1,E=f;do E=(E+y+l.length)%l.length;while(!nt(l[E]));m(E)}}else if(ce(c)&&!Number.isNaN(Number(x.line))){let y=Number(x.line)-1,E=-1,C=l.findIndex(U=>_.isSeparator(U)?!1:(E++,E===y)),A=l[C];A!=null&&rt(A)&&m(C),d.current=setTimeout(()=>{x.clearLine(0)},700)}else if(ae(c))x.clearLine(0);else if(h){let y=x.line.toLowerCase(),E=l.findIndex(C=>_.isSeparator(C)||!rt(C)?!1:C.name.toLowerCase().startsWith(y));E!==-1&&m(E),d.current=setTimeout(()=>{x.clearLine(0)},700)}}),M(()=>()=>{clearTimeout(d.current)},[]);let v=i.style.message(t.message,s),L=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]),P=0,I=de({items:l,active:f,renderItem({item:c,isActive:x,index:y}){if(_.isSeparator(c))return P++,` ${c.separator}`;let E=x?i.icon.cursor:" ",C=i.indexMode==="number"?`${y+1-P}. `:"";if(c.disabled){let U=typeof c.disabled=="string"?c.disabled:"(disabled)",Ce=x?i.icon.cursor:"-";return i.style.disabled(`${Ce} ${C}${c.name} ${U}`)}return(x?i.style.highlight:U=>U)(`${E} ${C}${c.name}`)},pageSize:n,loop:r});if(s==="done")return[p,v,i.style.answer(S.short)].filter(Boolean).join(" ");let{description:R}=S;return`${[[p,v].filter(Boolean).join(" "),I," ",R?i.style.description(R):"",b?i.style.error(b):"",L].filter(Boolean).join(`
20
- `).trimEnd()}${_e}`});(async()=>{let e=!process.argv.slice(2).includes("--no-project-filter");try{let r=await new he(process.cwd()).loadProjectConfig();console.info("## Add New VEX Statement ##");let n=await ie({message:"CVE name (e.g. CVE-2023-52070)",required:!0}),i=r.projects.filter(f=>!e||f.enabled&&!f.silent).map(f=>({name:`${f.name}@${f.version}`,value:f.purl}));i.sort((f,m)=>f.name.localeCompare(m.name));let o=await et({message:"Projects to add",choices:i,required:!0,pageSize:15}),s=(0,tr.resolve)(r.vexDir,`${n}.json`),a=["under_investigation","affected","fixed","not_affected"],p=await Te({message:"Status?",choices:a.map(f=>({name:f,value:f})),default:a[a.length-1]}),d={};switch(p){case"affected":{let f=await ie({message:"Action statement?",required:!0});d.actionStatement=f;break}case"not_affected":{let m=await Te({message:"Justification?",choices:["none","component_not_present","vulnerable_code_not_present","vulnerable_code_not_in_execute_path","vulnerable_code_cannot_be_controlled_by_adversary","inline_mitigations_already_exist"].map(b=>({name:b,value:b}))});m!=="none"&&(d.justification=m);let S=await ie({message:"Impact statement?",required:m==="none"});S&&(d.impactStatement=S);break}case"fixed":{let f=await ie({message:"Status note?"});f&&(d.statusNotes=f);break}}let h=new Date().toISOString(),l=lt({cveName:n,purls:Array.from(o),status:p,timestamp:h,...d});await tt({message:`Following statement will be added to ${s}:
16
+ `+r:""),f=Math.floor(i.length/o)-this.cursorPos.rows+(r?Wt(r):0);f>0&&(a+=Ge(f)),a+=Je(this.cursorPos.cols),this.write(qe(this.extraLinesUnderPrompt)+Xe(this.height)+a),this.extraLinesUnderPrompt=f,this.height=Wt(a)}checkCursorPos(){let e=this.rl.getCursorPos();e.cols!==this.cursorPos.cols&&(this.write(Je(e.cols)),this.cursorPos=e)}done({clearContent:e}){this.rl.setPrompt("");let r=qe(this.extraLinesUnderPrompt);r+=e?Xe(this.height):`
17
+ `,r+="\x1B[G",r+=Mt,this.write(r),this.rl.close()}};var Pe=class extends Promise{static withResolver(){let e,r;return{promise:new Promise((i,s)=>{e=i,r=s}),resolve:e,reject:r}}};var Jt=z(require("node:path"),1),Jr=globalThis.setImmediate;function Xr(){let t=Error.prepareStackTrace,e=[];try{Error.prepareStackTrace=(r,n)=>{let i=n.slice(1);return e=i,i},new Error().stack}catch{return e}return Error.prepareStackTrace=t,e}function H(t){let e=Xr();return(n,i={})=>{let{input:s=process.stdin,signal:o}=i,a=new Set,c=new qt.default;c.pipe(i.output??process.stdout);let f=Ht.createInterface({terminal:!0,input:s,output:c});c.mute();let m=new pe(f),{promise:l,resolve:d,reject:g}=Pe.withResolver(),p=()=>g(new be);if(o){let S=()=>g(new we({cause:o.reason}));if(o.aborted)return S(),Object.assign(l,{cancel:p});o.addEventListener("abort",S),a.add(()=>o.removeEventListener("abort",S))}a.add($t((S,x)=>{g(new ue(`User force closed the prompt with ${S} ${x}`))}));let h=()=>g(new ue("User force closed the prompt with SIGINT"));return f.on("SIGINT",h),a.add(()=>f.removeListener("SIGINT",h)),dt(f,S=>{let x=Gt.AsyncResource.bind(()=>Z.clearAll());f.on("close",x),a.add(()=>f.removeListener("close",x));let w=()=>{let v=()=>m.checkCursorPos();f.input.on("keypress",v),a.add(()=>f.input.removeListener("keypress",v));let L=null;S(()=>{let _=!1;try{let I=t(n,u=>{_?d(u):L={value:u}});if(I===void 0){let u=e[1]?.getFileName();throw u&&!u.startsWith("file://")&&(u=Jt.default.resolve(u)),new Error(`Prompt functions must return a string.
18
+ at ${u}`)}let[R,C]=typeof I=="string"?[I]:I;m.render(R,C),Z.run()}catch(I){g(I)}if(_=!0,L!==null){let{value:I}=L;L=null,d(I)}})};return"readableFlowing"in s?Jr(w):w(),Object.assign(l.then(v=>(Z.clearAll(),v),v=>{throw Z.clearAll(),v}).finally(()=>{a.forEach(v=>v()),m.done({clearContent:!!i.clearPromptOnDone}),c.end()}).then(()=>l),{cancel:p})})}}var Xt=require("node:util");var P=class{separator=(0,Xt.styleText)("dim",Array.from({length:15}).join(N.line));type="separator";constructor(e){e&&(this.separator=e)}static isSeparator(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="separator")}};var X=require("node:util");var zr={icon:{checked:(0,X.styleText)("green",N.circleFilled),unchecked:N.circle,cursor:N.pointer,disabledChecked:(0,X.styleText)("green",N.circleDouble),disabledUnchecked:"-"},style:{disabled:t=>(0,X.styleText)("dim",t),renderSelectedChoices:t=>t.map(e=>e.short).join(", "),description:t=>(0,X.styleText)("cyan",t),keysHelpTip:t=>t.map(([e,r])=>`${(0,X.styleText)("bold",e)} ${(0,X.styleText)("dim",r)}`).join((0,X.styleText)("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be toggled."}};function _e(t){return!P.isSeparator(t)&&!t.disabled}function ze(t){return!P.isSeparator(t)}function zt(t){return!P.isSeparator(t)&&t.checked}function Ye(t){return _e(t)?{...t,checked:!t.checked}:t}function Yr(t){return function(e){return _e(e)?{...e,checked:t}:e}}function Qr(t){return t.map(e=>{if(P.isSeparator(e))return e;if(typeof e!="object"||e===null||!("value"in e)){let i=String(e);return{value:e,name:i,short:i,checkedName:i,disabled:!1,checked:!1}}let r=e.name??String(e.value),n={value:e.value,name:r,short:e.short??r,checkedName:e.checkedName??r,disabled:e.disabled??!1,checked:e.checked??!1};return e.description&&(n.description=e.description),n})}var Qe=H((t,e)=>{let{pageSize:r=7,loop:n=!0,required:i,validate:s=()=>!0}=t,o={all:"a",invert:"i",...t.shortcuts},a=A(zr,t.theme),{keybindings:c}=a,[f,m]=D("idle"),l=M({status:f,theme:a}),[d,g]=D(Qr(t.choices)),p=ee(()=>{let u=d.findIndex(ze),b=d.findLastIndex(ze);if(u===-1)throw new J("[checkbox prompt] No selectable choices. All choices are disabled.");return{first:u,last:b}},[d]),[h,S]=D(p.first),[x,w]=D();W(async u=>{if($(u)){let b=d.filter(zt),y=await s([...b]);i&&!b.length?w("At least one choice must be selected"):y===!0?(m("done"),e(b.map(E=>E.value))):w(y||"You must select a valid value")}else if(k(u,c)||Y(u,c)){if(x&&w(void 0),n||k(u,c)&&h!==p.first||Y(u,c)&&h!==p.last){let b=k(u,c)?-1:1,y=h;do y=(y+b+d.length)%d.length;while(!ze(d[y]));S(y)}}else if(je(u)){let b=d[h];b&&!P.isSeparator(b)&&(b.disabled?w(a.i18n.disabledError):(w(void 0),g(d.map((y,E)=>E===h?Ye(y):y))))}else if(u.name===o.all){let b=d.some(y=>_e(y)&&!y.checked);g(d.map(Yr(b)))}else if(u.name===o.invert)g(d.map(Ye));else if(ce(u)){let b=Number(u.name)-1,y=-1,E=d.findIndex(O=>P.isSeparator(O)?!1:(y++,y===b)),T=d[E];T&&_e(T)&&(S(E),g(d.map((O,U)=>U===E?Ye(O):O)))}});let v=a.style.message(t.message,f),L,_=de({items:d,active:h,renderItem({item:u,isActive:b}){if(P.isSeparator(u))return` ${u.separator}`;let y=b?a.icon.cursor:" ";if(u.disabled){let U=typeof u.disabled=="string"?u.disabled:"(disabled)",Ce=u.checked?a.icon.disabledChecked:a.icon.disabledUnchecked;return a.style.disabled(`${y}${Ce} ${u.name} ${U}`)}b&&(L=u.description);let E=u.checked?a.icon.checked:a.icon.unchecked,T=u.checked?u.checkedName:u.name;return(b?a.style.highlight:U=>U)(`${y}${E} ${T}`)},pageSize:r,loop:n});if(f==="done"){let u=d.filter(zt),b=a.style.answer(a.style.renderSelectedChoices(u,d));return[l,v,b].filter(Boolean).join(" ")}let I=[["\u2191\u2193","navigate"],["space","select"]];o.all&&I.push([o.all,"all"]),o.invert&&I.push([o.invert,"invert"]),I.push(["\u23CE","submit"]);let R=a.style.keysHelpTip(I);return`${[[l,v].filter(Boolean).join(" "),_," ",L?a.style.description(L):"",x?a.style.error(x):"",R].filter(Boolean).join(`
19
+ `).trimEnd()}${Ie}`});function Yt(t,e){let r=e!==!1;return/^(y|yes)/i.test(t)?r=!0:/^(n|no)/i.test(t)&&(r=!1),r}function Qt(t){return t?"Yes":"No"}var Ze=H((t,e)=>{let{transformer:r=Qt}=t,[n,i]=D("idle"),[s,o]=D(""),a=A(t.theme),c=M({status:n,theme:a});W((d,g)=>{if(n==="idle")if($(d)){let p=Yt(s,t.default);o(r(p)),i("done"),e(p)}else if(le(d)){let p=Qt(!Yt(s,t.default));g.clearLine(0),g.write(p),o(p)}else o(g.line)});let f=s,m="";n==="done"?f=a.style.answer(s):m=` ${a.style.defaultAnswer(t.default===!1?"y/N":"Y/n")}`;let l=a.style.message(t.message,n);return`${c} ${l}${m} ${f}`});var Zr={validationFailureMode:"keep"},ie=H((t,e)=>{let{prefill:r="tab"}=t,n=A(Zr,t.theme),[i,s]=D("idle"),[o,a]=D(String(t.default??"")),[c,f]=D(),[m,l]=D(""),d=M({status:i,theme:n});async function g(w){let{required:v,pattern:L,patternError:_="Invalid input"}=t;return v&&!w?"You must provide a value":L&&!L.test(w)?_:typeof t.validate=="function"?await t.validate(w)||"You must provide a valid value":!0}W(async(w,v)=>{if(i==="idle")if($(w)){let L=m||o;s("loading");let _=await g(L);_===!0?(l(L),s("done"),e(L)):(n.validationFailureMode==="clear"?l(""):v.write(m),f(_),s("idle"))}else ae(w)&&!m?a(""):le(w)&&!m?(a(""),v.clearLine(0),v.write(o),l(o)):(l(v.line),f(void 0))}),V(w=>{r==="editable"&&o&&(w.write(o),l(o))},[]);let p=n.style.message(t.message,i),h=m;typeof t.transformer=="function"?h=t.transformer(m,{isFinal:i==="done"}):i==="done"&&(h=n.style.answer(m));let S;o&&i!=="done"&&!m&&(S=n.style.defaultAnswer(o));let x="";return c&&(x=n.style.error(c)),[[d,p,S,h].filter(w=>w!==void 0).join(" "),x]});var oe=require("node:util");var en={icon:{cursor:N.pointer},style:{disabled:t=>(0,oe.styleText)("dim",t),description:t=>(0,oe.styleText)("cyan",t),keysHelpTip:t=>t.map(([e,r])=>`${(0,oe.styleText)("bold",e)} ${(0,oe.styleText)("dim",r)}`).join((0,oe.styleText)("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function et(t){return!P.isSeparator(t)&&!t.disabled}function tt(t){return!P.isSeparator(t)}function tn(t){return t.map(e=>{if(P.isSeparator(e))return e;if(typeof e!="object"||e===null||!("value"in e)){let i=String(e);return{value:e,name:i,short:i,disabled:!1}}let r=e.name??String(e.value),n={value:e.value,name:r,short:e.short??r,disabled:e.disabled??!1};return e.description&&(n.description=e.description),n})}var Re=H((t,e)=>{let{loop:r=!0,pageSize:n=7}=t,i=A(en,t.theme),{keybindings:s}=i,[o,a]=D("idle"),c=M({status:o,theme:i}),f=te(),m=!s.includes("vim"),l=ee(()=>tn(t.choices),[t.choices]),d=ee(()=>{let u=l.findIndex(tt),b=l.findLastIndex(tt);if(u===-1)throw new J("[select prompt] No selectable choices. All choices are disabled.");return{first:u,last:b}},[l]),g=ee(()=>"default"in t?l.findIndex(u=>et(u)&&u.value===t.default):-1,[t.default,l]),[p,h]=D(g===-1?d.first:g),S=l[p];if(S==null||P.isSeparator(S))throw new Error("Active index does not point to a choice");let[x,w]=D();W((u,b)=>{if(clearTimeout(f.current),x&&w(void 0),$(u))S.disabled?w(i.i18n.disabledError):(a("done"),e(S.value));else if(k(u,s)||Y(u,s)){if(b.clearLine(0),r||k(u,s)&&p!==d.first||Y(u,s)&&p!==d.last){let y=k(u,s)?-1:1,E=p;do E=(E+y+l.length)%l.length;while(!tt(l[E]));h(E)}}else if(ce(u)&&!Number.isNaN(Number(b.line))){let y=Number(b.line)-1,E=-1,T=l.findIndex(U=>P.isSeparator(U)?!1:(E++,E===y)),O=l[T];O!=null&&et(O)&&h(T),f.current=setTimeout(()=>{b.clearLine(0)},700)}else if(ae(u))b.clearLine(0);else if(m){let y=b.line.toLowerCase(),E=l.findIndex(T=>P.isSeparator(T)||!et(T)?!1:T.name.toLowerCase().startsWith(y));E!==-1&&h(E),f.current=setTimeout(()=>{b.clearLine(0)},700)}}),V(()=>()=>{clearTimeout(f.current)},[]);let v=i.style.message(t.message,o),L=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]),_=0,I=de({items:l,active:p,renderItem({item:u,isActive:b,index:y}){if(P.isSeparator(u))return _++,` ${u.separator}`;let E=b?i.icon.cursor:" ",T=i.indexMode==="number"?`${y+1-_}. `:"";if(u.disabled){let U=typeof u.disabled=="string"?u.disabled:"(disabled)",Ce=b?i.icon.cursor:"-";return i.style.disabled(`${Ce} ${T}${u.name} ${U}`)}return(b?i.style.highlight:U=>U)(`${E} ${T}${u.name}`)},pageSize:n,loop:r});if(o==="done")return[c,v,i.style.answer(S.short)].filter(Boolean).join(" ");let{description:R}=S;return`${[[c,v].filter(Boolean).join(" "),I," ",R?i.style.description(R):"",x?i.style.error(x):"",L].filter(Boolean).join(`
20
+ `).trimEnd()}${Ie}`});(async()=>{let e=!process.argv.slice(2).includes("--no-project-filter");try{let r=await new he(process.cwd()).loadProjectConfig();console.info("## Add New VEX Statement ##");let n=await ie({message:"CVE name (e.g. CVE-2023-52070)",required:!0}),i=r.projects.filter(p=>!e||p.enabled&&!p.silent).map(p=>({name:`${p.name}@${p.version}`,value:p.purl}));i.sort((p,h)=>p.name.localeCompare(h.name));let s=await Qe({message:"Projects to add",choices:i,required:!0,pageSize:15}),o=(0,Zt.resolve)(r.vexDir,`${n}.json`),a=["under_investigation","affected","fixed","not_affected"],c=await Re({message:"Status?",choices:a.map(p=>({name:p,value:p})),default:a[a.length-1]}),f={};switch(c){case"affected":{let p=await ie({message:"Action statement?",required:!0});f.actionStatement=p;break}case"not_affected":{let h=await Re({message:"Justification?",choices:["none","component_not_present","vulnerable_code_not_present","vulnerable_code_not_in_execute_path","vulnerable_code_cannot_be_controlled_by_adversary","inline_mitigations_already_exist"].map(x=>({name:x,value:x}))});h!=="none"&&(f.justification=h);let S=await ie({message:"Impact statement?",required:h==="none"});S&&(f.impactStatement=S);break}case"fixed":{let p=await ie({message:"Status note?"});p&&(f.statusNotes=p);break}}let m=new Date().toISOString(),l=st({cveName:n,purls:Array.from(s),status:c,timestamp:m,...f});await Ze({message:`Following statement will be added to ${o}:
21
21
  ${JSON.stringify(l,null,2)}
22
22
 
23
- Do you want to proceed?`})||(console.log("Aborted."),process.exit(0));let g=new se(s);await g.read(),g.upsert(l),await g.write()}catch(r){console.error(`Error: ${r}`),process.exitCode=1}})();
23
+ Do you want to proceed?`})||(console.log("Aborted."),process.exit(0));let g=new se(o);await g.read(),g.upsert(l),await g.write()}catch(r){console.error(`Error: ${r}`),process.exitCode=1}})();
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Ae=Object.create;var pe=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var Oe=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Ne=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ke(e))!Ie.call(t,o)&&o!==r&&pe(t,o,{get:()=>e[o],enumerable:!(n=Ce(e,o))||n.enumerable});return t};var me=(t,e,r)=>(r=t!=null?Ae(Oe(t)):{},Ne(e||!t||!t.__esModule?pe(r,"default",{value:t,enumerable:!0}):r,t));var ue=require("path");var C=me(require("path")),ne=require("fs/promises");var w=require("fs/promises");async function W(t){try{return await Te(t)?JSON.parse(await(0,w.readFile)(t,{encoding:"utf-8"})):void 0}catch(e){throw new Error(`Error reading JSON file ${t}: ${e}`,{cause:e})}}async function ge(t,e){let r=JSON.stringify(e,null,4)+`
3
- `,n=await _e(t,r);await(0,w.writeFile)(t,n,{encoding:"utf-8"})}async function Te(t){try{return await(0,w.access)(t,w.constants.F_OK),!0}catch{return!1}}async function _e(t,e){let r=await Fe();if(!r)return e;let n=await r.resolveConfig(t);return n?await r.format(e,{...n,filepath:t}):e}var De;function Fe(){return De??=import("prettier").catch(()=>{})}var H={UNKNOWN:0,LOW:1,MEDIUM:2,HIGH:3,CRITICAL:4},$=["UNKNOWN","LOW","MEDIUM","HIGH","CRITICAL"];function U(t,e){return H[t]-H[e]}function J(t,e){return H[t]<H[e]}var ie=class t{constructor(e){this.workingDir=e}workingDir;static DEFAULT_MAVEN_REPO="https://repository.conterra.de/repository/maven-mirror-ct";static DEFAULT_VEX_SUBDIR="input/vex";static DEFAULT_OUT_SUBDIR="output";static DEFAULT_CACHE_SUBDIR="cache";static DEFAULT_SCANNERS=["grype","trivy","ossindex"];normalize(e,r){let n=e.findNoLongerDetectedVulnerabilitiesOnlyForSnapshots??!1;return{projectConfigFileLocation:r,onNewVulnerabilities:e.onNewVulnerabilities??(e.failOnNewVulnerabilities?"fail":"warn"),onNoLongerDetectedVulnerabilities:e.onNoLongerDetectedVulnerabilities??"ignore",reportNoLongerDetectedVulnerabilities:e.reportNoLongerDetectedVulnerabilities??!0,consoleReport:e.consoleReport??"BY_PROJECT_DETAILED",createSubDirsForProject:e.createSubDirsForProject??!0,mavenRepo:e.mavenRepo??t.DEFAULT_MAVEN_REPO,vexUrls:e.vexUrls??[],vexDir:this.resolvePath(e.vexDir)??(0,C.resolve)(this.workingDir,t.DEFAULT_VEX_SUBDIR),outDir:this.resolvePath(e.outDir)??(0,C.resolve)(this.workingDir,t.DEFAULT_OUT_SUBDIR),cacheDir:this.resolvePath(e.cacheDir)??(0,C.resolve)(this.workingDir,t.DEFAULT_CACHE_SUBDIR),scanners:this.normalizeScanners(e.scanners,r),projects:this.normalizeProjects(e.projects??[],n)}}normalizeScanners(e,r){return(e??t.DEFAULT_SCANNERS).map(o=>{if(typeof o!="string")throw new Error(`Invalid scanner name '${String(o)}' in configuration file '${r}'`);let i=o.split("@");if(i.length>2)throw new Error(`Invalid scanner name '${o}' in configuration file '${r}'`);return{name:i[0],version:i[1]??""}})}normalizeProjects(e,r){return e.map(n=>{let o=n;if(!o.name)throw new Error("Project name is missing on entry: "+JSON.stringify(o));if(!o.version)throw new Error("Project version is missing on entry: "+JSON.stringify(o));if(!o.purl)throw new Error("Project purl is missing on entry: "+JSON.stringify(o));let i={...o,purlAliases:o.purlAliases??[],enabled:o.enabled??!0,silent:o.silent??!1,minimumSeverity:o.minimumSeverity??"UNKNOWN"};return i.sbomFile?{...i,sbomFile:this.resolvePath(i.sbomFile)??i.sbomFile}:{...i,detectNoLongerUsedVulnerabilities:r?i.purl.endsWith("-SNAPSHOT"):!0}})}resolvePath(e){if(e)return C.default.isAbsolute(e)?e:(0,C.resolve)(this.workingDir,e)}},T=class{constructor(e){this.workingDir=e;this.normalizer=new ie(e)}workingDir;normalizer;projectConfigCache;async loadProjectConfig(){return this.projectConfigCache??=this.doLoadProjectConfig(),this.projectConfigCache}async doLoadProjectConfig(){let e=(0,C.resolve)(this.workingDir,"vuln-scan-conf.json"),r=await W(e);if(!r)throw new Error(`Missing project configuration file '${e}'`);return this.normalizer.normalize(r,e)}async loadJiraConfig(e){let r=await(0,ne.readFile)(e,"utf8"),n=JSON.parse(r);if(!n.issues&&n.issue&&(n.issues=n.issue),!n.jiraUrl||typeof n.jiraUrl!="string")throw new Error("jira-conf.json: missing or invalid 'jiraUrl' field");if(!Array.isArray(n.issues))throw new Error("jira-conf.json: missing or invalid 'issues' array");this.validateAutoCloseSeverity(n.autoCloseBelowSeverity,"jira-conf.json: invalid 'autoCloseBelowSeverity'");for(let[o,i]of n.issues.entries())i&&typeof i=="object"&&this.validateAutoCloseSeverity(i.autoCloseBelowSeverity,`jira-conf.json: invalid 'issues[${o}].autoCloseBelowSeverity'`);return n}validateAutoCloseSeverity(e,r){if(e!==void 0&&!$.includes(e))throw new Error(`${r} value '${String(e)}'. Must be one of: ${$.join(", ")}`)}async loadAutoVexConfig(e){let r=await(0,ne.readFile)(e,"utf8"),n=JSON.parse(r);if(!n.impactStatement||typeof n.impactStatement!="string")throw new Error("auto-vex-conf.json: missing or invalid 'impactStatement' field (must be a non-empty string)");if(n.maxSeverity!==void 0&&!$.includes(n.maxSeverity))throw new Error(`auto-vex-conf.json: invalid 'maxSeverity' value '${String(n.maxSeverity)}'. Must be one of: ${$.join(", ")}`);if(n.projectOverrides!==void 0){if(!Array.isArray(n.projectOverrides))throw new Error("auto-vex-conf.json: 'projectOverrides' must be an array");for(let[o,i]of n.projectOverrides.entries()){if(!i||typeof i!="object")throw new Error(`auto-vex-conf.json: 'projectOverrides[${o}]' must be an object`);let s=i;if(!Array.isArray(s.projects)||s.projects.length===0||!s.projects.every(u=>typeof u=="string"&&u.length>0))throw new Error(`auto-vex-conf.json: 'projectOverrides[${o}].projects' must be a non-empty array of non-empty strings`);if(!$.includes(s.maxSeverity))throw new Error(`auto-vex-conf.json: invalid 'projectOverrides[${o}].maxSeverity' value '${String(s.maxSeverity)}'. Must be one of: ${$.join(", ")}`)}}return n}};var $e=require("fs/promises"),B=require("path");var ve=require("crypto");var oe="auto_vex_max_severity=";function se(t){return`${oe}${t}`}function O(t){let e=t.status_notes;if(!e||!e.startsWith(oe))return;let r=e.slice(oe.length).trim();return $.includes(r)?r:void 0}function he(t){let{cveName:e,purls:r,status:n,impactStatement:o,actionStatement:i,statusNotes:s,justification:u,timestamp:f=new Date().toISOString(),autoVexMaxSeverity:a}=t,g={vulnerability:{name:e},timestamp:f,products:r.map(y=>({"@id":y})),status:n};return o&&(g.impact_statement=o),i&&(g.action_statement=i),a?g.status_notes=se(a):s&&(g.status_notes=s),u&&(g.justification=u),g}var Re="https://openvex.dev/ns/v0.2.0";function ye(t,e="conterra"){let n=`https://openvex.dev/docs/public/vex-${(0,ve.randomUUID)()}`,o=t.timestamp??new Date().toISOString();return{"@context":Re,"@id":n,author:e,timestamp:o,last_updated:o,version:1,statements:[t]}}function Se(t,e){let r=e.timestamp??new Date().toISOString();return{...t,last_updated:r,version:t.version+1,statements:[...t.statements,e]}}var K=require("fs/promises"),G=require("path");var we=require("fs/promises"),ae=require("path");async function z(t,e){for(let r of await(0,we.readdir)(t,{withFileTypes:!0}))r.name.endsWith(".json")?await e(new _((0,ae.resolve)(r.parentPath,r.name))):r.isDirectory()&&await z((0,ae.resolve)(r.parentPath,r.name),e)}function xe(t){let e=t.vulnerability.name;return new Set([e,...t.vulnerability.aliases??[]])}var _=class{constructor(e){this.location=e}location;_content=void 0;_exists=!1;get exists(){return this._exists}get content(){return this._content}set content(e){this._content=e,this._exists=e!==void 0}async read(){let e=await W(this.location);this._content=e??void 0,this._exists=this._content!==void 0}async write(){if(this._content===void 0)throw new Error(`Cannot write VexFile: content is undefined (${this.location})`);await(0,K.mkdir)((0,G.dirname)((0,G.resolve)(this.location)),{recursive:!0}),await ge(this.location,this._content)}async delete(){await(0,K.unlink)(this.location),this._exists=!1}upsert(e,r){if(this._content===void 0)return this._content=ye(e,r),this._exists=!0,{created:!0,changed:!0};let n=O(e);if(n!==void 0){let o=this._content.statements.findIndex(i=>i.vulnerability.name===e.vulnerability.name&&i.status===e.status&&O(i)===n);if(o!==-1){let i=this._content.statements[o];return Me(i,e)?{created:!1,changed:!1}:(i.products=e.products,i.impact_statement=e.impact_statement,i.action_statement=e.action_statement,i.justification=e.justification,i.status_notes=e.status_notes,i.timestamp=e.timestamp,this._content.version+=1,this._content.last_updated=e.timestamp??new Date().toISOString(),{created:!1,changed:!0})}}return this._content=Se(this._content,e),{created:!1,changed:!0}}addProductId(e,r){this.assertContentLoaded("addProductId");let n=!1;for(let o of this._content.statements){if(!o.products||o.products.some(s=>s["@id"]===r))continue;let i=o.products.findIndex(s=>s["@id"]===e);i!==-1&&(o.products.splice(i+1,0,{"@id":r}),n=!0)}return n}removeProductId(e,r){this.assertContentLoaded("removeProductId");let n=this._content.statements,o=[],i=!1;for(let s of n){if(r&&!xe(s).has(r)||!s.products)continue;let u=s.products.findIndex(f=>f["@id"]===e);u!==-1&&(s.products.splice(u,1),i=!0,s.products.length===0&&o.push(s))}if(!i)return"unchanged";for(let s of o)n.splice(n.indexOf(s),1);return n.length===0?"emptied":"changed"}hasStatementForProduct(e){return this.assertContentLoaded("hasStatementForProduct"),this._content.statements.some(r=>r.products?.some(n=>n["@id"]===e)??!1)}assertContentLoaded(e){if(this._content===void 0)throw new Error(`VexFile.${e}(): content is not loaded. Call read() first (${this.location})`)}};function Me(t,e){return t.impact_statement!==e.impact_statement||t.action_statement!==e.action_statement||t.justification!==e.justification||t.status_notes!==e.status_notes?!1:Le(t.products,e.products)}function Le(t,e){let r=i=>Array.from(new Set((i??[]).map(s=>s["@id"]).filter(s=>typeof s=="string"))).sort(),n=r(t),o=r(e);return n.length!==o.length?!1:n.every((i,s)=>i===o[s])}function Ue(t){return t.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}function Be(t,e){let r=e.split("*").map(Ue).join(".*");return new RegExp(`^${r}$`).test(t)}function be(t,e){return e.some(r=>Be(t,r))}var Xe="HIGH";function Pe(t){if(t.kind==="default")return"default";let e=t.override,r=e.projects.join(", "),n=e.comment?`, comment: "${e.comment}"`:"";return`override [${r}]${n}`}var Ee=10,We=" ".repeat(Ee);function He(t){return`[${t}]`.padEnd(Ee," ")}function E(t,e,r=[]){let n=`${He(t)}${e}`,o=t==="warn"||t==="error"?console.error:console.log;o(n);for(let i of r)o(`${We}${i}`)}var d={info(t,e=[]){E("info",t,e)},create(t,e=[]){E("create",t,e)},update(t,e=[]){E("update",t,e)},revoke(t,e=[]){E("revoke",t,e)},skip(t,e=[]){E("skip",t,e)},dryRun(t,e=[]){E("dry-run",t,e)},backfill(t,e=[]){E("backfill",t,e)},warn(t,e=[]){E("warn",t,e)},error(t,e=[]){E("error",t,e)},banner(t){let e="\u2500".repeat(Math.max(0,62-t.length-4));console.log(""),console.log(`\u2500\u2500 ${t} ${e}`)}};function I(t){let e=(0,B.relative)(process.cwd(),t);return e===""?".":e.startsWith("..")?t:e.split(/[\\/]/).join("/")}async function je(t){let{scanSummaryPath:e,autoVexConfigPath:r,vexDir:n,dryRun:o=!1,writeMissingMarker:i=!1}=t,s=new T(process.cwd()),[u,f,a]=await Promise.all([Je(e),s.loadProjectConfig(),s.loadAutoVexConfig(r)]),g=new Map(f.projects.map(c=>[`${c.name}@${c.version}`,c.purl])),y=a.maxSeverity??Xe,D=a.subDir??"auto",j=(0,B.resolve)(n,D),F=a.projectOverrides??[],V=c=>{let v={severity:y,source:{kind:"default"}};for(let m of F)be(c,m.projects)&&U(m.maxSeverity,v.severity)<0&&(v={severity:m.maxSeverity,source:{kind:"override",override:m}});return v},x=c=>V(c).severity,l={created:[],updated:[],invalidated:[],markersWritten:[],errors:[],warnings:[],skipped:{atOrAboveThreshold:[],noEligibleProject:[],partial:[]},revokedProducts:0,filesRemoved:0},R=(c,v=[])=>{d.warn(c,v),l.warnings.push(c)};if(i)return d.banner("Marker backfill"),await Ye(j,y,o,l,R),l;d.banner("Invalidation pass"),await ze(j,u,g,y,x,o,l),d.info(`${l.revokedProducts} product(s) revoked across ${l.invalidated.length} CVE(s)`+(l.filesRemoved>0?`, ${l.filesRemoved} file(s) removed`:"")),d.banner("Statement creation");for(let[c,v]of Object.entries(u.vulnerabilities))try{let m=(0,B.resolve)(j,`${c}.json`),b=u.vulnerabilityToProject[c]??[];if(b.length===0){d.skip(`${c}: no affected projects found in summary`),l.skipped.noEligibleProject.push(c);continue}let A=new Map,N=[],h=[],M=!1;for(let p of b){let S=g.get(p);if(S===void 0){R(`${c}: project "${p}" not found in vuln-scan-conf.json, skipping product`),M=!0;continue}let P=V(p);if(!J(v.severity,P.severity)){h.push({projectId:p,effective:P});continue}N.push({projectId:p,purl:S,effective:P});let k=A.get(P.severity);k===void 0?A.set(P.severity,[S]):k.includes(S)||k.push(S)}if(A.size===0){h.length>0?(d.skip(`${c}: severity ${v.severity} meets or exceeds threshold for every eligible project`,h.map(p=>`${p.projectId} -> ${p.effective.severity} (${Pe(p.effective.source)})`)),l.skipped.atOrAboveThreshold.push(c)):M?(d.skip(`${c}: no resolvable project PURLs (see [warn] above)`),l.skipped.noEligibleProject.push(c)):(d.skip(`${c}: no eligible projects`),l.skipped.noEligibleProject.push(c));continue}h.length>0&&l.skipped.partial.push(c);let le=Array.from(A.entries()).sort(([p],[S])=>U(p,S)),q=le.map(([p,S])=>{let P=new Set(N.filter(L=>L.effective.severity===p).map(L=>L.effective.source.kind)),k=P.size===1?P.has("default")?" (default)":" (override)":" (mixed)";return`\u2022 max severity ${p}${k}: ${S.join(", ")}`}),Q=h.map(p=>`excluded: ${p.projectId} -> ${p.effective.severity} (${Pe(p.effective.source)})`);if(o){let p=h.length>0?` (partial: ${h.length} project(s) excluded)`:"";d.dryRun(`${c}${p} -> ${I(m)}`,[`severity=${v.severity}`,...q,...Q]),l.created.push(c);continue}let Z=new _(m);await Z.read();let X=!1,ee=!1,de=!1,Ve=new Date().toISOString();for(let[p,S]of le){let P=he({cveName:c,purls:S,status:"not_affected",impactStatement:a.impactStatement,timestamp:Ve,autoVexMaxSeverity:p}),{created:k,changed:L}=Z.upsert(P,a.author);L&&(de=!0,k?X=!0:ee=!0)}let fe=h.length>0?` (partial: ${h.length} project(s) excluded)`:"";if(!de){d.skip(`${c}${fe} -> ${I(m)}: unchanged`,[`severity=${v.severity}`,...q,...Q]);continue}await Z.write();let te=`${c}${fe} -> ${I(m)}`,re=[`severity=${v.severity}`,...q,...Q];X&&ee?(d.create(te,re),d.update(`${c}: also updated existing statement(s)`)):X?d.create(te,re):d.update(te,re),X?l.created.push(c):ee&&l.updated.push(c)}catch(m){let b=`Failed to process ${c}: ${String(m)}`;d.error(b),l.errors.push(b)}return l}async function Je(t){let e=await(0,$e.readFile)(t,"utf8");return JSON.parse(e)}async function ze(t,e,r,n,o,i,s){let u=Ge(e,r),f=Ke(r,o);try{await z(t,async a=>{if(await a.read(),!a.content)return;let y=a.content.statements.slice(),D=new Set,j=!1,F=!1;for(let V of y){if(F)break;let x=O(V)??n,l=V.vulnerability.name,R=u.get(l);if(!R)continue;let c=[];for(let v of V.products??[]){let m=v["@id"];if(!m)continue;let b=R.get(m);if(b===void 0)continue;let A=f.get(m),N=A!==void 0&&U(A,x)<0?A:x;if(!J(b,N)){c.push(m);let h=N===x?`severity ${b} meets or exceeds recorded threshold ${x}`:`severity ${b} meets or exceeds effective threshold ${N} (override stricter than recorded ${x})`,M=i?`would revoke ${l} on ${m}`:`revoked ${l} on ${m}`;i?d.dryRun(M,[h]):d.revoke(M,[h]),s.revokedProducts++}}if(c.length!==0){if(D.add(l),i){j=!0;continue}for(let v of c){let m=a.removeProductId(v,l);m==="emptied"?(F=!0,j=!0):m==="changed"&&(j=!0)}}}if(D.size>0){let V=new Set(s.invalidated);for(let x of D)V.has(x)||s.invalidated.push(x)}i||!j||(F?(await a.delete(),s.filesRemoved++,d.revoke(`removed empty auto VEX file ${I(a.location)}`)):await a.write())})}catch(a){if(a.code!=="ENOENT"){let g=`Auto-VEX invalidation pass failed: ${String(a)}`;d.error(g),s.errors.push(g)}}}function Ke(t,e){let r=new Map;for(let[n,o]of t){let i=e(n),s=r.get(o);(s===void 0||U(i,s)<0)&&r.set(o,i)}return r}function Ge(t,e){let r=new Map;for(let[n,o]of Object.entries(t.vulnerabilities)){let i=t.vulnerabilityToProject[n]??[],s=new Map;for(let u of i){let f=e.get(u);f&&s.set(f,o.severity)}s.size>0&&r.set(n,s)}return r}async function Ye(t,e,r,n,o){let i=se(e);try{await z(t,async s=>{if(await s.read(),!s.content)return;let u=!1,f=0,a=0;for(let y of s.content.statements)if(O(y)===void 0){if(y.status_notes){a++;continue}r||(y.status_notes=i),f++,u=!0}if(a>0&&o(`${I(s.location)}: skipped ${a} statement(s) that already have manual status notes`),!u)return;n.markersWritten.push(s.location);let g=r?`would stamp ${f} statement(s) in ${I(s.location)} with ${i}`:`${I(s.location)}: stamped ${f} statement(s) with ${i}`;r?d.dryRun(g):d.backfill(g),!r&&(s.content.version+=1,s.content.last_updated=new Date().toISOString(),await s.write())})}catch(s){if(s.code!=="ENOENT"){let u=`Auto-VEX marker backfill failed: ${String(s)}`;d.error(u),n.errors.push(u)}}}var ce={flag:"--dry-run",description:"Print what would happen without making changes"},Y=class{specs;booleanSpecs;commandName;helpLines;constructor(e,r,n=[],o=[]){this.commandName=e,this.specs=r;let i=o.some(s=>s.flag===ce.flag);this.booleanSpecs=i?o:[...o,ce],this.helpLines=n}parse(e){let r=e.slice(2),n=new Map(this.specs.map(i=>[i.flag,i.defaultValue])),o=new Map(this.booleanSpecs.map(i=>[i.flag,!1]));for(let i=0;i<r.length;i++){let s=r[i];(s==="--help"||s==="-h")&&(this.printHelp(),process.exit(0));let u=this.booleanSpecs.find(a=>a.flag===s||a.alias===s);if(u){o.set(u.flag,!0);continue}let f=this.specs.find(a=>a.flag===s||a.alias===s);f&&r[i+1]?n.set(f.flag,r[++i]):(console.error(`Unknown argument: ${s}`),this.printHelp(),process.exit(1))}return{values:n,dryRun:o.get(ce.flag)===!0,booleans:o}}printHelp(){let e=this.specs.map(n=>` ${(n.alias?`${n.alias}, ${n.flag} <path>`:` ${n.flag} <path>`).padEnd(38)}${n.description}
4
- ${"".padEnd(42)}(default: ${n.defaultValue})`),r=this.booleanSpecs.map(n=>` ${(n.alias?`${n.alias}, ${n.flag}`:` ${n.flag}`).padEnd(38)}${n.description}`);console.log([`Usage: ${this.commandName} [options]`,"","Options:",...e,...r," -h, --help"+" ".repeat(32)+"Show this help message",...this.helpLines].join(`
5
- `))}};var qe=new Y("ct-vuln-auto-vex",[{flag:"--auto-vex-config",alias:"-c",description:"Path to auto-vex-conf.json configuration file",defaultValue:(0,ue.join)(process.cwd(),"auto-vex-conf.json")},{flag:"--summary",alias:"-s",description:"Path to scan-summary.json produced by ct-vuln-scan",defaultValue:(0,ue.join)(process.cwd(),"output","scan-summary.json")}],["","Configuration (auto-vex-conf.json):"," impactStatement Required. Text written as impact_statement in each VEX statement."," maxSeverity Optional. Exclusive severity threshold. CVEs with a severity"," strictly below this level receive an auto-generated statement."," Values: UNKNOWN | LOW | MEDIUM | HIGH | CRITICAL (default: HIGH)"," author Optional. Author field in the OpenVEX document (default: conterra)"," subDir Optional. Sub-directory of vexDir for auto files (default: auto)"],[{flag:"--write-missing-marker",description:"Backfill auto_vex_max_severity into auto VEX statements that lack it, then exit"}]);(async()=>{let{values:t,dryRun:e,booleans:r}=qe.parse(process.argv),n=t.get("--auto-vex-config"),o=t.get("--summary"),i=r.get("--write-missing-marker")===!0,s=process.cwd(),u=i?" [write-missing-marker]":e?" [dry-run]":"";console.log(`Auto VEX Creator${u}`),console.log(` auto-vex-config: ${n}`),console.log(` summary: ${o}`);try{let f=await new T(s).loadProjectConfig();console.log(` vex-dir: ${f.vexDir}`);let a=await je({scanSummaryPath:o,autoVexConfigPath:n,vexDir:f.vexDir,dryRun:e,writeMissingMarker:i});if(console.log(""),console.log(`=== Auto VEX Creator Summary${u} ===`),i)console.log(` Files stamped : ${a.markersWritten.length}`);else{let g=a.skipped.atOrAboveThreshold.length+a.skipped.noEligibleProject.length;console.log(` Created : ${a.created.length}`),console.log(` Updated : ${a.updated.length}`),console.log(` Invalidated : ${a.invalidated.length} CVE (${a.revokedProducts} product(s), ${a.filesRemoved} file(s) removed)`),console.log(` Skipped (CVEs) : ${g}`),console.log(` at or above threshold : ${a.skipped.atOrAboveThreshold.length}`),console.log(` no eligible project : ${a.skipped.noEligibleProject.length}`),console.log(` partial (some projects excluded): ${a.skipped.partial.length}`)}console.log(` Warnings : ${a.warnings.length}`),console.log(` Errors : ${a.errors.length}`),e&&(console.log(""),console.log("No files were written (dry-run). Re-run without --dry-run to apply.")),a.errors.length>0&&(process.exitCode=1)}catch(f){console.error(`Fatal error: ${String(f)}`),process.exit(1)}})();
2
+ "use strict";var Ie=Object.create;var ge=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,_e=Object.prototype.hasOwnProperty;var De=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Te(e))!_e.call(t,o)&&o!==n&&ge(t,o,{get:()=>e[o],enumerable:!(r=Oe(e,o))||r.enumerable});return t};var ve=(t,e,n)=>(n=t!=null?Ie(Ne(t)):{},De(e||!t||!t.__esModule?ge(n,"default",{value:t,enumerable:!0}):n,t));var fe=require("path");var A=ve(require("path")),oe=require("fs/promises");var x=require("fs/promises");async function z(t){try{return await Fe(t)?JSON.parse(await(0,x.readFile)(t,{encoding:"utf-8"})):void 0}catch(e){throw new Error(`Error reading JSON file ${t}: ${e}`,{cause:e})}}async function he(t,e){let n=JSON.stringify(e,null,4)+`
3
+ `,r=await Re(t,n);await(0,x.writeFile)(t,r,{encoding:"utf-8"})}async function Fe(t){try{return await(0,x.access)(t,x.constants.F_OK),!0}catch{return!1}}async function Re(t,e){let n=await Me();if(!n)return e;let r=await n.resolveConfig(t);return r?await n.format(e,{...r,filepath:t}):e}var Le;function Me(){return Le??=import("prettier").catch(()=>{})}var K={UNKNOWN:0,LOW:1,MEDIUM:2,HIGH:3,CRITICAL:4},E=["UNKNOWN","LOW","MEDIUM","HIGH","CRITICAL"];function q(t,e){return K[t]-K[e]}function G(t,e){return K[t]<K[e]}var se=class t{constructor(e){this.workingDir=e}workingDir;static DEFAULT_MAVEN_REPO="https://repository.conterra.de/repository/maven-mirror-ct";static DEFAULT_VEX_SUBDIR="input/vex";static DEFAULT_OUT_SUBDIR="output";static DEFAULT_CACHE_SUBDIR="cache";static DEFAULT_SCANNERS=["grype","trivy","ossindex"];normalize(e,n){let r=e.findNoLongerDetectedVulnerabilitiesOnlyForSnapshots??!1;return{projectConfigFileLocation:n,onNewVulnerabilities:e.onNewVulnerabilities??(e.failOnNewVulnerabilities?"fail":"warn"),onNoLongerDetectedVulnerabilities:e.onNoLongerDetectedVulnerabilities??"ignore",reportNoLongerDetectedVulnerabilities:e.reportNoLongerDetectedVulnerabilities??!0,consoleReport:e.consoleReport??"BY_PROJECT_DETAILED",createSubDirsForProject:e.createSubDirsForProject??!0,mavenRepo:e.mavenRepo??t.DEFAULT_MAVEN_REPO,vexUrls:e.vexUrls??[],vexDir:this.resolvePath(e.vexDir)??(0,A.resolve)(this.workingDir,t.DEFAULT_VEX_SUBDIR),outDir:this.resolvePath(e.outDir)??(0,A.resolve)(this.workingDir,t.DEFAULT_OUT_SUBDIR),cacheDir:this.resolvePath(e.cacheDir)??(0,A.resolve)(this.workingDir,t.DEFAULT_CACHE_SUBDIR),scanners:this.normalizeScanners(e.scanners,n),projects:this.normalizeProjects(e.projects??[],r)}}normalizeScanners(e,n){return(e??t.DEFAULT_SCANNERS).map(o=>{if(typeof o!="string")throw new Error(`Invalid scanner name '${String(o)}' in configuration file '${n}'`);let s=o.split("@");if(s.length>2)throw new Error(`Invalid scanner name '${o}' in configuration file '${n}'`);return{name:s[0],version:s[1]??""}})}normalizeProjects(e,n){let r=e.map(o=>{let s=o;if(!s.name)throw new Error("Project name is missing on entry: "+JSON.stringify(s));if(!s.version)throw new Error("Project version is missing on entry: "+JSON.stringify(s));if(!s.purl)throw new Error("Project purl is missing on entry: "+JSON.stringify(s));let i={...s,purlAliases:s.purlAliases??[],enabled:s.enabled??!0,silent:s.silent??!1,minimumSeverity:s.minimumSeverity??"UNKNOWN"};return i.sbomFile?{...i,sbomFile:this.resolvePath(i.sbomFile)??i.sbomFile}:{...i,detectNoLongerUsedVulnerabilities:n?i.purl.endsWith("-SNAPSHOT"):!0}});return this.assertUniqueProjectIds(r),this.assertUniqueProjectPurls(r),r}assertUniqueProjectIds(e){let n=new Set;for(let r of e){let o=`${r.name}@${r.version}`;if(n.has(o))throw new Error(`Duplicate project id '${o}' in vuln-scan-conf.json: each 'name@version' pair must be unique across the projects array.`);n.add(o)}}assertUniqueProjectPurls(e){let n=new Map;for(let r of e){let o=`${r.name}@${r.version}`,s=n.get(r.purl);if(s!==void 0)throw new Error(`Duplicate project purl '${r.purl}' in vuln-scan-conf.json: used by '${s}' and '${o}'. Each project must have a unique purl; use 'purlAliases' when two projects should be matched by the same VEX statement.`);n.set(r.purl,o)}}resolvePath(e){if(e)return A.default.isAbsolute(e)?e:(0,A.resolve)(this.workingDir,e)}},_=class{constructor(e){this.workingDir=e;this.normalizer=new se(e)}workingDir;normalizer;projectConfigCache;async loadProjectConfig(){return this.projectConfigCache??=this.doLoadProjectConfig(),this.projectConfigCache}async doLoadProjectConfig(){let e=(0,A.resolve)(this.workingDir,"vuln-scan-conf.json"),n=await z(e);if(!n)throw new Error(`Missing project configuration file '${e}'`);return this.normalizer.normalize(n,e)}async loadJiraConfig(e){let n=await(0,oe.readFile)(e,"utf8"),r=JSON.parse(n);if(!r.issues&&r.issue&&(r.issues=r.issue),!r.jiraUrl||typeof r.jiraUrl!="string")throw new Error("jira-conf.json: missing or invalid 'jiraUrl' field");if(!Array.isArray(r.issues))throw new Error("jira-conf.json: missing or invalid 'issues' array");this.validateAutoCloseSeverity(r.autoCloseBelowSeverity,"jira-conf.json: invalid 'autoCloseBelowSeverity'");for(let[o,s]of r.issues.entries())if(s&&typeof s=="object"){let i=s;this.validateAutoCloseSeverity(i.autoCloseBelowSeverity,`jira-conf.json: invalid 'issues[${o}].autoCloseBelowSeverity'`),this.validateAutoCloseProjectOverrides(i.projectOverrides,`jira-conf.json: invalid 'issues[${o}].projectOverrides'`)}return r}validateAutoCloseSeverity(e,n){if(e!==void 0&&!E.includes(e))throw new Error(`${n} value '${String(e)}'. Must be one of: ${E.join(", ")}`)}validateAutoCloseProjectOverrides(e,n){if(e!==void 0){if(!Array.isArray(e))throw new Error(`${n}: must be an array`);for(let r=0;r<e.length;r++){let o=e[r],s=`${n}[${r}]`;if(o==null||typeof o!="object")throw new Error(`${s}: must be an object`);let i=o,a=i.projects;if(!Array.isArray(a)||a.length===0)throw new Error(`${s}.projects: must be a non-empty array of strings`);for(let u=0;u<a.length;u++){let l=a[u];if(typeof l!="string"||l.length===0)throw new Error(`${s}.projects[${u}]: must be a non-empty string`)}if(i.autoCloseBelowSeverity===void 0)throw new Error(`${s}.autoCloseBelowSeverity: is required`);if(this.validateAutoCloseSeverity(i.autoCloseBelowSeverity,`${s}.autoCloseBelowSeverity`),i.comment!==void 0&&typeof i.comment!="string")throw new Error(`${s}.comment: must be a string`)}}}async loadAutoVexConfig(e){let n=await(0,oe.readFile)(e,"utf8"),r=JSON.parse(n);if(!r.impactStatement||typeof r.impactStatement!="string")throw new Error("auto-vex-conf.json: missing or invalid 'impactStatement' field (must be a non-empty string)");if(r.maxSeverity!==void 0&&!E.includes(r.maxSeverity))throw new Error(`auto-vex-conf.json: invalid 'maxSeverity' value '${String(r.maxSeverity)}'. Must be one of: ${E.join(", ")}`);if(r.projectOverrides!==void 0){if(!Array.isArray(r.projectOverrides))throw new Error("auto-vex-conf.json: 'projectOverrides' must be an array");for(let[o,s]of r.projectOverrides.entries()){if(!s||typeof s!="object")throw new Error(`auto-vex-conf.json: 'projectOverrides[${o}]' must be an object`);let i=s;if(!Array.isArray(i.projects)||i.projects.length===0||!i.projects.every(a=>typeof a=="string"&&a.length>0))throw new Error(`auto-vex-conf.json: 'projectOverrides[${o}].projects' must be a non-empty array of non-empty strings`);if(!E.includes(i.maxSeverity))throw new Error(`auto-vex-conf.json: invalid 'projectOverrides[${o}].maxSeverity' value '${String(i.maxSeverity)}'. Must be one of: ${E.join(", ")}`)}}return r}};var $e=require("fs/promises"),W=require("path");var ye=require("crypto");var ae="auto_vex_max_severity=";function ce(t){return`${ae}${t}`}function Y(t){let e=t.status_notes;if(!e||!e.startsWith(ae))return;let n=e.slice(ae.length).trim();return E.includes(n)?n:void 0}function Se(t){let{cveName:e,purls:n,status:r,impactStatement:o,actionStatement:s,statusNotes:i,justification:a,timestamp:u=new Date().toISOString(),autoVexMaxSeverity:l}=t,d={vulnerability:{name:e},timestamp:u,products:n.map(S=>({"@id":S})),status:r};return o&&(d.impact_statement=o),s&&(d.action_statement=s),l?d.status_notes=ce(l):i&&(d.status_notes=i),a&&(d.justification=a),d}var Ue="https://openvex.dev/ns/v0.2.0";function we(t,e="conterra"){let r=`https://openvex.dev/docs/public/vex-${(0,ye.randomUUID)()}`,o=t.timestamp??new Date().toISOString();return{"@context":Ue,"@id":r,author:e,timestamp:o,last_updated:o,version:1,statements:[t]}}var Z=require("fs/promises"),ee=require("path");var xe=require("fs/promises"),ue=require("path");async function Q(t,e){for(let n of await(0,xe.readdir)(t,{withFileTypes:!0}))n.name.endsWith(".json")?await e(new D((0,ue.resolve)(n.parentPath,n.name))):n.isDirectory()&&await Q((0,ue.resolve)(n.parentPath,n.name),e)}function be(t){let e=t.vulnerability.name;return new Set([e,...t.vulnerability.aliases??[]])}var D=class{constructor(e){this.location=e}location;_content=void 0;_exists=!1;get exists(){return this._exists}get content(){return this._content}set content(e){this._content=e,this._exists=e!==void 0}async read(){let e=await z(this.location);this._content=e??void 0,this._exists=this._content!==void 0}async write(){if(this._content===void 0)throw new Error(`Cannot write VexFile: content is undefined (${this.location})`);await(0,Z.mkdir)((0,ee.dirname)((0,ee.resolve)(this.location)),{recursive:!0}),await he(this.location,this._content)}async delete(){await(0,Z.unlink)(this.location),this._exists=!1}upsert(e,n){if(this._content===void 0)return this._content=we(e,n),this._exists=!0,{created:!0,changed:!0};let r=je(e.products),o=this._content.statements,s=[];for(let i=0;i<o.length;i++){let a=o[i];a.vulnerability.name===e.vulnerability.name&&a.status===e.status&&Xe(je(a.products),r)&&s.push(i)}if(s.length>0){let i=s[0],a=o[i],u=s.slice(1),l=!Be(a,e);if(u.length===0&&!l)return{created:!1,changed:!1};l&&(a.impact_statement=e.impact_statement,a.action_statement=e.action_statement,a.justification=e.justification,a.status_notes=e.status_notes,a.timestamp=e.timestamp);for(let d=u.length-1;d>=0;d--)o.splice(u[d],1);return this._content.version+=1,this._content.last_updated=e.timestamp??new Date().toISOString(),{created:!1,changed:!0}}for(let i=o.length-1;i>=0;i--){let a=o[i];if(a.vulnerability.name!==e.vulnerability.name||a.status!==e.status||!a.products||a.products.length===0)continue;let u=a.products.filter(l=>{let d=l["@id"];return typeof d!="string"||!r.has(d)});u.length!==a.products.length&&(u.length===0?o.splice(i,1):a.products=u)}return o.push(e),this._content.version+=1,this._content.last_updated=e.timestamp??new Date().toISOString(),{created:!1,changed:!0}}addProductId(e,n){this.assertContentLoaded("addProductId");let r=!1;for(let o of this._content.statements){if(!o.products||o.products.some(i=>i["@id"]===n))continue;let s=o.products.findIndex(i=>i["@id"]===e);s!==-1&&(o.products.splice(s+1,0,{"@id":n}),r=!0)}return r}removeProductId(e,n){this.assertContentLoaded("removeProductId");let r=this._content.statements,o=[],s=!1;for(let i of r){if(n&&!be(i).has(n)||!i.products)continue;let a=i.products.findIndex(u=>u["@id"]===e);a!==-1&&(i.products.splice(a,1),s=!0,i.products.length===0&&o.push(i))}if(!s)return"unchanged";for(let i of o)r.splice(r.indexOf(i),1);return r.length===0?"emptied":"changed"}hasStatementForProduct(e){return this.assertContentLoaded("hasStatementForProduct"),this._content.statements.some(n=>n.products?.some(r=>r["@id"]===e)??!1)}assertContentLoaded(e){if(this._content===void 0)throw new Error(`VexFile.${e}(): content is not loaded. Call read() first (${this.location})`)}};function Be(t,e){return t.impact_statement===e.impact_statement&&t.action_statement===e.action_statement&&t.justification===e.justification&&t.status_notes===e.status_notes}function je(t){let e=new Set;if(!t)return e;for(let n of t){let r=n["@id"];typeof r=="string"&&e.add(r)}return e}function Xe(t,e){if(t.size!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}function He(t){return t.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}function We(t,e){let n=e.split("*").map(He).join(".*");return new RegExp(`^${n}$`).test(t)}function Ee(t,e){return e.some(n=>We(t,n))}function Pe(t){return t.created.length===0&&t.updated.length===0&&t.invalidated.length===0&&t.revokedProducts===0&&t.filesRemoved===0&&t.skipped.atOrAboveThreshold.length===0&&t.skipped.noEligibleProject.length===0&&t.skipped.partial.length===0&&t.markersWritten.length===0&&t.warnings.length===0&&t.errors.length===0}var Je="HIGH";function le(t){if(t.kind==="default")return"default";let e=t.override,n=e.projects.join(", "),r=e.comment?`, comment: "${e.comment}"`:"";return`override [${n}]${r}`}var Ve=12;function F(t){return t.padEnd(Ve," ")}function ze(t){let{projectId:e,current:n,limit:r,limitSource:o}=t,s=e??"<unknown>",i=[`${F("project")}: ${s}`,`${F("current")}: ${n}`,`${F("limit")}: ${r} (auto-VEX requires current strictly below limit)`];switch(o.kind){case"marker":i.push(`${F("limit source")}: status_notes marker \`auto_vex_max_severity=${o.severity}\``);break;case"default":i.push(`${F("limit source")}: config default (statement has no auto_vex_max_severity marker)`);break;case"override":{let a=o.effective.source,u=a.kind==="override"?le(a):"default";i.push(`${F("limit source")}: projectOverrides entry ${u.replace(/^override /,"")}`);let l=o.markerPresent?`(stricter than statement marker ${o.recorded})`:`(stricter than config default ${o.recorded}; statement has no marker)`;i.push(`${" ".repeat(Ve+2)}${l}`);break}}return i}var ke=10,Ke=" ".repeat(ke);function qe(t){return`[${t}]`.padEnd(ke," ")}function $(t,e,n=[]){let r=`${qe(t)}${e}`,o=t==="warn"||t==="error"?console.error:console.log;o(r);for(let s of n)o(`${Ke}${s}`)}var p={info(t,e=[]){$("info",t,e)},create(t,e=[]){$("create",t,e)},update(t,e=[]){$("update",t,e)},revoke(t,e=[]){$("revoke",t,e)},skip(t,e=[]){$("skip",t,e)},dryRun(t,e=[]){$("dry-run",t,e)},backfill(t,e=[]){$("backfill",t,e)},warn(t,e=[]){$("warn",t,e)},error(t,e=[]){$("error",t,e)},banner(t){let e="\u2500".repeat(Math.max(0,62-t.length-4));console.log(""),console.log(`\u2500\u2500 ${t} ${e}`)}};function I(t){let e=(0,W.relative)(process.cwd(),t);return e===""?".":e.startsWith("..")?t:e.split(/[\\/]/).join("/")}async function Ae(t){let{scanSummaryPath:e,autoVexConfigPath:n,vexDir:r,dryRun:o=!1,writeMissingMarker:s=!1}=t,i=new _(process.cwd()),[a,u,l]=await Promise.all([Ge(e),i.loadProjectConfig(),i.loadAutoVexConfig(n)]),d=new Map(u.projects.map(c=>[`${c.name}@${c.version}`,c.purl])),S=new Map;for(let c of u.projects)S.set(c.purl,`${c.name}@${c.version}`);let R=l.maxSeverity??Je,L=l.subDir??"auto",P=(0,W.resolve)(r,L),M=l.projectOverrides??[],V=c=>{let h={severity:R,source:{kind:"default"}};for(let g of M)Ee(c,g.projects)&&q(g.maxSeverity,h.severity)<0&&(h={severity:g.maxSeverity,source:{kind:"override",override:g}});return h},m={created:[],updated:[],invalidated:[],markersWritten:[],errors:[],warnings:[],skipped:{atOrAboveThreshold:[],noEligibleProject:[],partial:[]},revokedProducts:0,filesRemoved:0},k=(c,h=[])=>{p.warn(c,h),m.warnings.push(c)};if(s)return p.banner("Marker backfill"),await et(P,R,o,m,k),m;p.banner("Invalidation pass"),await Ye(P,a,d,S,R,V,o,m),p.banner("Statement creation");for(let[c,h]of Object.entries(a.vulnerabilities))try{let g=(0,W.resolve)(P,`${c}.json`),j=a.vulnerabilityToProject[c]??[];if(j.length===0){p.skip(`${c}: no affected projects found in summary`),m.skipped.noEligibleProject.push(c);continue}let v=new Map,O=[],y=[],U=!1;for(let f of j){let w=d.get(f);if(w===void 0){k(`${c}: project "${f}" not found in vuln-scan-conf.json, skipping product`),U=!0;continue}let b=V(f);if(!G(h.severity,b.severity)){y.push({projectId:f,effective:b});continue}O.push({projectId:f,purl:w,effective:b});let C=v.get(b.severity);C===void 0?v.set(b.severity,[w]):C.includes(w)||C.push(w)}if(v.size===0){y.length>0?(p.skip(`${c}: current ${h.severity} is not strictly below limit for every eligible project`,y.map(f=>`${f.projectId} \u2014 limit ${f.effective.severity} (${le(f.effective.source)})`)),m.skipped.atOrAboveThreshold.push(c)):U?(p.skip(`${c}: no resolvable project PURLs (see [warn] above)`),m.skipped.noEligibleProject.push(c)):(p.skip(`${c}: no eligible projects`),m.skipped.noEligibleProject.push(c));continue}y.length>0&&m.skipped.partial.push(c);let B=Array.from(v.entries()).sort(([f],[w])=>q(f,w)),X=B.map(([f,w])=>{let b=new Set(O.filter(H=>H.effective.severity===f).map(H=>H.effective.source.kind)),C=b.size===1?b.has("default")?" (default)":" (override)":" (mixed)";return`\u2022 limit ${f}${C}: ${w.join(", ")}`}),T=y.map(f=>`excluded: ${f.projectId} \u2014 limit ${f.effective.severity} (${le(f.effective.source)})`);if(o){let f=y.length>0?` (partial: ${y.length} project(s) excluded)`:"";p.dryRun(`${c}${f} -> ${I(g)}`,[`severity=${h.severity}`,...X,...T]),m.created.push(c);continue}let N=new D(g);await N.read();let J=!1,re=!1,pe=!1,Ce=new Date().toISOString();for(let[f,w]of B){let b=Se({cveName:c,purls:w,status:"not_affected",impactStatement:l.impactStatement,timestamp:Ce,autoVexMaxSeverity:f}),{created:C,changed:H}=N.upsert(b,l.author);H&&(pe=!0,C?J=!0:re=!0)}let me=y.length>0?` (partial: ${y.length} project(s) excluded)`:"";if(!pe){p.skip(`${c}${me} -> ${I(g)}: unchanged`,[`severity=${h.severity}`,...X,...T]);continue}await N.write();let ne=`${c}${me} -> ${I(g)}`,ie=[`severity=${h.severity}`,...X,...T];J&&re?(p.create(ne,ie),p.update(`${c}: also updated existing statement(s)`)):J?p.create(ne,ie):p.update(ne,ie),J?m.created.push(c):re&&m.updated.push(c)}catch(g){let j=`Failed to process ${c}: ${String(g)}`;p.error(j),m.errors.push(j)}return m}async function Ge(t){let e=await(0,$e.readFile)(t,"utf8");return JSON.parse(e)}async function Ye(t,e,n,r,o,s,i,a){let u=Ze(e,n),l=Qe(n,s);try{await Q(t,async d=>{if(await d.read(),!d.content)return;let R=d.content.statements.slice(),L=new Set,P=!1,M=!1;for(let V of R){if(M)break;let m=Y(V),k=m??o,c=V.vulnerability.name,h=u.get(c);if(!h)continue;let g=[];for(let j of V.products??[]){let v=j["@id"];if(!v)continue;let O=h.get(v);if(O===void 0)continue;let y=l.get(v),U=y!==void 0&&q(y.severity,k)<0,B=U?y.severity:k;if(!G(O,B)){g.push(v);let X=U?{kind:"override",effective:y,recorded:k,markerPresent:m!==void 0}:m!==void 0?{kind:"marker",severity:k}:{kind:"default",severity:k},T=ze({projectId:r.get(v),current:O,limit:B,limitSource:X}),N=i?`would revoke ${c} on ${v}`:`revoked ${c} on ${v}`;i?p.dryRun(N,T):p.revoke(N,T),a.revokedProducts++}}if(g.length!==0){if(L.add(c),i){P=!0;continue}for(let j of g){let v=d.removeProductId(j,c);v==="emptied"?(M=!0,P=!0):v==="changed"&&(P=!0)}}}if(L.size>0){let V=new Set(a.invalidated);for(let m of L)V.has(m)||a.invalidated.push(m)}i||!P||(M?(await d.delete(),a.filesRemoved++,p.revoke(`removed empty auto VEX file ${I(d.location)}`)):await d.write())})}catch(d){if(d.code!=="ENOENT"){let S=`Auto-VEX invalidation pass failed: ${String(d)}`;p.error(S),a.errors.push(S)}}}function Qe(t,e){let n=new Map;for(let[r,o]of t)n.set(o,e(r));return n}function Ze(t,e){let n=new Map;for(let[r,o]of Object.entries(t.vulnerabilities)){let s=t.vulnerabilityToProject[r]??[],i=new Map;for(let a of s){let u=e.get(a);u&&i.set(u,o.severity)}i.size>0&&n.set(r,i)}return n}async function et(t,e,n,r,o){let s=ce(e);try{await Q(t,async i=>{if(await i.read(),!i.content)return;let a=!1,u=0,l=0;for(let S of i.content.statements)if(Y(S)===void 0){if(S.status_notes){l++;continue}n||(S.status_notes=s),u++,a=!0}if(l>0&&o(`${I(i.location)}: skipped ${l} statement(s) that already have manual status notes`),!a)return;r.markersWritten.push(i.location);let d=n?`would stamp ${u} statement(s) in ${I(i.location)} with ${s}`:`${I(i.location)}: stamped ${u} statement(s) with ${s}`;n?p.dryRun(d):p.backfill(d),!n&&(i.content.version+=1,i.content.last_updated=new Date().toISOString(),await i.write())})}catch(i){if(i.code!=="ENOENT"){let a=`Auto-VEX marker backfill failed: ${String(i)}`;p.error(a),r.errors.push(a)}}}var de={flag:"--dry-run",description:"Print what would happen without making changes"},te=class{specs;booleanSpecs;commandName;helpLines;constructor(e,n,r=[],o=[]){this.commandName=e,this.specs=n;let s=o.some(i=>i.flag===de.flag);this.booleanSpecs=s?o:[...o,de],this.helpLines=r}parse(e){let n=e.slice(2),r=new Map(this.specs.map(s=>[s.flag,s.defaultValue])),o=new Map(this.booleanSpecs.map(s=>[s.flag,!1]));for(let s=0;s<n.length;s++){let i=n[s];(i==="--help"||i==="-h")&&(this.printHelp(),process.exit(0));let a=this.booleanSpecs.find(l=>l.flag===i||l.alias===i);if(a){o.set(a.flag,!0);continue}let u=this.specs.find(l=>l.flag===i||l.alias===i);u&&n[s+1]?r.set(u.flag,n[++s]):(console.error(`Unknown argument: ${i}`),this.printHelp(),process.exit(1))}return{values:r,dryRun:o.get(de.flag)===!0,booleans:o}}printHelp(){let e=this.specs.map(r=>` ${(r.alias?`${r.alias}, ${r.flag} <path>`:` ${r.flag} <path>`).padEnd(38)}${r.description}
4
+ ${"".padEnd(42)}(default: ${r.defaultValue})`),n=this.booleanSpecs.map(r=>` ${(r.alias?`${r.alias}, ${r.flag}`:` ${r.flag}`).padEnd(38)}${r.description}`);console.log([`Usage: ${this.commandName} [options]`,"","Options:",...e,...n," -h, --help"+" ".repeat(32)+"Show this help message",...this.helpLines].join(`
5
+ `))}};var tt=new te("ct-vuln-auto-vex",[{flag:"--auto-vex-config",alias:"-c",description:"Path to auto-vex-conf.json configuration file",defaultValue:(0,fe.join)(process.cwd(),"auto-vex-conf.json")},{flag:"--summary",alias:"-s",description:"Path to scan-summary.json produced by ct-vuln-scan",defaultValue:(0,fe.join)(process.cwd(),"output","scan-summary.json")}],["","Configuration (auto-vex-conf.json):"," impactStatement Required. Text written as impact_statement in each VEX statement."," maxSeverity Optional. Exclusive severity threshold. CVEs with a severity"," strictly below this level receive an auto-generated statement."," Values: UNKNOWN | LOW | MEDIUM | HIGH | CRITICAL (default: HIGH)"," author Optional. Author field in the OpenVEX document (default: conterra)"," subDir Optional. Sub-directory of vexDir for auto files (default: auto)"],[{flag:"--write-missing-marker",description:"Backfill auto_vex_max_severity into auto VEX statements that lack it, then exit"}]);(async()=>{let{values:t,dryRun:e,booleans:n}=tt.parse(process.argv),r=t.get("--auto-vex-config"),o=t.get("--summary"),s=n.get("--write-missing-marker")===!0,i=process.cwd();console.log(`Auto VEX Creator${s?" [write-missing-marker]":e?" [dry-run]":""}`);try{let u=await new _(i).loadProjectConfig(),l=await Ae({scanSummaryPath:o,autoVexConfigPath:r,vexDir:u.vexDir,dryRun:e,writeMissingMarker:s});Pe(l)&&console.log("[info] nothing to do"),e&&(console.log(""),console.log("No files were written (dry-run). Re-run without --dry-run to apply.")),l.errors.length>0&&(process.exitCode=1)}catch(u){console.error(`Fatal error: ${String(u)}`),process.exit(1)}})();