cdk-insights 1.28.0 → 1.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/entry.js +5 -5
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/entry.js
CHANGED
|
@@ -170,7 +170,7 @@ ${yt.primary.bold(`${Jt.rocket} ${s}`)}`),console.log(`${yt.comment("\u2500".rep
|
|
|
170
170
|
${yt.primary.bold(`${Jt.chart} Analysis Complete!`)}`),console.log(yt.comment("\u2500".repeat(50))),console.log(yt.success(`\u2705 Completed: ${n}`)),i>0&&console.log(yt.error(`\u274C Failed: ${i}`)),o>0&&console.log(yt.warning(`\u23F0 Timed out: ${o}`)),console.log(yt.comment(`\u23F1\uFE0F Total time: ${v}s`))}}}createSpinner(e){let s=rm({text:e,color:"blue",spinner:"dots"}).start();return{stop:n=>{n?s.succeed(n):s.stop()},fail:n=>{s.fail(n||"Failed")},warn:n=>{s.warn(n||"Warning")},info:n=>{s.info(n||"Info")}}}showSummary(e){console.log(`
|
|
171
171
|
${yt.primary.bold(`${Jt.chart} Analysis Summary`)}`),console.log(yt.comment("\u2500".repeat(40))),console.log(yt.text(`Completed ${e.length} step${e.length===1?"":"s"} successfully!`))}header(e){console.log(`
|
|
172
172
|
${yt.primary.bold(`${Jt.rocket} ${e}`)}`),console.log(`${yt.comment("\u2500".repeat(60))}
|
|
173
|
-
`)}section(e,s=Jt.info){console.log(yt.primary.bold(`${s} ${e}`))}success(e,s=Jt.success){console.log(yt.success(`${s} ${e}`))}info(e,s=Jt.info){console.log(yt.info(`${s} ${e}`))}warning(e,s=Jt.warning){console.log(yt.warning(`${s} ${e}`))}error(e,s=Jt.error){console.log(yt.error(`${s} ${e}`))}comment(e,s=""){console.log(yt.comment(`${s} ${e}`))}phase1(e){console.log(yt.info(`${Jt.phase1} Phase 1: ${e}`))}phase2(e){console.log(yt.primary(`${Jt.phase2} Phase 2: ${e}`))}phase3(e){console.log(yt.secondary(`${Jt.phase3} Phase 3: ${e}`))}severityBadge(e){switch(e.toUpperCase()){case"CRITICAL":return yt.severity.critical.bold(`${Jt.critical} CRITICAL`);case"HIGH":return yt.severity.high.bold(`${Jt.high} HIGH`);case"MEDIUM":return yt.severity.medium.bold(`${Jt.medium} MEDIUM`);case"LOW":return yt.severity.low.bold(`${Jt.low} LOW`);default:return yt.comment(e)}}divider(){console.log(yt.comment("\u2500".repeat(60)))}newline(){console.log("")}clearLine(){process.stdout.write(`\r${" ".repeat(process.stdout.columns)}\r`)}},im=iS.getInstance()});var T8,P8=D(()=>{"use strict";T8=t=>t&&(t.Name||t.ResourceName||t.FunctionName)||"Unnamed"});var aS,L8,cS,O8=D(()=>{"use strict";lt();aS=null,L8=t=>{aS=t},cS=()=>{if(aS&&!process.env.CI)try{aS.saveToDisk(),re.info("\u{1F4BE} Cache saved to disk on exit")}catch(t){re.warn("\u26A0\uFE0F Could not save cache on exit",{error:t instanceof Error?t.message:String(t)})}};process.on("exit",cS);process.on("SIGINT",()=>{cS(),process.exit(0)});process.on("SIGTERM",()=>{cS(),process.exit(0)})});var QJ,XJ,om,eQ,tQ,sQ,nQ,M8,B8=D(()=>{"use strict";$b();Y3();Lb();tl();Hf();t8();Gb();oS();lt();$r();P8();O8();QJ={maxConcurrent:Xu.DEFAULT_MAX_CONCURRENT,retryAttempts:Xu.DEFAULT_RETRY_ATTEMPTS,retryDelay:Xu.DEFAULT_RETRY_DELAY_MS,timeoutMs:Xu.DEFAULT_TIMEOUT_MS},XJ=t=>{if(!(t instanceof Error))return!1;let e=t.message??"";return e.startsWith("Polling timed out")||e==="Analysis timeout"||e.toLowerCase().includes("timeout")},om=(t,e)=>{let s=t.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return t;let[,n,r=""]=s;return`${Dc(e,n)}${r}`},eQ=t=>{let e=Yu({ttl:6e4,maxSize:1e3});return({analysisError:s,redactedId:n})=>{let r=s instanceof Error?s.message:"unknown",i=`${n}:${r}`,o=e.get(i)||0;return XJ(s)?{status:"timeout",redactedId:n}:(e.set(i,o+1),o>t.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},tQ=({analyzeResource:t,redactionMapping:e,aggregatedResult:s,errorHandler:n,config:r,authToken:i,fingerprint:o,stackName:a,analysisCache:c,originalResources:u,relationships:l,aiModelId:d})=>async({redactedId:p,redactedResources:f,findingsByResource:m,progressTracker:g})=>{let h=m.get(p)||[],v=f[p];if(!v)return{status:"skipped",redactedId:p};let S=Wb(p,v,i,o,[]),w=jb(S),E=e[p];if(!E)return{status:"skipped",redactedId:p};let P=E,k=()=>(s[P]||(s[P]={issues:[]}),s[P]),A=c.get(w);if(A){let _=(A.issues||[]).map(y=>({...y,resource:P,resourceId:P})),Y=k();return Y.issues.push(...Zo({existing:Y.issues,incoming:_})),Y.resourceName=A.resourceName,{status:"success",redactedId:p,resourceKey:P,remappedIssues:_,resourceName:A.resourceName}}let M=Dc(a,E),z=Dc("cdk-insights-stack",a),C=Uf(E,l,u),U={dependencies:C.dependencies.map(_=>om(_,a)),dependents:C.dependents.map(_=>om(_,a)),usageDescription:C.usageDescription};for(let _=1;_<=r.retryAttempts;_++)try{let Y=await Promise.race([t(z,M,v,v.Type,i,o,h,g,U,d),new Promise((K,q)=>setTimeout(()=>q(new Error("Analysis timeout")),r.timeoutMs))]);Y.resourceId=P;let y=(Y.issues||[]).map(K=>({...K,resource:P,resourceId:P})),b=k();return b.issues.push(...Zo({existing:b.issues,incoming:y})),b.resourceName=Y.resourceName,c.set(w,Y,S),{status:"success",redactedId:p,resourceKey:P,remappedIssues:y,resourceName:Y.resourceName}}catch(Y){if(_===r.retryAttempts)return n({analysisError:Y,redactedId:p});await new Promise(y=>setTimeout(y,r.retryDelay*2**(_-1)))}return{status:"fail",redactedId:p,error:new Error("Max retries exceeded")}},sQ=async(t,e,s)=>{let n=Math.max(1,Math.floor(e)),r=0,i=Array.from({length:Math.min(n,t.length)}).map(async()=>{for(;r<t.length;){let o=r;r+=1;let a=t[o];await s(a)}});await Promise.allSettled(i)},nQ=10,M8=({analyzeResource:t,analyzeResourcesBatch:e,redactResources:s,config:n=QJ})=>async({stackName:r,resources:i,authToken:o,existingFindingsMap:a,pathToLogicalId:c,fingerprint:u,noCache:l=!1,cacheConfig:d,aiModelId:p,aiBatchSize:f})=>{let m={},g=[],h={startTime:Date.now(),processedCount:0,successCount:0,failureCount:0,timeoutCount:0},{redactedResources:v,mapping:x}=s(i),S=n8(a,x,c),w=new Map;for(let te of S){let X=w.get(te.resourceId);X?X.push(te):w.set(te.resourceId,[te])}let E=Object.keys(v),P=E.length,k=Vo(i),A=new Jf({ttl:d?.ttl||6*60*60*1e3,maxSize:d?.maxSize||5e3,disabled:l||!d?.enabled});L8(A);let M=eQ(n),z=tQ({analyzeResource:t,redactionMapping:x,aggregatedResult:m,errorHandler:M,config:n,authToken:o,fingerprint:u,stackName:r,analysisCache:A,originalResources:i,relationships:k,aiModelId:p}),C=im.createSingleLineProgressTracker(P,"Analyzing resources with AI"),U=Math.min(Math.max(1,Math.floor(f??1)),nQ);if(U>1&&!!e&&e){re.debug("Batched analysis enabled",{batchSize:U,totalResources:P});let te=Dc("cdk-insights-stack",r),X=ee=>{let fe=Uf(ee,k,i);return{dependencies:fe.dependencies.map(Re=>om(Re,r)),dependents:fe.dependents.map(Re=>om(Re,r)),usageDescription:fe.usageDescription}};for(let ee=0;ee<E.length;ee+=U){let fe=E.slice(ee,ee+U),Re=async()=>{for(let G of fe){let xe=await z({redactedId:G,redactedResources:v,findingsByResource:w,progressTracker:C});switch(h.processedCount++,xe.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:G,resourceData:v[G],resourceType:v[G].Type,existingFindings:w.get(G)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},se=new Map,Ce=[];for(let G of fe){let xe=v[G],ge=x[G];if(!xe||!ge){h.processedCount++,h.failureCount++;continue}let L=Wb(G,xe,o,u,[]),ae=jb(L),W=A.get(ae);if(W){let De=(W.issues||[]).map(I=>({...I,resource:ge,resourceId:ge}));m[ge]||(m[ge]={issues:[]});let Be=m[ge];Be.issues.push(...Zo({existing:Be.issues,incoming:De})),Be.resourceName=W.resourceName,h.processedCount++,h.successCount++;continue}let ue=Dc(r,ge);se.set(ue,{redactedId:G,originalResourceId:ge,cacheKey:ae,cacheComponents:L}),Ce.push({stableResourceId:ue,resourceData:xe,resourceType:xe.Type,context:X(ge),existingFindings:w.get(G)||[]})}if(Ce.length!==0)try{let G=await Promise.race([e(te,Ce,o,u,p),new Promise((xe,ge)=>setTimeout(()=>ge(new Error("Analysis timeout")),n.timeoutMs))]);for(let[xe,ge]of se){let L=G.get(xe);if(h.processedCount++,!L){re.warn(`Batched response missing entry for resource ${ge.originalResourceId}`,{stableResourceId:xe,redactedId:ge.redactedId}),h.failureCount++;continue}let ae=(L.issues||[]).map(ue=>({...ue,resource:ge.originalResourceId,resourceId:ge.originalResourceId}));m[ge.originalResourceId]||(m[ge.originalResourceId]={issues:[]});let W=m[ge.originalResourceId];W.issues.push(...Zo({existing:W.issues,incoming:ae})),W.resourceName=L.resourceName,A.set(ge.cacheKey,{resourceId:ge.originalResourceId,issues:L.issues||[],resourceName:L.resourceName},ge.cacheComponents),h.successCount++}}catch(G){re.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:G instanceof Error?G.message:String(G),chunkSize:fe.length}),await Re()}}}else await sQ(E,n.maxConcurrent,async te=>{re.debug(`Starting analysis for resource ${te}`,{redactedId:te,maxConcurrent:n.maxConcurrent});let X=await z({redactedId:te,redactedResources:v,findingsByResource:w,progressTracker:C});switch(h.processedCount++,re.debug(`Resource ${te} analysis result: ${X.status}`,{redactedId:te,status:X.status,hasProgressTracker:!!C}),X.status){case"success":h.successCount++,re.debug(`Resource ${te} completed successfully`,{redactedId:te,resourceKey:X.resourceKey});break;case"timeout":h.timeoutCount++,re.warn(`Resource ${te} timed out`,{redactedId:te}),g.push({redactedId:te,resourceData:v[te],resourceType:v[te].Type,existingFindings:w.get(te)||[]});break;case"fail":case"skipped":h.failureCount++,re.warn(`Resource ${te} failed or was skipped`,{redactedId:te,status:X.status});break}});let Y=Date.now()-h.startTime,y=C.getStats();if(re.debug("Analysis completed with progress tracker stats",{progressTrackerStats:y,performanceMetrics:h,totalTime:Y,totalResources:P,maxConcurrent:n.maxConcurrent}),T.analysisComplete(Y,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){T.newline(),T.info("\u{1F4CA} Performance Analysis:");let te=h.successCount>0?Math.round(Y/1e3/h.successCount):0;T.comment(` \u23F1\uFE0F Average completion time: ${te}s`),T.comment(` \u{1F4CA} Success rate: ${(h.successCount/P*100).toFixed(1)}%`)}if(g.length>0){T.newline(),T.warning("\u23F0 Timed Out Resources:"),T.comment(` \u{1F4CB} Total timed out: ${g.length}`);for(let te of g){if(T.comment(` \u274C ${te.resourceType}: ${te.redactedId}`),te.resourceData?.Properties){let ee=te.resourceData.Properties,fe=T8(ee);T.comment(` \u{1F4DD} Name: ${fe}`)}te.existingFindings.length>0&&T.comment(` \u{1F50D} Existing findings: ${te.existingFindings.length}`),te.resourceData?.Metadata&&T.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(te.resourceType)&&T.comment(" \u26A0\uFE0F Complex resource type - may require extended analysis time")}T.newline(),T.info("\u{1F4A1} Tip: Some resources are taking longer to analyze than expected."),T.comment(" This is normal for complex resources. The analysis will continue with the remaining resources."),T.warning(`Retrying ${g.length} resource${g.length===1?"":"s"} that need a little more time...`)}let b=new Set(Object.keys(m)),K=new Set(Object.values(x)),q=Array.from(K).filter(te=>!b.has(te)||!m[te]?.issues?.length);if(q.length>0){let te=A.getCachedResultsForResources(q),X=0;for(let[ee,fe]of Array.from(te.entries())){if(m[ee]?.issues?.length>0)continue;let Re=(fe.issues||[]).map(se=>({...se,resource:ee,resourceId:ee}));Re.length>0&&(m[ee]||(m[ee]={issues:[]}),m[ee].issues.push(...Re),m[ee].resourceName=fe.resourceName,X+=Re.length)}X>0}return m}});var W8,rQ,N8,iQ,oQ,$8,am,cm,j8,U8,aQ,cQ,uQ,Ac,um=D(()=>{"use strict";W8="1.28.0",rQ={Security:"https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/",Reliability:"https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/","Performance Efficiency":"https://docs.aws.amazon.com/wellarchitected/latest/performance-efficiency-pillar/","Cost Optimization":"https://docs.aws.amazon.com/wellarchitected/latest/cost-optimization-pillar/","Operational Excellence":"https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/",Sustainability:"https://docs.aws.amazon.com/wellarchitected/latest/sustainability-pillar/"},N8=t=>t.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),iQ=(t,e)=>{let s=0;if(s+=2e3,e){let n=Object.values(t).filter(r=>{let i=r.sources.cdkInsights?.issues??[],o=r.sources.cdkNag?.issues??[];return i.length>0||o.length>0});s+=n.length*100}for(let[,n]of Object.entries(t)){let r=n.sources.cdkInsights?.issues??[],i=n.sources.cdkNag?.issues??[];for(let o of[...r,...i])s+=o.issue.length,s+=o.recommendation?.length||0,s+=o.codeSnippet?.length||0,s+=500}return s},oQ=t=>t?t.split(`
|
|
173
|
+
`)}section(e,s=Jt.info){console.log(yt.primary.bold(`${s} ${e}`))}success(e,s=Jt.success){console.log(yt.success(`${s} ${e}`))}info(e,s=Jt.info){console.log(yt.info(`${s} ${e}`))}warning(e,s=Jt.warning){console.log(yt.warning(`${s} ${e}`))}error(e,s=Jt.error){console.log(yt.error(`${s} ${e}`))}comment(e,s=""){console.log(yt.comment(`${s} ${e}`))}phase1(e){console.log(yt.info(`${Jt.phase1} Phase 1: ${e}`))}phase2(e){console.log(yt.primary(`${Jt.phase2} Phase 2: ${e}`))}phase3(e){console.log(yt.secondary(`${Jt.phase3} Phase 3: ${e}`))}severityBadge(e){switch(e.toUpperCase()){case"CRITICAL":return yt.severity.critical.bold(`${Jt.critical} CRITICAL`);case"HIGH":return yt.severity.high.bold(`${Jt.high} HIGH`);case"MEDIUM":return yt.severity.medium.bold(`${Jt.medium} MEDIUM`);case"LOW":return yt.severity.low.bold(`${Jt.low} LOW`);default:return yt.comment(e)}}divider(){console.log(yt.comment("\u2500".repeat(60)))}newline(){console.log("")}clearLine(){process.stdout.write(`\r${" ".repeat(process.stdout.columns)}\r`)}},im=iS.getInstance()});var T8,P8=D(()=>{"use strict";T8=t=>t&&(t.Name||t.ResourceName||t.FunctionName)||"Unnamed"});var aS,L8,cS,O8=D(()=>{"use strict";lt();aS=null,L8=t=>{aS=t},cS=()=>{if(aS&&!process.env.CI)try{aS.saveToDisk(),re.info("\u{1F4BE} Cache saved to disk on exit")}catch(t){re.warn("\u26A0\uFE0F Could not save cache on exit",{error:t instanceof Error?t.message:String(t)})}};process.on("exit",cS);process.on("SIGINT",()=>{cS(),process.exit(0)});process.on("SIGTERM",()=>{cS(),process.exit(0)})});var QJ,XJ,om,eQ,tQ,sQ,nQ,M8,B8=D(()=>{"use strict";$b();Y3();Lb();tl();Hf();t8();Gb();oS();lt();$r();P8();O8();QJ={maxConcurrent:Xu.DEFAULT_MAX_CONCURRENT,retryAttempts:Xu.DEFAULT_RETRY_ATTEMPTS,retryDelay:Xu.DEFAULT_RETRY_DELAY_MS,timeoutMs:Xu.DEFAULT_TIMEOUT_MS},XJ=t=>{if(!(t instanceof Error))return!1;let e=t.message??"";return e.startsWith("Polling timed out")||e==="Analysis timeout"||e.toLowerCase().includes("timeout")},om=(t,e)=>{let s=t.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return t;let[,n,r=""]=s;return`${Dc(e,n)}${r}`},eQ=t=>{let e=Yu({ttl:6e4,maxSize:1e3});return({analysisError:s,redactedId:n})=>{let r=s instanceof Error?s.message:"unknown",i=`${n}:${r}`,o=e.get(i)||0;return XJ(s)?{status:"timeout",redactedId:n}:(e.set(i,o+1),o>t.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},tQ=({analyzeResource:t,redactionMapping:e,aggregatedResult:s,errorHandler:n,config:r,authToken:i,fingerprint:o,stackName:a,analysisCache:c,originalResources:u,relationships:l,aiModelId:d})=>async({redactedId:p,redactedResources:f,findingsByResource:m,progressTracker:g})=>{let h=m.get(p)||[],v=f[p];if(!v)return{status:"skipped",redactedId:p};let S=Wb(p,v,i,o,[]),w=jb(S),E=e[p];if(!E)return{status:"skipped",redactedId:p};let P=E,k=()=>(s[P]||(s[P]={issues:[]}),s[P]),A=c.get(w);if(A){let _=(A.issues||[]).map(y=>({...y,resource:P,resourceId:P})),Y=k();return Y.issues.push(...Zo({existing:Y.issues,incoming:_})),Y.resourceName=A.resourceName,{status:"success",redactedId:p,resourceKey:P,remappedIssues:_,resourceName:A.resourceName}}let M=Dc(a,E),z=Dc("cdk-insights-stack",a),C=Uf(E,l,u),U={dependencies:C.dependencies.map(_=>om(_,a)),dependents:C.dependents.map(_=>om(_,a)),usageDescription:C.usageDescription};for(let _=1;_<=r.retryAttempts;_++)try{let Y=await Promise.race([t(z,M,v,v.Type,i,o,h,g,U,d),new Promise((K,q)=>setTimeout(()=>q(new Error("Analysis timeout")),r.timeoutMs))]);Y.resourceId=P;let y=(Y.issues||[]).map(K=>({...K,resource:P,resourceId:P})),b=k();return b.issues.push(...Zo({existing:b.issues,incoming:y})),b.resourceName=Y.resourceName,c.set(w,Y,S),{status:"success",redactedId:p,resourceKey:P,remappedIssues:y,resourceName:Y.resourceName}}catch(Y){if(_===r.retryAttempts)return n({analysisError:Y,redactedId:p});await new Promise(y=>setTimeout(y,r.retryDelay*2**(_-1)))}return{status:"fail",redactedId:p,error:new Error("Max retries exceeded")}},sQ=async(t,e,s)=>{let n=Math.max(1,Math.floor(e)),r=0,i=Array.from({length:Math.min(n,t.length)}).map(async()=>{for(;r<t.length;){let o=r;r+=1;let a=t[o];await s(a)}});await Promise.allSettled(i)},nQ=10,M8=({analyzeResource:t,analyzeResourcesBatch:e,redactResources:s,config:n=QJ})=>async({stackName:r,resources:i,authToken:o,existingFindingsMap:a,pathToLogicalId:c,fingerprint:u,noCache:l=!1,cacheConfig:d,aiModelId:p,aiBatchSize:f})=>{let m={},g=[],h={startTime:Date.now(),processedCount:0,successCount:0,failureCount:0,timeoutCount:0},{redactedResources:v,mapping:x}=s(i),S=n8(a,x,c),w=new Map;for(let te of S){let X=w.get(te.resourceId);X?X.push(te):w.set(te.resourceId,[te])}let E=Object.keys(v),P=E.length,k=Vo(i),A=new Jf({ttl:d?.ttl||6*60*60*1e3,maxSize:d?.maxSize||5e3,disabled:l||!d?.enabled});L8(A);let M=eQ(n),z=tQ({analyzeResource:t,redactionMapping:x,aggregatedResult:m,errorHandler:M,config:n,authToken:o,fingerprint:u,stackName:r,analysisCache:A,originalResources:i,relationships:k,aiModelId:p}),C=im.createSingleLineProgressTracker(P,"Analyzing resources with AI"),U=Math.min(Math.max(1,Math.floor(f??1)),nQ);if(U>1&&!!e&&e){re.debug("Batched analysis enabled",{batchSize:U,totalResources:P});let te=Dc("cdk-insights-stack",r),X=ee=>{let fe=Uf(ee,k,i);return{dependencies:fe.dependencies.map(Re=>om(Re,r)),dependents:fe.dependents.map(Re=>om(Re,r)),usageDescription:fe.usageDescription}};for(let ee=0;ee<E.length;ee+=U){let fe=E.slice(ee,ee+U),Re=async()=>{for(let G of fe){let xe=await z({redactedId:G,redactedResources:v,findingsByResource:w,progressTracker:C});switch(h.processedCount++,xe.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:G,resourceData:v[G],resourceType:v[G].Type,existingFindings:w.get(G)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},se=new Map,Ce=[];for(let G of fe){let xe=v[G],ge=x[G];if(!xe||!ge){h.processedCount++,h.failureCount++;continue}let L=Wb(G,xe,o,u,[]),ae=jb(L),W=A.get(ae);if(W){let De=(W.issues||[]).map(I=>({...I,resource:ge,resourceId:ge}));m[ge]||(m[ge]={issues:[]});let Be=m[ge];Be.issues.push(...Zo({existing:Be.issues,incoming:De})),Be.resourceName=W.resourceName,h.processedCount++,h.successCount++;continue}let ue=Dc(r,ge);se.set(ue,{redactedId:G,originalResourceId:ge,cacheKey:ae,cacheComponents:L}),Ce.push({stableResourceId:ue,resourceData:xe,resourceType:xe.Type,context:X(ge),existingFindings:w.get(G)||[]})}if(Ce.length!==0)try{let G=await Promise.race([e(te,Ce,o,u,p),new Promise((xe,ge)=>setTimeout(()=>ge(new Error("Analysis timeout")),n.timeoutMs))]);for(let[xe,ge]of se){let L=G.get(xe);if(h.processedCount++,!L){re.warn(`Batched response missing entry for resource ${ge.originalResourceId}`,{stableResourceId:xe,redactedId:ge.redactedId}),h.failureCount++;continue}let ae=(L.issues||[]).map(ue=>({...ue,resource:ge.originalResourceId,resourceId:ge.originalResourceId}));m[ge.originalResourceId]||(m[ge.originalResourceId]={issues:[]});let W=m[ge.originalResourceId];W.issues.push(...Zo({existing:W.issues,incoming:ae})),W.resourceName=L.resourceName,A.set(ge.cacheKey,{resourceId:ge.originalResourceId,issues:L.issues||[],resourceName:L.resourceName},ge.cacheComponents),h.successCount++}}catch(G){re.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:G instanceof Error?G.message:String(G),chunkSize:fe.length}),await Re()}}}else await sQ(E,n.maxConcurrent,async te=>{re.debug(`Starting analysis for resource ${te}`,{redactedId:te,maxConcurrent:n.maxConcurrent});let X=await z({redactedId:te,redactedResources:v,findingsByResource:w,progressTracker:C});switch(h.processedCount++,re.debug(`Resource ${te} analysis result: ${X.status}`,{redactedId:te,status:X.status,hasProgressTracker:!!C}),X.status){case"success":h.successCount++,re.debug(`Resource ${te} completed successfully`,{redactedId:te,resourceKey:X.resourceKey});break;case"timeout":h.timeoutCount++,re.warn(`Resource ${te} timed out`,{redactedId:te}),g.push({redactedId:te,resourceData:v[te],resourceType:v[te].Type,existingFindings:w.get(te)||[]});break;case"fail":case"skipped":h.failureCount++,re.warn(`Resource ${te} failed or was skipped`,{redactedId:te,status:X.status});break}});let Y=Date.now()-h.startTime,y=C.getStats();if(re.debug("Analysis completed with progress tracker stats",{progressTrackerStats:y,performanceMetrics:h,totalTime:Y,totalResources:P,maxConcurrent:n.maxConcurrent}),T.analysisComplete(Y,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){T.newline(),T.info("\u{1F4CA} Performance Analysis:");let te=h.successCount>0?Math.round(Y/1e3/h.successCount):0;T.comment(` \u23F1\uFE0F Average completion time: ${te}s`),T.comment(` \u{1F4CA} Success rate: ${(h.successCount/P*100).toFixed(1)}%`)}if(g.length>0){T.newline(),T.warning("\u23F0 Timed Out Resources:"),T.comment(` \u{1F4CB} Total timed out: ${g.length}`);for(let te of g){if(T.comment(` \u274C ${te.resourceType}: ${te.redactedId}`),te.resourceData?.Properties){let ee=te.resourceData.Properties,fe=T8(ee);T.comment(` \u{1F4DD} Name: ${fe}`)}te.existingFindings.length>0&&T.comment(` \u{1F50D} Existing findings: ${te.existingFindings.length}`),te.resourceData?.Metadata&&T.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(te.resourceType)&&T.comment(" \u26A0\uFE0F Complex resource type - may require extended analysis time")}T.newline(),T.info("\u{1F4A1} Tip: Some resources are taking longer to analyze than expected."),T.comment(" This is normal for complex resources. The analysis will continue with the remaining resources."),T.warning(`Retrying ${g.length} resource${g.length===1?"":"s"} that need a little more time...`)}let b=new Set(Object.keys(m)),K=new Set(Object.values(x)),q=Array.from(K).filter(te=>!b.has(te)||!m[te]?.issues?.length);if(q.length>0){let te=A.getCachedResultsForResources(q),X=0;for(let[ee,fe]of Array.from(te.entries())){if(m[ee]?.issues?.length>0)continue;let Re=(fe.issues||[]).map(se=>({...se,resource:ee,resourceId:ee}));Re.length>0&&(m[ee]||(m[ee]={issues:[]}),m[ee].issues.push(...Re),m[ee].resourceName=fe.resourceName,X+=Re.length)}X>0}return m}});var W8,rQ,N8,iQ,oQ,$8,am,cm,j8,U8,aQ,cQ,uQ,Ac,um=D(()=>{"use strict";W8="1.29.0",rQ={Security:"https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/",Reliability:"https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/","Performance Efficiency":"https://docs.aws.amazon.com/wellarchitected/latest/performance-efficiency-pillar/","Cost Optimization":"https://docs.aws.amazon.com/wellarchitected/latest/cost-optimization-pillar/","Operational Excellence":"https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/",Sustainability:"https://docs.aws.amazon.com/wellarchitected/latest/sustainability-pillar/"},N8=t=>t.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),iQ=(t,e)=>{let s=0;if(s+=2e3,e){let n=Object.values(t).filter(r=>{let i=r.sources.cdkInsights?.issues??[],o=r.sources.cdkNag?.issues??[];return i.length>0||o.length>0});s+=n.length*100}for(let[,n]of Object.entries(t)){let r=n.sources.cdkInsights?.issues??[],i=n.sources.cdkNag?.issues??[];for(let o of[...r,...i])s+=o.issue.length,s+=o.recommendation?.length||0,s+=o.codeSnippet?.length||0,s+=500}return s},oQ=t=>t?t.split(`
|
|
174
174
|
`).map(e=>e.trim()).filter(Boolean).join(`
|
|
175
175
|
`):"",$8=t=>{let e=`- **Issue:** ${t.issue}`;return t.recommendation&&(e+=`
|
|
176
176
|
- **Recommendation:** ${oQ(t.recommendation)}`),t.context&&(t.context.property&&(e+=`
|
|
@@ -289,7 +289,7 @@ ${o}`)}});var Z8,Y8,J8=D(()=>{"use strict";Z8=require("node:child_process"),Y8=(
|
|
|
289
289
|
`)}catch(a){console.error("Failed to write GitHub outputs:",a)}}});var pm,p4,f4=D(()=>{"use strict";lt();pm=t=>{switch(t.toUpperCase()){case"CRITICAL":return"\u{1F534}";case"HIGH":return"\u{1F7E0}";case"MEDIUM":return"\u{1F7E1}";case"LOW":return"\u{1F7E2}";default:return"\u26AA"}},p4=(t,e)=>{Oe.info(`
|
|
290
290
|
\u{1F4DD} Analysis Summary for stack: ${t}`),Oe.info(`Total Resources Scanned: ${e.totalResources}`),Oe.info(`Resources with Issues: ${e.resourcesWithIssues} (${e.percentWithIssues}%)`),Oe.info(`Total Issues Found: ${e.totalIssues}
|
|
291
291
|
`),Oe.info("Severity Breakdown:"),Oe.info(` ${pm("CRITICAL")} Critical: ${e.severityCounts.CRITICAL}`),Oe.info(` ${pm("HIGH")} High: ${e.severityCounts.HIGH}`),Oe.info(` ${pm("MEDIUM")} Medium: ${e.severityCounts.MEDIUM}`),Oe.info(` ${pm("LOW")} Low: ${e.severityCounts.LOW}
|
|
292
|
-
`),Oe.info("WAF Pillar Impact:");for(let[s,n]of Object.entries(e.wafIssues))Oe.info(` ${s}: ${n}`);Oe.info(""),Oe.info("Top Priorities:"),e.severityCounts.CRITICAL>0&&Oe.info(" \u{1F534} Address Critical issues immediately (highest risk)"),e.severityCounts.HIGH>0&&Oe.info(" \u{1F7E0} Then handle High-severity issues"),e.severityCounts.MEDIUM>0&&Oe.info(" \u{1F7E1} Schedule Medium-severity tasks soon"),e.severityCounts.LOW>0&&Oe.info(" \u{1F7E2} Plan Low-severity enhancements at your convenience"),Oe.info("")}});var wQ,AQ,EQ,m4,ul,gS=D(()=>{"use strict";wQ=Hg(),AQ=t=>{switch(t){case"CRITICAL":return"\u{1F534}";case"HIGH":return"\u{1F536}";case"MEDIUM":return"\u{1F7E1}";case"LOW":return"\u{1F7E2}";default:return"\u26AA"}},EQ=(t,e)=>{let s=t.sourceLocation||e?.sourceLocation;if(s){let{filePath:n,line:r,column:i,confidence:o}=s,a=o==="high"?"\u{1F3AF}":o==="medium"?"\u{1F4CD}":"\u2753",c=n.length>40?`...${n.slice(-37)}`:n;return`${a} ${c}:${r}:${i}`}if(e?.rootSourceLocation){let{filePath:n,line:r,column:i}=e.rootSourceLocation;return`\u{1F517} ${n.length>40?`...${n.slice(-37)}`:n}:${r}:${i}`}return e?.createdBy?`\u{1F517} ${e.createdBy.length>28?`${e.createdBy.slice(0,25)}...`:e.createdBy}`:""},m4={CRITICAL:4,HIGH:3,MEDIUM:2,LOW:1},ul=t=>{let e=new wQ({head:["Resource","Stack","Severity","Service","Issue","Location"],colWidths:[20,15,10,15,40,30],wordWrap:!0}),s=[];for(let[,n]of Object.entries(t)){let r=[...n.sources?.cdkInsights?.issues??[],...n.sources?.cdkNag?.issues??[]];for(let i of r){let o=i.constructType||n.constructType||n.type||"Unknown",a=EQ(i,n);s.push({issue:i,group:n,service:o,sourceLocation:a})}}s.sort((n,r)=>{let i=m4[n.issue.severity]||0;return(m4[r.issue.severity]||0)-i});for(let{issue:n,group:r,service:i,sourceLocation:o}of s)e.push([r.friendlyName||r.resourceId,n.stackName||"Unknown",`${AQ(n.severity)} ${n.severity}`,i,n.issue,o||n.locationHint||""]);console.log(e.toString())}});var ll=O((mRe,RQ)=>{RQ.exports={name:"cdk-insights",version:"1.28.0",description:"AWS CDK security and cost analysis CLI. Free static scans via npm \u2014 no account needed. Sign up free to add AI-powered insights.",main:"dist/index.js",types:"dist/index.d.ts",bin:{"cdk-insights":"dist/entry.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.js"}},files:["dist/**/*","README.md","LICENSE"],scripts:{test:"vitest --run",lint:"biome lint src/",typecheck:"tsc --noEmit",format:"biome format --write src/",check:"biome check src/","check:schema-sync":"ts-node scripts/check-schema-sync.ts",build:"ts-node scripts/build.ts","build:dev":"CDK_INSIGHTS_ENVIRONMENT=dev CDK_INSIGHTS_API_URL=https://s2zhmjbwlj.execute-api.eu-west-2.amazonaws.com/v1 ts-node scripts/build.ts",start:"node dist/index.js",dev:"ts-node src/index.ts",prepare:"husky install && npm run build","start:dev":"CDK_ENV=local ts-node src/index.ts","ai-run":"ts-node src/index.ts",unlink:"npm unlink -g cdk-insights",link:"npm link","prepare:test":"npm run unlink && npm run build && npm run link","prepare:dev":"npm run unlink && npm run build:dev && npm run link","deploy:dev":"STAGE=dev cdk deploy","destroy:dev":"STAGE=dev cdk destroy","release:patch":"bumper release patch","release:minor":"bumper release minor","release:major":"bumper release major","release:dry-run":"bumper release patch --dry-run","changelog:preview":"bumper preview","changelog:generate":"bumper generate","validate:commits":"bumper validate","release:check":"npm run validate:commits && npm run test && npm run build","release:full":"npm run release:check && npm run changelog:generate","setup:bumper":"bumper setup","publish:beta":"npm run build && npm publish --tag beta && npm dist-tag add cdk-insights@$npm_package_version latest","publish:alpha":"npm run build && npm publish --tag alpha","publish:canary":"npm run build && npm publish --tag canary","publish:latest":"npm run build && npm publish --tag latest","version:beta":"npm version prerelease --preid=beta","version:alpha":"npm version prerelease --preid=alpha","version:rc":"npm version prerelease --preid=rc","cdk-insights":"node scripts/cdk-insights-wrapper.js",scan:"node scripts/cdk-insights-wrapper.js scan","scan:all":"node scripts/cdk-insights-wrapper.js scan --all","scan:json":"node scripts/cdk-insights-wrapper.js scan --format json","scan:markdown":"node scripts/cdk-insights-wrapper.js scan --format markdown","scan:summary":"node scripts/cdk-insights-wrapper.js scan --format summary","scan:with-issues":"node scripts/cdk-insights-wrapper.js scan --withIssue","cache:clear":"node scripts/cdk-insights-wrapper.js cache clear","cache:status":"node scripts/cdk-insights-wrapper.js cache status","demo:progress":"ts-node src/examples/progress-demo.ts","demo:single-line":"ts-node src/examples/single-line-progress-demo.ts","test:line-clearing":"ts-node src/examples/line-clearing-test.ts"},publishConfig:{access:"public"},keywords:["aws","cdk","cloudformation","analysis","security","cost-optimization","static-analysis","devops","infrastructure","aws-cdk","cloud-security","compliance"],author:"Lee Priest <lee@cdkinsights.dev>",license:"BUSL-1.1",homepage:"https://github.com/instancelabs/cdk-insights",bugs:"https://github.com/instancelabs/cdk-insights/issues",repository:{type:"git",url:"git+https://github.com/instancelabs/cdk-insights.git"},dependencies:{"@inquirer/prompts":"^7.4.1","@middy/core":"^6.1.6","@types/glob":"^8.1.0",axios:"^1.8.4",chalk:"^5.4.1",chokidar:"^3.6.0","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.5.0",envolution:"^1.4.1",glob:"^11.0.3",ora:"^8.2.0",strogger:"^2.0.3",yargs:"^17.7.2",zod:"^3.23.8"},devDependencies:{"@aws-sdk/client-dynamodb":"^3.788.0","@biomejs/biome":"^2.0.6","@commitlint/cli":"^19.8.1","@commitlint/config-conventional":"^19.8.1","@types/cli-progress":"^3.11.6","@types/jsonwebtoken":"^9.0.9","@types/node":"^22.14.1","@types/yargs":"^17.0.33","aws-cdk":"^2.1010.0","bumper-cli":"^1.6.0",esbuild:"^0.25.2",husky:"^8.0.3","ts-node":"^10.9.2",typescript:"^5.8.3",vitest:"^3.1.1"},peerDependencies:{"aws-cdk-lib":"^2.190.0","cdk-nag":"^2.35.73",constructs:"^10.4.2"},optionalDependencies:{"@aws-solutions-constructs/aws-apigateway-lambda":"^2.0.0","@aws-solutions-constructs/aws-lambda-stepfunctions":"^2.0.0","@aws-solutions-constructs/aws-s3-lambda":"^2.0.0"}}});var g4,IQ,h4,_Q,y4,x4=D(()=>{"use strict";g4=oe(require("node:fs"));lt();tl();({version:IQ}=ll()),h4={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3},_Q=(t,e,s)=>{let n=Object.entries(s).map(([r,i])=>{let o=[...i.sources?.cdkInsights?.issues??[],...i.sources?.cdkNag?.issues??[]].slice().sort((c,u)=>h4[c.severity]-h4[u.severity]),a=em(o,i.cdkPath);return{resourceId:i.resourceId,logicalId:i.logicalId,cdkName:i.friendlyName,resourceName:i.resourceName,cdkPath:i.cdkPath,githubUrl:i.githubUrl,docUrl:i.docUrl,constructType:i.constructType,parentPath:i.parentPath,childCount:i.childCount,tags:i.tags,sourceLocation:i.sourceLocation,constructHierarchy:i.constructHierarchy,serviceCategory:i.serviceCategory,dependencies:i.dependencies,sensitiveProperties:i.sensitiveProperties,usesDefaults:i.usesDefaults,l2ConstructType:i.l2ConstructType,l2ConstructId:i.l2ConstructId,createdBy:i.createdBy,rootSourceLocation:i.rootSourceLocation,searchHint:i.searchHint,issues:a.map(c=>({issue:c.issue,recommendation:c.recommendation,severity:c.severity,wafPillar:c.wafPillar,codeSnippet:c.codeSnippet,locationHint:c.locationHint,foundBy:c.foundBy,sourceLocation:c.sourceLocation,stackName:c.stackName}))}});return{stackName:t,generatedAt:new Date().toISOString(),version:IQ,summary:e,recommendations:n}},y4=(t,e,s)=>{let n=_Q(t,e,s),r=`${t}_analysis_report.json`;try{g4.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),Oe.info(`\u{1F4C4} JSON report written to ${r}`)}catch(i){let o=i instanceof Error?i.message:String(i);throw Oe.error(`\u274C Failed to write JSON report to ${r}: ${o}`),new Error(`Failed to write analysis report: ${o}`)}return n}});var kQ,FQ,b4,fm,TQ,yS=D(()=>{"use strict";({version:kQ}=ll()),FQ=t=>{switch(t){case"CRITICAL":case"HIGH":return"error";case"MEDIUM":return"warning";default:return"note"}},b4=t=>{switch(t){case"CRITICAL":return 9;case"HIGH":return 7;case"MEDIUM":return 4;case"LOW":return 2;default:return 1}},fm=(t,e)=>{let s=[],n=[],r=new Set;for(let[i,o]of Object.entries(e)){let a=[...o.sources?.cdkInsights?.issues||[],...o.sources?.cdkNag?.issues||[]];for(let c of a){let u=TQ(c);r.has(u)||(r.add(u),s.push({id:u,name:c.issue.slice(0,100),shortDescription:{text:c.issue},fullDescription:c.recommendation?{text:c.recommendation}:void 0,helpUri:c.docUrl||c.githubUrl,properties:{"security-severity":b4(c.severity).toString(),tags:[c.wafPillar,c.severity,c.foundBy].filter(Boolean)}}));let d=(c.sourceLocation?.frames?.slice(1)??[]).map(p=>({physicalLocation:{artifactLocation:{uri:p.filePath,uriBaseId:"%SRCROOT%"},region:{startLine:p.line,startColumn:p.column}},message:{text:p.kind==="property"&&p.propertyName?`Property set: ${p.propertyName}`:p.kind==="creation"?"Construct created here":"Related call site"}}));n.push({ruleId:u,level:FQ(c.severity),message:{text:c.recommendation||c.issue},locations:[{physicalLocation:{artifactLocation:{uri:c.sourceLocation?.filePath||`cdk.out/${t}.template.json`,uriBaseId:"%SRCROOT%"},region:c.sourceLocation?{startLine:c.sourceLocation.line,startColumn:c.sourceLocation.column}:void 0}}],...d.length>0?{relatedLocations:d}:{},properties:{"security-severity":b4(c.severity).toString(),wafPillar:c.wafPillar,recommendation:c.recommendation}})}}return{$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"cdk-insights",version:kQ,informationUri:"https://cdkinsights.dev",rules:s}},results:n}]}},TQ=t=>{let e=t.issue.toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,50);return`CDK-${t.severity}-${e}`}});var xS,S4,v4=D(()=>{"use strict";xS=oe(require("node:fs"));lt();um();f4();gS();x4();yS();hS();S4=(t,e,s,n,r)=>{switch(Oe.info(`Generating output in format: ${t}`),t){case"markdown":{let i=Ac(e,s,r,n),o=`${e}_analysis_report.md`;try{xS.writeFileSync(o,i),Oe.info(`\u{1F4C4} Saved Markdown report to ${o}`)}catch(a){let c=a instanceof Error?a.message:String(a);throw Oe.error(`\u274C Failed to write Markdown report to ${o}: ${c}`),new Error(`Failed to write Markdown report: ${c}`)}break}case"table":{ul(s);break}case"json":{let i=y4(e,r,s);process.stdout.write(`${JSON.stringify(i,null,2)}
|
|
292
|
+
`),Oe.info("WAF Pillar Impact:");for(let[s,n]of Object.entries(e.wafIssues))Oe.info(` ${s}: ${n}`);Oe.info(""),Oe.info("Top Priorities:"),e.severityCounts.CRITICAL>0&&Oe.info(" \u{1F534} Address Critical issues immediately (highest risk)"),e.severityCounts.HIGH>0&&Oe.info(" \u{1F7E0} Then handle High-severity issues"),e.severityCounts.MEDIUM>0&&Oe.info(" \u{1F7E1} Schedule Medium-severity tasks soon"),e.severityCounts.LOW>0&&Oe.info(" \u{1F7E2} Plan Low-severity enhancements at your convenience"),Oe.info("")}});var wQ,AQ,EQ,m4,ul,gS=D(()=>{"use strict";wQ=Hg(),AQ=t=>{switch(t){case"CRITICAL":return"\u{1F534}";case"HIGH":return"\u{1F536}";case"MEDIUM":return"\u{1F7E1}";case"LOW":return"\u{1F7E2}";default:return"\u26AA"}},EQ=(t,e)=>{let s=t.sourceLocation||e?.sourceLocation;if(s){let{filePath:n,line:r,column:i,confidence:o}=s,a=o==="high"?"\u{1F3AF}":o==="medium"?"\u{1F4CD}":"\u2753",c=n.length>40?`...${n.slice(-37)}`:n;return`${a} ${c}:${r}:${i}`}if(e?.rootSourceLocation){let{filePath:n,line:r,column:i}=e.rootSourceLocation;return`\u{1F517} ${n.length>40?`...${n.slice(-37)}`:n}:${r}:${i}`}return e?.createdBy?`\u{1F517} ${e.createdBy.length>28?`${e.createdBy.slice(0,25)}...`:e.createdBy}`:""},m4={CRITICAL:4,HIGH:3,MEDIUM:2,LOW:1},ul=t=>{let e=new wQ({head:["Resource","Stack","Severity","Service","Issue","Location"],colWidths:[20,15,10,15,40,30],wordWrap:!0}),s=[];for(let[,n]of Object.entries(t)){let r=[...n.sources?.cdkInsights?.issues??[],...n.sources?.cdkNag?.issues??[]];for(let i of r){let o=i.constructType||n.constructType||n.type||"Unknown",a=EQ(i,n);s.push({issue:i,group:n,service:o,sourceLocation:a})}}s.sort((n,r)=>{let i=m4[n.issue.severity]||0;return(m4[r.issue.severity]||0)-i});for(let{issue:n,group:r,service:i,sourceLocation:o}of s)e.push([r.friendlyName||r.resourceId,n.stackName||"Unknown",`${AQ(n.severity)} ${n.severity}`,i,n.issue,o||n.locationHint||""]);console.log(e.toString())}});var ll=O((mRe,RQ)=>{RQ.exports={name:"cdk-insights",version:"1.29.0",description:"AWS CDK security and cost analysis CLI. Free static scans via npm \u2014 no account needed. Sign up free to add AI-powered insights.",main:"dist/index.js",types:"dist/index.d.ts",bin:{"cdk-insights":"dist/entry.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.js"}},files:["dist/**/*","README.md","LICENSE"],scripts:{test:"vitest --run",lint:"biome lint src/",typecheck:"tsc --noEmit",format:"biome format --write src/",check:"biome check src/","check:schema-sync":"ts-node scripts/check-schema-sync.ts",build:"ts-node scripts/build.ts","build:dev":"CDK_INSIGHTS_ENVIRONMENT=dev CDK_INSIGHTS_API_URL=https://s2zhmjbwlj.execute-api.eu-west-2.amazonaws.com/v1 ts-node scripts/build.ts",start:"node dist/index.js",dev:"ts-node src/index.ts",prepare:"husky install && npm run build","start:dev":"CDK_ENV=local ts-node src/index.ts","ai-run":"ts-node src/index.ts",unlink:"npm unlink -g cdk-insights",link:"npm link","prepare:test":"npm run unlink && npm run build && npm run link","prepare:dev":"npm run unlink && npm run build:dev && npm run link","deploy:dev":"STAGE=dev cdk deploy","destroy:dev":"STAGE=dev cdk destroy","release:patch":"bumper release patch","release:minor":"bumper release minor","release:major":"bumper release major","release:dry-run":"bumper release patch --dry-run","changelog:preview":"bumper preview","changelog:generate":"bumper generate","validate:commits":"bumper validate","release:check":"npm run validate:commits && npm run test && npm run build","release:full":"npm run release:check && npm run changelog:generate","setup:bumper":"bumper setup","publish:beta":"npm run build && npm publish --tag beta && npm dist-tag add cdk-insights@$npm_package_version latest","publish:alpha":"npm run build && npm publish --tag alpha","publish:canary":"npm run build && npm publish --tag canary","publish:latest":"npm run build && npm publish --tag latest","version:beta":"npm version prerelease --preid=beta","version:alpha":"npm version prerelease --preid=alpha","version:rc":"npm version prerelease --preid=rc","cdk-insights":"node scripts/cdk-insights-wrapper.js",scan:"node scripts/cdk-insights-wrapper.js scan","scan:all":"node scripts/cdk-insights-wrapper.js scan --all","scan:json":"node scripts/cdk-insights-wrapper.js scan --format json","scan:markdown":"node scripts/cdk-insights-wrapper.js scan --format markdown","scan:summary":"node scripts/cdk-insights-wrapper.js scan --format summary","scan:with-issues":"node scripts/cdk-insights-wrapper.js scan --withIssue","cache:clear":"node scripts/cdk-insights-wrapper.js cache clear","cache:status":"node scripts/cdk-insights-wrapper.js cache status","demo:progress":"ts-node src/examples/progress-demo.ts","demo:single-line":"ts-node src/examples/single-line-progress-demo.ts","test:line-clearing":"ts-node src/examples/line-clearing-test.ts"},publishConfig:{access:"public"},keywords:["aws","cdk","cloudformation","analysis","security","cost-optimization","static-analysis","devops","infrastructure","aws-cdk","cloud-security","compliance"],author:"Lee Priest <lee@cdkinsights.dev>",license:"BUSL-1.1",homepage:"https://github.com/instancelabs/cdk-insights",bugs:"https://github.com/instancelabs/cdk-insights/issues",repository:{type:"git",url:"git+https://github.com/instancelabs/cdk-insights.git"},dependencies:{"@inquirer/prompts":"^7.4.1","@middy/core":"^6.1.6","@types/glob":"^8.1.0",axios:"^1.8.4",chalk:"^5.4.1",chokidar:"^3.6.0","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.5.0",envolution:"^1.4.1",glob:"^11.0.3",ora:"^8.2.0",strogger:"^2.0.3",yargs:"^17.7.2",zod:"^3.23.8"},devDependencies:{"@aws-sdk/client-dynamodb":"^3.788.0","@biomejs/biome":"^2.0.6","@commitlint/cli":"^19.8.1","@commitlint/config-conventional":"^19.8.1","@types/cli-progress":"^3.11.6","@types/jsonwebtoken":"^9.0.9","@types/node":"^22.14.1","@types/yargs":"^17.0.33","aws-cdk":"^2.1010.0","bumper-cli":"^1.6.0",esbuild:"^0.25.2",husky:"^8.0.3","ts-node":"^10.9.2",typescript:"^5.8.3",vitest:"^3.1.1"},peerDependencies:{"aws-cdk-lib":"^2.190.0","cdk-nag":"^2.35.73",constructs:"^10.4.2"},optionalDependencies:{"@aws-solutions-constructs/aws-apigateway-lambda":"^2.0.0","@aws-solutions-constructs/aws-lambda-stepfunctions":"^2.0.0","@aws-solutions-constructs/aws-s3-lambda":"^2.0.0"}}});var g4,IQ,h4,_Q,y4,x4=D(()=>{"use strict";g4=oe(require("node:fs"));lt();tl();({version:IQ}=ll()),h4={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3},_Q=(t,e,s)=>{let n=Object.entries(s).map(([r,i])=>{let o=[...i.sources?.cdkInsights?.issues??[],...i.sources?.cdkNag?.issues??[]].slice().sort((c,u)=>h4[c.severity]-h4[u.severity]),a=em(o,i.cdkPath);return{resourceId:i.resourceId,logicalId:i.logicalId,cdkName:i.friendlyName,resourceName:i.resourceName,cdkPath:i.cdkPath,githubUrl:i.githubUrl,docUrl:i.docUrl,constructType:i.constructType,parentPath:i.parentPath,childCount:i.childCount,tags:i.tags,sourceLocation:i.sourceLocation,constructHierarchy:i.constructHierarchy,serviceCategory:i.serviceCategory,dependencies:i.dependencies,sensitiveProperties:i.sensitiveProperties,usesDefaults:i.usesDefaults,l2ConstructType:i.l2ConstructType,l2ConstructId:i.l2ConstructId,createdBy:i.createdBy,rootSourceLocation:i.rootSourceLocation,searchHint:i.searchHint,issues:a.map(c=>({issue:c.issue,recommendation:c.recommendation,severity:c.severity,wafPillar:c.wafPillar,codeSnippet:c.codeSnippet,locationHint:c.locationHint,foundBy:c.foundBy,sourceLocation:c.sourceLocation,stackName:c.stackName}))}});return{stackName:t,generatedAt:new Date().toISOString(),version:IQ,summary:e,recommendations:n}},y4=(t,e,s)=>{let n=_Q(t,e,s),r=`${t}_analysis_report.json`;try{g4.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),Oe.info(`\u{1F4C4} JSON report written to ${r}`)}catch(i){let o=i instanceof Error?i.message:String(i);throw Oe.error(`\u274C Failed to write JSON report to ${r}: ${o}`),new Error(`Failed to write analysis report: ${o}`)}return n}});var kQ,FQ,b4,fm,TQ,yS=D(()=>{"use strict";({version:kQ}=ll()),FQ=t=>{switch(t){case"CRITICAL":case"HIGH":return"error";case"MEDIUM":return"warning";default:return"note"}},b4=t=>{switch(t){case"CRITICAL":return 9;case"HIGH":return 7;case"MEDIUM":return 4;case"LOW":return 2;default:return 1}},fm=(t,e)=>{let s=[],n=[],r=new Set;for(let[i,o]of Object.entries(e)){let a=[...o.sources?.cdkInsights?.issues||[],...o.sources?.cdkNag?.issues||[]];for(let c of a){let u=TQ(c);r.has(u)||(r.add(u),s.push({id:u,name:c.issue.slice(0,100),shortDescription:{text:c.issue},fullDescription:c.recommendation?{text:c.recommendation}:void 0,helpUri:c.docUrl||c.githubUrl,properties:{"security-severity":b4(c.severity).toString(),tags:[c.wafPillar,c.severity,c.foundBy].filter(Boolean)}}));let d=(c.sourceLocation?.frames?.slice(1)??[]).map(p=>({physicalLocation:{artifactLocation:{uri:p.filePath,uriBaseId:"%SRCROOT%"},region:{startLine:p.line,startColumn:p.column}},message:{text:p.kind==="property"&&p.propertyName?`Property set: ${p.propertyName}`:p.kind==="creation"?"Construct created here":"Related call site"}}));n.push({ruleId:u,level:FQ(c.severity),message:{text:c.recommendation||c.issue},locations:[{physicalLocation:{artifactLocation:{uri:c.sourceLocation?.filePath||`cdk.out/${t}.template.json`,uriBaseId:"%SRCROOT%"},region:c.sourceLocation?{startLine:c.sourceLocation.line,startColumn:c.sourceLocation.column}:void 0}}],...d.length>0?{relatedLocations:d}:{},properties:{"security-severity":b4(c.severity).toString(),wafPillar:c.wafPillar,recommendation:c.recommendation}})}}return{$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"cdk-insights",version:kQ,informationUri:"https://cdkinsights.dev",rules:s}},results:n}]}},TQ=t=>{let e=t.issue.toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,50);return`CDK-${t.severity}-${e}`}});var xS,S4,v4=D(()=>{"use strict";xS=oe(require("node:fs"));lt();um();f4();gS();x4();yS();hS();S4=(t,e,s,n,r)=>{switch(Oe.info(`Generating output in format: ${t}`),t){case"markdown":{let i=Ac(e,s,r,n),o=`${e}_analysis_report.md`;try{xS.writeFileSync(o,i),Oe.info(`\u{1F4C4} Saved Markdown report to ${o}`)}catch(a){let c=a instanceof Error?a.message:String(a);throw Oe.error(`\u274C Failed to write Markdown report to ${o}: ${c}`),new Error(`Failed to write Markdown report: ${c}`)}break}case"table":{ul(s);break}case"json":{let i=y4(e,r,s);process.stdout.write(`${JSON.stringify(i,null,2)}
|
|
293
293
|
`);break}case"sarif":{let i=fm(e,s),o=`${e}_analysis_report.sarif`;try{xS.writeFileSync(o,JSON.stringify(i,null,2)),Oe.info(`\u{1F4C4} SARIF report written to: ${o}`),console.log(JSON.stringify(i,null,2))}catch(a){let c=a instanceof Error?a.message:String(a);throw Oe.error(`\u274C Failed to write SARIF report to ${o}: ${c}`),new Error(`Failed to write SARIF report: ${c}`)}break}case"github-actions":{dm(e,s,r.severityCounts,r.totalResources);break}default:p4(e,r);break}}});var mm,C4=D(()=>{"use strict";mm=(t,e,s,n)=>{let r=0,i=0,o={CRITICAL:0,HIGH:0,MEDIUM:0,LOW:0},a={"Operational Excellence":0,Security:0,"Cost Optimization":0,Reliability:0,"Performance Efficiency":0,Sustainability:0};for(let l in t){let d=[...t[l].sources.cdkInsights?.issues??[],...t[l].sources.cdkNag?.issues??[]],p=!s||s.has(l);d.length>0&&p&&i++,r+=d.length;for(let f of d)o[f.severity]+=1,a[f.wafPillar]+=1}let c=e,u=c>0?Number.parseFloat((i/c*100).toFixed(1)):0;return{totalResources:c,resourcesWithIssues:i,percentWithIssues:u,totalIssues:r,severityCounts:o,wafIssues:a,generatedBy:"cdk-insights",generatedAt:new Date().toISOString(),...n?{aiSkippedReason:n}:{}}}});var D4,w4,A4=D(()=>{"use strict";D4=oe(require("node:crypto")),w4=t=>D4.createHash("sha256").update(JSON.stringify(t)).digest("hex")});var hm,PQ,LQ,bS,SS=D(()=>{"use strict";hm=(t,e)=>e.endsWith("*")?t.startsWith(e.slice(0,-1)):t===e,PQ=(t,e)=>{if(!t)return!1;let s=t.startsWith("/")?t.slice(1):t,n=e.startsWith("/")?e.slice(1):e;return n?s===n||s.startsWith(`${n}/`):!0},LQ=(t,e,s)=>!t.ruleId||s.length===0||e.length===0?!1:s.some(n=>n.ruleId===t.ruleId&&e.some(r=>PQ(r,n.constructPath))),bS=(t,e,s)=>{let{ignoreRules:n=[],ignorePaths:r=[],acknowledgements:i=[]}=s;return n.length===0&&r.length===0&&i.length===0?!1:r.some(a=>e.some(c=>hm(c,a)))||t.ruleId&&n.some(c=>hm(t.ruleId,c))?!0:LQ(t,e,i)}});var OQ,MQ,BQ,NQ,E4,R4=D(()=>{"use strict";OQ=[/depends\s*on.*(?:not\s*(?:be\s*)?available|may\s*not\s*exist|circular)/i,/dependson.*relationship/i,/resource.*depends.*another.*resource/i,/dependency.*(?:not\s*)?(?:be\s*)?ready/i,/lacks?\s*(?:meaningful\s*)?tags?(?:\s*for)?/i,/missing.*tags?.*(?:metadata|identification)/i,/no\s*tags?\s*(?:defined|configured|specified)/i,/does\s*not\s*have\s*any\s*tags/i,/tags?.*(?:auditing|cost\s*allocation|management)/i,/\[redacted\].*(?:incomplete|invalid|malformed|missing)/i,/incomplete.*\[redacted\]/i,/placeholder.*value/i,/missing.*closing.*brace/i,/replac(?:e|ing).*\[redacted\]/i,/\[redacted\].*(?:should|could|must)\s*be/i,/trust.*policy.*any.*service.*\[redacted\]/i,/any.*service.*within.*account.*\[redacted\]/i,/cdk.*metadata.*exposed/i,/metadata.*cdk.*path/i,/nat\s*gateway.*(?:move|associated).*(?:private\s*subnet|public\s*subnet.*risk)/i,/move.*nat\s*gateway.*private/i,/eip.*not\s*associated.*(?:instance|resource)/i,/elastic\s*ip.*not.*(?:associated|utilized|being\s*used)/i,/userdata\s*(?:script\s*)?is\s*empty/i,/empty.*userdata/i,/routetable.*(?:tags?|metadata)/i,/iam.*(?:policy|role).*(?:grants?|has).*(?:sts:assumerole|administratoraccess).*(?:overly\s*)?permissive/i,/inline\s*policy\s*grants?\s*unrestricted\s*access\s*to\s*all/i,/subnet.*mappubliciponlaunch.*(?:true|set)/i,/mappubliciponlaunch.*(?:expose|public\s*ip|internet)/i,/instances.*launched.*subnet.*public\s*ip/i],MQ=[/tags?/i,/naming\s*convention/i,/resource\s*name.*not.*descriptive/i,/lacks?\s*description/i,/missing\s*description/i,/default\s*iam\s*role.*(?:broad|permissive)/i,/security\s*group.*(?:all\s*outbound|all\s*egress|unrestricted\s*egress)/i,/allows?\s*all\s*outbound\s*traffic/i],BQ=t=>OQ.some(e=>e.test(t)),NQ=t=>MQ.some(e=>e.test(t)),E4=(t,e=!1)=>t.filter(s=>{let n=s.issue||"";return!(BQ(n)||e&&NQ(n))})});var I4,_4=D(()=>{"use strict";lt();tl();R4();I4=({staticRecommendations:t,aiRecommendations:e,recommendationMap:s,ruleFilter:n,filterIssuesByRule:r,_displayNameMap:i={}})=>{let o={...s};for(let[d,{issues:p}]of Object.entries(t))o[d]&&(o[d].sources||(o[d].sources={cdkInsights:{issues:[]},cdkNag:{issues:[]}}),o[d].sources.cdkInsights||(o[d].sources.cdkInsights={issues:[]}),o[d].sources.cdkInsights.issues.push(...p));let a=0,c=0,u=0,l=0;for(let[d,p]of Object.entries(e)){if(!p||!Array.isArray(p.issues)){Oe.warn(`\u26A0\uFE0F No AI issues for resource '${d}', skipping.`);continue}let f=d;if(!o[f]){Oe.warn(`\u26A0\uFE0F AI recommendations for unknown resource '${f}', skipping enrichment.`);continue}let m=o[f],g=n.length>0?r(p.issues,n):p.issues,v=E4(g,m.isGenerated).map(S=>{switch(S.severity||(Oe.debug(`AI recommendation missing severity for resource '${f}', defaulting to MEDIUM`),S.severity="MEDIUM"),S.severity.toUpperCase()==="CRITICAL"&&(Oe.debug(`Capping AI finding from CRITICAL \u2192 HIGH for resource '${f}' (AI findings are advisory)`),S.severity="HIGH"),S.severity.toUpperCase()){case"CRITICAL":a++;break;case"HIGH":c++;break;case"MEDIUM":u++;break;case"LOW":l++;break;default:Oe.warn(`\u26A0\uFE0F Unknown severity '${S.severity}' for resource '${f}', defaulting to MEDIUM`),S.severity="MEDIUM",u++;break}return{resourceName:S.resourceName||m.resourceName,resourceId:f,friendlyName:m.friendlyName,displayName:m.displayName,locationHint:S.locationHint||m.locationHint,constructPath:m.cdkPath,githubUrl:m.githubUrl,docUrl:m.docUrl,issue:S.issue||"AI analysis issue",recommendation:S.recommendation||"No specific recommendation provided",severity:S.severity,wafPillar:(()=>{if(S.wafPillar)switch(S.wafPillar.toLowerCase().trim()){case"security":return"Security";case"operational excellence":return"Operational Excellence";case"cost optimization":return"Cost Optimization";case"reliability":return"Reliability";case"performance efficiency":return"Performance Efficiency";case"sustainability":return"Sustainability";default:return"Security"}return"Security"})(),codeSnippet:S.codeSnippet||"",foundBy:S.foundBy??"cdkInsights"}}),x=em(v,m.cdkPath);m.sources||(m.sources={cdkInsights:{issues:[]},cdkNag:{issues:[]}}),m.sources.cdkInsights||(m.sources.cdkInsights={issues:[]}),m.sources.cdkInsights.issues.push(...x)}return{updatedMap:o,criticalCount:a,highCount:c,mediumCount:u,lowCount:l}}});var gm,vS,$Q,WQ,CS=D(()=>{"use strict";gm=t=>{if(!t||t.length===0)return 0;let e=t.length,s=new Map;for(let r of t)s.set(r,(s.get(r)||0)+1);let n=0;for(let r of s.values()){let i=r/e;n-=i*Math.log2(i)}return n},vS=(t,e=!1)=>{if(t.length<16||$Q(t)||gm(t)<(e?4:4.5))return!1;let r=/[A-Z]/.test(t),i=/[a-z]/.test(t),o=/[0-9]/.test(t),a=/[^A-Za-z0-9]/.test(t),c=[r,i,o,a].filter(Boolean).length;return e?c>=1:c>=2},$Q=t=>{if(/^https?:\/\//i.test(t)||/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^arn:aws[a-z-]*:[a-z0-9-]+:[a-z0-9-]*:\d*:/.test(t)||/^(\/|\.\/|\.\.\/|[A-Za-z]:\\)/.test(t)||/^s3:\/\/[a-z0-9.-]+\//.test(t)||/^[A-Za-z][A-Za-z0-9]*(DefaultPolicy|DefaultRole|ServiceRole|EventsRole|ExecutionRole|LogRetention|LambdaFunction|Handler|Function|Role|Policy)[A-F0-9]{8,}$/.test(t)||/^sha256:[a-f0-9]{64}$/.test(t)||/^[a-f0-9]{40}$/.test(t)||/^Z[A-Z0-9]{14,22}$/.test(t)||/^[a-z]{2}-[a-z]+-\d_[A-Za-z0-9]{9,}$/.test(t)||/^(vpc|subnet|sg|igw|nat|rtb|acl|eni|i|ami|vol|snap|eipalloc)-[a-f0-9]{8,17}$/.test(t)||/^E[A-Z0-9]{13}$/.test(t))return!0;if(/^[A-Za-z0-9+/]{4,}={0,2}$/.test(t)){let e=new Set(t).size;if(t.length>50&&e<10)return!0}return!!WQ(t)},WQ=t=>{let e=t.length;for(let s=1;s<=e/2;s++)if(t.slice(0,s).repeat(Math.ceil(e/s)).slice(0,e)===t)return!0;return!1}});var DS,wS,jQ,UQ,HQ,GQ,k4,F4,AS,ES,RS,IS,ym,_S,kS=D(()=>{"use strict";DS=[/api[_-]?key/i,/secret[_-]?key/i,/^password$/i,/^passwd$/i,/credential/i,/private[_-]?key/i,/access[_-]?key/i,/auth[_-]?token/i,/bearer[_-]?token/i,/refresh[_-]?token/i,/client[_-]?secret/i,/app[_-]?secret/i,/secret[_-]?value/i,/aws[_-]?secret/i,/aws[_-]?access[_-]?key/i,/aws[_-]?session[_-]?token/i,/db[_-]?password/i,/database[_-]?password/i,/master[_-]?password/i,/master[_-]?user[_-]?password/i,/admin[_-]?password/i,/root[_-]?password/i,/connection[_-]?string/i,/stripe[_-]?key/i,/stripe[_-]?secret/i,/github[_-]?token/i,/gitlab[_-]?token/i,/slack[_-]?token/i,/slack[_-]?webhook/i,/discord[_-]?token/i,/twilio[_-]?token/i,/sendgrid[_-]?key/i,/mailgun[_-]?key/i,/datadog[_-]?key/i,/new[_-]?relic[_-]?key/i,/sentry[_-]?dsn/i,/webhook[_-]?secret/i,/signing[_-]?key/i,/signing[_-]?secret/i,/encryption[_-]?key/i,/jwt[_-]?secret/i,/hmac[_-]?key/i,/ssh[_-]?key/i,/ssh[_-]?private/i,/pem[_-]?key/i,/rsa[_-]?key/i],wS=[/^A[BGIK-Z][A-Z]{2}[0-9A-Z]{16}$/,/^[A-Za-z0-9/+=]{40}$/,/-----BEGIN (RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----/,/-----BEGIN PGP PRIVATE KEY BLOCK-----/,/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,/^gh[pousr]_[A-Za-z0-9]{36,}$/,/^[srp]k_(live|test)_[A-Za-z0-9]{24,}$/,/^xox[bpas]-[A-Za-z0-9-]+$/,/^SK[a-f0-9]{32}$/i,/^SG\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/],jQ=[/\{\{resolve:secretsmanager:/,/{{resolve:secretsmanager:/,/\{\{resolve:ssm:/,/{{resolve:ssm:/,/\{\{resolve:ssm-secure:/,/{{resolve:ssm-secure:/,/^\/[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+(\/[a-zA-Z0-9_.-]+)+$/,/!Ref\s+\w+/,/!GetAtt\s+[\w.]+/,/!Sub\s+/,/\$\{[\w:.]+\}/,/\$\{Token\[/,/\[\[token:/i,/\${Token\[TOKEN\.\d+\]\}/,/^arn:aws[a-z-]*:[a-z0-9-]+:[a-z0-9-]*:\d*:/],UQ=[/^<[^>]+>$/,/^CHANGE[_-]?ME$/i,/^REPLACE[_-]?ME$/i,/^TODO$/i,/^TODO:/i,/^FIXME$/i,/^XXX$/i,/^YOUR[_-]/i,/^INSERT[_-]/i,/^ENTER[_-]/i,/^\*+$/,/^x+$/i,/^\s*$/,/^default$/i,/^example$/i,/^sample$/i,/^test$/i,/^demo$/i,/^dummy$/i,/^fake$/i,/^mock$/i,/^placeholder$/i],HQ=[/^Description$/i,/^AlarmDescription$/i,/^Comment$/i,/^Label$/i,/^Summary$/i,/^DisplayName$/i,/^Name$/i,/^PolicyName$/i,/^RoleName$/i,/^FunctionName$/i,/^QueueName$/i,/^TopicName$/i,/^BucketName$/i,/^TableName$/i,/^StreamName$/i,/^LogGroupName$/i,/^ParameterName$/i,/^SecretName$/i,/^StateMachineName$/i,/^RuleName$/i,/^AliasName$/i,/^StackName$/i,/^GroupName$/i,/^UserName$/i,/^PolicyDocument$/i,/^ClientId$/i,/^UserPoolClientId$/i,/^UserPoolId$/i,/^IdentityPoolId$/i,/^DistributionId$/i,/^HostedZoneId$/i,/^CertificateArn$/i,/^TopicArn$/i,/^QueueArn$/i,/^FunctionArn$/i,/^Arn$/i,/^EventPattern$/i,/^Definition$/i,/^DefinitionString$/i,/^Template$/i,/^TemplateURL$/i,/^TemplateBody$/i,/^EventSourceName$/i,/^PartnerEventSource$/i],GQ=[/(?:^|\.)Targets\[\d+\]\.Input$/,/(?:^|\.)Create$/,/(?:^|\.)Update$/,/(?:^|\.)Delete$/,/(?:^|\.)DefinitionString$/,/(?:^|\.)Code\.ZipFile$/,/(?:^|\.)Statement\[\d+\]\.Resource$/,/(?:^|\.)Statement\[\d+\]\.Resource\[\d+\]$/,/(?:^|\.)Statement\[\d+\]\.Sid$/],k4=t=>HQ.some(e=>e.test(t)),F4=t=>GQ.some(e=>e.test(t)),AS=t=>DS.some(e=>e.test(t)),ES=t=>wS.some(e=>e.test(t)),RS=t=>jQ.some(e=>e.test(t)),IS=t=>UQ.some(e=>e.test(t)),ym=t=>{if(typeof t!="object"||t===null)return!1;let e=["Ref","Fn::GetAtt","Fn::Sub","Fn::Join","Fn::ImportValue","Fn::If","Fn::Select","Fn::Split","Fn::Base64","Fn::Cidr","Fn::FindInMap","Fn::GetAZs","Fn::Transform"],s=Object.keys(t);return s.length===1&&e.includes(s[0])},_S=t=>{let e=[{patterns:[/api[_-]?key/i,/access[_-]?key/i],category:"api_key"},{patterns:[/password/i,/passwd/i],category:"password"},{patterns:[/private[_-]?key/i,/ssh[_-]?key/i,/pem[_-]?key/i,/rsa[_-]?key/i],category:"private_key"},{patterns:[/aws[_-]?secret/i,/aws[_-]?access/i],category:"aws_credentials"},{patterns:[/token/i,/bearer/i],category:"token"},{patterns:[/secret/i,/credential/i],category:"secret"},{patterns:[/connection[_-]?string/i,/database/i,/db[_-]/i],category:"database"},{patterns:[/webhook/i,/signing/i,/encryption/i,/hmac/i,/jwt/i],category:"encryption_key"}];for(let{patterns:s,category:n}of e)if(s.some(r=>r.test(t)))return n;return"secret"}});var dl,pl,FS=D(()=>{"use strict";dl=t=>{let e={api_key:`Use AWS Secrets Manager to store API keys securely:
|
|
294
294
|
|
|
295
295
|
// CDK TypeScript example:
|
|
@@ -449,7 +449,7 @@ See: https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html`},pl
|
|
|
449
449
|
`)},eX=t=>{let e=t.diagnostics;switch(t.detectionReason){case"high_entropy":return e?.entropy!==void 0&&e?.entropyThreshold!==void 0?`high entropy (${e.entropy} bits/char, threshold ${e.entropyThreshold})`:"high entropy";case"value_pattern":return e?.matchedValuePattern?`value matches known-secret pattern /${e.matchedValuePattern}/`:"value matches a known-secret pattern";case"property_name":return`sensitive property name "${t.propertyName}"`;default:return"value appears sensitive"}},tX=t=>{let e=t.findings.map(i=>`'${i.propertyPath}'`).join(", "),s=t.findings.some(i=>i.detectionReason==="high_entropy"),n=t.findings.some(i=>i.detectionReason==="property_name"),r=[];return r.push(" - A hardcoded API key, token, or password \u2192 move to AWS Secrets Manager or SSM Parameter Store."),s&&(r.push(" - A CDK-auto-generated resource name (likely if the property is a *Name) \u2192 provide an explicit name on the construct, or trust the short-circuit shipped with cdk-insights 1.2.7+."),r.push(" - A content hash (git SHA, Docker digest, JWT) \u2192 already exempt in 1.2.7+; upgrade the CLI if this is still firing.")),n&&r.push(" - An SSM parameter path or similar safe reference stored in a sensitive-sounding env var \u2192 pass it via CloudFormation intrinsics (Fn::Sub, !Ref) or SSM dynamic references ({{resolve:ssm:...}}) so the scanner can recognise it."),["Likely causes (in rough order of likelihood):",...r,"","If this is a known false positive, suppress it via the scanner config:",` { "ignoreProperties": [${e}] }`,"","See: https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html"].join(`
|
|
450
450
|
`)},OS=(t,e={})=>{let s=[],n=[],r=0;for(let[i,o]of Object.entries(t)){let a=L4(o,i,e);s.push(a),a.hasSensitiveData&&(n.push(i),r+=a.findings.length)}return{totalResourcesScanned:Object.keys(t).length,resourcesWithSensitiveData:n.length,totalFindings:r,hasSkippedResources:n.length>0,skippedResourceIds:n,detectionResults:s}}});var B4=D(()=>{"use strict";M4();TS();kS();CS();FS()});function $4(t,e){if(!t||typeof t!="object")return et.warn(`Custom rule '${e}': condition must be an object`),!1;let s=t;if(!s.type||!rX.has(s.type))return et.warn(`Custom rule '${e}': invalid condition type '${s.type}'`),!1;if(s.type==="and"||s.type==="or")return!Array.isArray(s.conditions)||s.conditions.length===0?(et.warn(`Custom rule '${e}': '${s.type}' condition requires non-empty conditions array`),!1):s.conditions.every(n=>$4(n,e));if(typeof s.path!="string"||s.path.length===0)return et.warn(`Custom rule '${e}': condition requires a non-empty 'path'`),!1;if(s.type==="property_matches")try{new RegExp(s.pattern)}catch{return et.warn(`Custom rule '${e}': invalid regex pattern '${s.pattern}'`),!1}return(s.type==="property_gt"||s.type==="property_lt")&&typeof s.value!="number"?(et.warn(`Custom rule '${e}': '${s.type}' requires a numeric value`),!1):!0}function iX(t,e){if(!t||typeof t!="object")return et.warn(`Custom rule at index ${e}: must be an object`),null;let s=t;return typeof s.ruleId!="string"||s.ruleId.length===0?(et.warn(`Custom rule at index ${e}: ruleId is required`),null):typeof s.name!="string"||s.name.length===0?(et.warn(`Custom rule '${s.ruleId}': name is required`),null):typeof s.description!="string"?(et.warn(`Custom rule '${s.ruleId}': description is required`),null):sX.has(s.severity)?nX.has(s.wafPillar)?!Array.isArray(s.resourceTypes)||s.resourceTypes.length===0?(et.warn(`Custom rule '${s.ruleId}': resourceTypes must be a non-empty array`),null):typeof s.recommendation!="string"?(et.warn(`Custom rule '${s.ruleId}': recommendation is required`),null):$4(s.condition,s.ruleId)?s:null:(et.warn(`Custom rule '${s.ruleId}': invalid wafPillar '${s.wafPillar}'`),null):(et.warn(`Custom rule '${s.ruleId}': invalid severity '${s.severity}'`),null)}function W4(t=process.cwd()){let e=N4.join(t,bm);if(!Sm.existsSync(e))return[];try{let s=Sm.readFileSync(e,"utf-8"),n=JSON.parse(s);if(!n.rules||!Array.isArray(n.rules))return et.warn(`${bm}: 'rules' must be an array`),[];let r=[];for(let i=0;i<n.rules.length;i++){let o=iX(n.rules[i],i);o&&r.push(o)}return r.length>0&&et.info(`Loaded ${r.length} custom rule(s) from ${bm}`),r}catch(s){return et.warn(`Failed to load ${bm}: ${s instanceof Error?s.message:String(s)}`),[]}}var Sm,N4,bm,sX,nX,rX,j4=D(()=>{"use strict";Sm=oe(require("node:fs")),N4=oe(require("node:path"));lt();bm=".cdk-insights-rules.json",sX=new Set(["CRITICAL","HIGH","MEDIUM","LOW"]),nX=new Set(["Operational Excellence","Security","Cost Optimization","Reliability","Performance Efficiency","Sustainability"]),rX=new Set(["property_exists","property_equals","property_matches","property_gt","property_lt","and","or"])});var MS,vm,U4,oX,H4=D(()=>{"use strict";MS=require("aws-cdk-lib"),vm=require("cdk-nag");lt();U4="cdk-insights::",oX=`${U4}nagFinding::`});var ml,Cm=D(()=>{"use strict";ml="1.0.0"});var G4=D(()=>{"use strict"});var z4=D(()=>{"use strict"});var q4=D(()=>{"use strict"});var V4=D(()=>{"use strict";G4();Bb();SS();z4();q4();Kf()});var J4,wm,aX,cX,uX,lX,Ci,dX,K4,pX,Dm,fX,mX,hX,gX,Z4,yX,xX,Y4,Am,BS=D(()=>{"use strict";J4=oe(require("node:fs"));Jn();Fb();Tb();LT();NT();Bb();K3();B8();Kd();K8();J8();s4();o4();u4();tl();l4();wb();hS();um();v4();C4();A4();yS();SS();Bf();gS();_4();Gb();B4();j4();oS();qa();lt();$r();H4();Cm();V4();wm=async(t,e)=>{try{return await t()}catch(s){return re.warn(`\u26A0\uFE0F Error in ${e.operationName}:`,{error:s}),e.fallbackValue}},aX=t=>!t||t.length===0||t.includes("All services"),cX=(t,e)=>{if(aX(e))return t;let s=new Set((e??[]).map(n=>`AWS::${n}::`));return Object.fromEntries(Object.entries(t).filter(([,n])=>{for(let r of s)if(n.Type.startsWith(r))return!0;return!1}))},uX=t=>Object.fromEntries(Object.entries(t).filter(([,e])=>!e.Type.startsWith("AWS::CDK::"))),lX=t=>{let{stackName:e,pathToLogicalId:s}=t;return n=>({resourceId:n,friendlyName:s[n]??n,cdkPath:`${e}/${n}`,isGenerated:!1,sources:{cdkInsights:{issues:[]},cdkNag:{issues:[]}}})},Ci=(t,e,s)=>{let n=t[e];if(n)return n;let r=s(e);return t[e]=r,r},dX=t=>[...t.sources?.cdkInsights?.issues??[],...t.sources?.cdkNag?.issues??[]],K4=t=>{for(let e of Object.values(t)){for(let s of e.sources?.cdkInsights?.issues??[])if(s.severity==="CRITICAL")return!0;for(let s of e.sources?.cdkNag?.issues??[])if(s.severity==="CRITICAL")return!0}return!1},pX=t=>{for(let[e,s]of Object.entries(t))(s.sources?.cdkInsights?.issues?.length??0)>0||(s.sources?.cdkNag?.issues?.length??0)>0||delete t[e];return t},Dm=(t,e,s,n,r,i,o)=>({resourceId:t,issue:e,recommendation:s,severity:n,wafPillar:r,foundBy:o,constructPath:i}),fX=t=>{let{recommendationMap:e,stackName:s,stackResources:n,manifest:r}=t;try{let i=new Map,o=a=>{let c=i.get(a);if(c)return c;let u=Mf(r,a);return i.set(a,u),u};return Object.entries(e).reduce((a,[c,u])=>{let l=u.cdkPath||c,d=o(l),p=n[c]?.Type||"Unknown",f=m=>({...m,...d?.filePath&&{sourceLocation:{filePath:d.filePath,line:d.line||1,column:d.column||1,confidence:d.confidence||"low"}},stackName:s,constructType:p});return a[c]={...u,sources:{cdkInsights:{issues:(u.sources?.cdkInsights?.issues??[]).map(f)},cdkNag:{issues:(u.sources?.cdkNag?.issues??[]).map(f)}}},a},{})}catch(i){return re.warn("\u26A0\uFE0F Could not enrich issues with source location:",{error:i}),e}},mX=t=>{let{authToken:e,fingerprint:s,tier:n,quotaValidation:r}=t,i=!!(e&&s&&n),o=!r||r.canRunStaticAnalysis,a=!r||r.canRunAIAnalysis,c=!!(n&&Sr.isFeatureEnabled("aiAnalysis",n));return{hasAuth:i,canRunStatic:o,canRunAI:i&&c&&a,isAiEnabledByTier:c,canRunAIByQuota:a}},hX=async t=>{let{userResources:e,selectedServices:s,constructRegistry:n,canRunStatic:r,customRules:i=[],ruleContext:o}=t,a=Object.keys(e).length;return a===0?{}:r?(T.phase1(`Static analysis on ${a} resource${a===1?"":"s"}`),await wm(()=>Promise.resolve(Mb({Resources:e},Dm,s||[],n,i,o)),{operationName:"static analysis",fallbackValue:{}})??{}):(T.warning("\u26A0\uFE0F Static analysis skipped due to license restrictions"),{})},gX=async t=>{let{stackName:e,userResources:s,inlineFindings:n,pathToLogicalId:r,authToken:i,fingerprint:o,tier:a,noCache:c=!1,cache:u,capabilities:l,aiModelId:d,aiBatchSize:p}=t,f=Object.keys(s).length;if(f===0)return{results:{}};if(!l.hasAuth)return{results:{},skippedReason:"auth"};if(a&&!l.isAiEnabledByTier)return T.comment("\u{1F4A1} AI analysis is available with Pro tier - upgrade for deeper insights"),{results:{},skippedReason:"unavailable"};if(!l.canRunAIByQuota&&l.canRunStatic)return a==="pro"?T.comment("\u{1F4A1} AI analysis skipped \u2014 monthly AI credit allowance reached. Static scans continue; AI resumes next billing cycle."):T.comment("\u{1F4A1} AI analysis skipped \u2014 credit allowance reached. Upgrade to Pro for 5,000 AI credits/month."),{results:{},skippedReason:"cap-reached"};if(!l.canRunAI)return{results:{},skippedReason:"unavailable"};if(!i||!o)return re.warn("AI analysis skipped: missing authToken or fingerprint"),{results:{},skippedReason:"auth"};T.phase2(`AI analysis on ${f} resource${f===1?"":"s"}`);let m=Wn(),g=t4(Rt,m),h=i4(Rt,m),v=s8(w4),x=M8({analyzeResource:g,analyzeResourcesBatch:h,redactResources:v});return{results:await wm(()=>x({stackName:e,resources:s,authToken:i,existingFindingsMap:n,pathToLogicalId:r,fingerprint:o,noCache:c,cacheConfig:u,aiModelId:d,aiBatchSize:p}),{operationName:"AI analysis",fallbackValue:{}})??{}}},Z4=t=>{let{recommendationMap:e,ignoreRules:s=[],ignorePaths:n=[],acknowledgements:r=[],baselineExclude:i,stackName:o=""}=t;if(s.length===0&&n.length===0&&r.length===0&&(!i||i.size===0))return e;for(let[a,c]of Object.entries(e)){let u=[a,c.cdkPath,c.friendlyName,c.displayName].filter(p=>typeof p=="string"&&p.length>0);if(n.some(p=>u.some(f=>hm(f,p)))){delete e[a];continue}let d=[c.cdkPath].concat(u).filter(p=>typeof p=="string"&&p.length>0);for(let p of["cdkInsights","cdkNag"]){let f=c.sources?.[p];f&&(f.issues=f.issues.filter(m=>{let g=[m.constructPath,...d].filter(v=>typeof v=="string"&&v.length>0);if(bS(m,g,{ignoreRules:s,acknowledgements:r}))return!1;if(i&&i.size>0){let v=pS(o,c,m);if(i.has(v))return!1}return!0}))}}return e},yX=t=>{let{recommendationMap:e,ruleFilter:s}=t;if(s.length===0)return e;for(let[n,r]of Object.entries(e)){let i=dX(r),o=fS(i,s);if(o.length===0){delete e[n];continue}r.sources||(r.sources={cdkInsights:{issues:[]},cdkNag:{issues:[]}}),r.sources.cdkInsights||(r.sources.cdkInsights={issues:[]}),r.sources.cdkNag||(r.sources.cdkNag={issues:[]}),r.sources.cdkInsights.issues=o.filter(a=>a.foundBy==="cdkInsights"),r.sources.cdkNag.issues=o.filter(a=>a.foundBy==="cdkNag")}return e},xX=async t=>{let{stackName:e,recommendationMap:s,summary:n,tier:r}=t;if(!r||!Sr.isFeatureEnabled("githubIntegration",r)){T.warning("GitHub integration is not available for your current tier"),T.comment(Vd("githubIntegration",r??"free","GitHub integration"));return}let i=Y8(),o=!!process.env.GITHUB_TOKEN;if(!i&&!o){T.warning("GitHub CLI not found and GITHUB_TOKEN not set. Skipping issue creation."),T.comment("Install GitHub CLI (gh) or set GITHUB_TOKEN environment variable to enable issue creation.");return}T.section("Creating GitHub Issue","\u{1F419}");let a=Ac(e,s,n);await wm(()=>V8({stackName:e,issueTitle:`CDK Insights Analysis for ${e}`,issueBody:a,ghCli:i,recommendations:s,summary:n}),{operationName:"creating GitHub issue"})},Y4=async({stackName:t,stack:e,selectedServices:s,inlineFindings:n,recommendationMapPerStack:r,pathToLogicalId:i,constructRegistry:o,ruleFilter:a,ignoreRules:c,ignorePaths:u,acknowledgements:l=[],authToken:d,fingerprint:p,output:f,withIssue:m,tier:g,noCache:h=!1,warnSensitive:v=!1,sensitiveDataDetection:x={},cache:S,quotaValidation:w,manifest:E,customRules:P=[],cdkContext:k,resourceIdMetadata:A,aiModelId:M,aiBatchSize:z,forceLocal:C=!1,baselineExclude:U,collectFingerprints:_,skipRendering:Y=!1})=>{let y=e.Resources??{},b=cX(y,s),K=uX(b),q=new Set(Object.keys(K)),te=q.size,X=mX({authToken:d,fingerprint:p,tier:g,quotaValidation:w}),ee=lX({stackName:t,pathToLogicalId:i}),fe=r[t]||{},Re=me=>{let Je=ee(me),ht=fe[me];return ht?{...Je,...ht,sources:Je.sources}:Je},se=X.canRunAI?Object.fromEntries(Object.keys(K).map(me=>[me,Re(me)])):{};for(let[me,Je]of Object.entries(fe)){let ht=Je.sources?.cdkNag?.issues??[];if(ht.length===0)continue;Ci(se,me,Re).sources.cdkNag.issues.push(...ht)}for(let me of n)Ci(se,me.resourceId,Re).sources.cdkNag.issues.push(me);let Ce=k||A?{cdkContext:k,resourceIdMetadata:A}:void 0,G=await hX({userResources:K,selectedServices:s,constructRegistry:o,canRunStatic:X.canRunStatic,customRules:P,ruleContext:Ce});for(let[me,Je]of Object.entries(G)){let ht=Ci(se,me,Re),Wl=Je.issues??[];ht.sources.cdkInsights.issues.push(...Wl)}let xe=Nb(e,Dm,a);for(let[me,Je]of Object.entries(xe))Ci(se,me,Re).sources.cdkInsights.issues.push(...Je.issues);let ge=zf(e,Dm);for(let[me,Je]of Object.entries(ge))Ci(se,me,Re).sources.cdkInsights.issues.push(...Je.issues);let L=Gf(e,Dm);for(let[me,Je]of Object.entries(L))Ci(se,me,Re).sources.cdkInsights.issues.push(...Je.issues);let ae=OS(K,{disabled:x.disabled,ignoreProperties:x.ignoreProperties,allowPatterns:x.allowPatterns,strictMode:x.strictMode}),W=K;if(ae.hasSkippedResources){let me=ae.resourcesWithSensitiveData;T.warning(`\u{1F512} Sensitive data detected in ${me} resource${me===1?"":"s"} - NOT sent to CDK Insights servers`),W=Object.fromEntries(Object.entries(K).filter(([Je])=>!ae.skippedResourceIds.includes(Je)));for(let Je of ae.detectionResults)if(Je.hasSensitiveData){let ht=Ci(se,Je.resourceId,Re),Wl=LS(Je,t);ht.sources.cdkInsights.issues.push(Wl)}}let ue=new Set(Object.entries(se).filter(([,me])=>me.sources.cdkInsights.issues.length>0||me.sources.cdkNag.issues.length>0).map(([me])=>me)),De=Object.fromEntries(Object.entries(W).filter(([me])=>ue.has(me))),Be=Object.keys(W).length-Object.keys(De).length;Be>0&&X.canRunAI&&T.comment(`\u{1F3AF} Skipping AI analysis on ${Be} resource${Be===1?"":"s"} with no static findings`);let I=await gX({stackName:t,userResources:De,inlineFindings:n,pathToLogicalId:i,authToken:d,fingerprint:p,tier:g,noCache:h,cache:S,capabilities:X,aiModelId:M,aiBatchSize:z}),H=I.results,ce=C?"local-mode":I.skippedReason;d&&p&&Object.keys(H).length>0&&T.phase3("Processing results...");let ne=I4({staticRecommendations:{},aiRecommendations:H,recommendationMap:se,ruleFilter:a,filterIssuesByRule:fS});for(let[me,Je]of Object.entries(ne.updatedMap)){let ht=Ci(se,me,Re);ht.sources.cdkInsights.issues.push(...Zo({existing:ht.sources.cdkInsights.issues,incoming:Je.sources.cdkInsights.issues}))}if(yX({recommendationMap:se,ruleFilter:a}),Z4({recommendationMap:se,ignoreRules:c,ignorePaths:u,acknowledgements:l}),_)for(let{fingerprint:me}of c4(t,se))_.add(me);U&&U.size>0&&Z4({recommendationMap:se,baselineExclude:U,stackName:t}),pX(se);let J=fX({recommendationMap:se,stackName:t,stackResources:K,manifest:E}),Ie=mm(J,te,q,ce),we=Object.keys(J).length>0;return r[t]=J,!Y&&f&&f!=="table"&&S4(f,t,J,!0,Ie),m&&we&&await xX({stackName:t,recommendationMap:J,summary:Ie,tier:g}),{recommendationMap:J,summary:Ie,hasIssues:we,scannedResourceCount:te,scannedResourceIds:q,stackName:t,sensitiveDataSummary:ae,hasSensitiveData:ae.hasSkippedResources}},Am=async({stacks:t,inlineFindings:e,pathToLogicalId:s,output:n,recommendationMapPerStack:r,withIssue:i,services:o,ruleFilter:a=[],ignoreRules:c=[],ignorePaths:u=[],acknowledgementsPerStack:l={},authToken:d,fingerprint:p,failOnCritical:f,tier:m,noCache:g=!1,allowOveruse:h=!1,warnSensitive:v=!1,sensitiveDataDetection:x={},cache:S,quotaValidation:w,cdkContext:E,resourceIdMetadata:P,aiModelId:k,aiBatchSize:A,forceLocal:M=!1,baselineExclude:z,collectFingerprints:C,skipRendering:U=!1})=>{if(re.info("\u{1F680} Starting CDK Insights analysis",{stackCount:Object.keys(t).length,stackNames:Object.keys(t),hasAuthToken:!!d,hasFingerprint:!!p,tier:m||"unknown",quotaValidation:w?{canRunStaticAnalysis:w.canRunStaticAnalysis,canRunAIAnalysis:w.canRunAIAnalysis,isTrial:w.quota?.isTrial}:null,services:o||["All services"],output:n||"table"}),w&&!w.quota.isTrial&&w.canRunAIAnalysis&&h){let Ce=w.quota.currentResourcesAnalyzed>=w.quota.maxResources,G=w.quota.wouldExceed;Ce?(T.warning(`\u26A0\uFE0F You have used ${w.quota.currentResourcesAnalyzed}/${w.quota.maxResources} AI credits this billing period.`),T.warning(" Proceeding with AI analysis as --allow-overuse is enabled.")):G&&(T.warning(`\u26A0\uFE0F This analysis will exceed your AI credit allowance (${w.quota.currentResourcesAnalyzed}/${w.quota.maxResources}).`),T.warning(" Proceeding with AI analysis as --allow-overuse is enabled."))}let _=W4(),Y=Sc("cdk.out"),y=await wm(()=>BT(PT()),{operationName:"loading construct metadata",fallbackValue:{}})??{},b={},K=!1,q=!1,te=0,X=new Set,ee=Object.keys(t),fe=ee.length,Re=Ce=>{let{stackName:G,map:xe}=Ce;for(let[ge,L]of Object.entries(xe))b[`${G}:${ge}`]=L};if(fe>1)await im.runAnalysis({title:`Deep Analysis of ${fe} CDK Stacks`,steps:ee.map((Ce,G)=>({title:`Analyzing stack ${G+1}/${fe}: ${Ce}`,task:async()=>{let xe=t[Ce],ge=await Y4({stackName:Ce,stack:xe,selectedServices:o,inlineFindings:e,recommendationMapPerStack:r,pathToLogicalId:s,constructRegistry:y,ruleFilter:a,ignoreRules:c,ignorePaths:u,acknowledgements:l[Ce]??[],authToken:d,fingerprint:p,output:n,withIssue:i,tier:m,noCache:g,warnSensitive:v,sensitiveDataDetection:x,cache:S,quotaValidation:w,manifest:Y,customRules:_,cdkContext:E,resourceIdMetadata:P,aiModelId:k,aiBatchSize:A,forceLocal:M,baselineExclude:z,collectFingerprints:C,skipRendering:U});Re({stackName:ge.stackName,map:ge.recommendationMap}),te+=ge.scannedResourceCount;for(let L of ge.scannedResourceIds)X.add(`${ge.stackName}:${L}`);return!K&&ge.hasIssues&&(K=K4(ge.recommendationMap)),ge.hasSensitiveData&&(q=!0),!U&&(n==="summary"||n==="table")&&T.summary(ge.summary),ge}})),showSummary:!0});else{let[Ce,G]=Object.entries(t)[0]??[];if(!Ce||!G)return{recommendationMaps:{},hasCriticalIssues:!1,scannedResourceIds:new Set};let xe=Object.entries(G.Resources||{}).filter(([,L])=>!L.Type.startsWith("AWS::CDK::")).length;T.analysisStart(Ce,xe);let ge=await Y4({stackName:Ce,stack:G,selectedServices:o,inlineFindings:e,recommendationMapPerStack:r,pathToLogicalId:s,constructRegistry:y,ruleFilter:a,ignoreRules:c,ignorePaths:u,acknowledgements:l[Ce]??[],authToken:d,fingerprint:p,output:n,withIssue:i,tier:m,noCache:g,warnSensitive:v,sensitiveDataDetection:x,cache:S,quotaValidation:w,manifest:Y,customRules:_,cdkContext:E,resourceIdMetadata:P,aiModelId:k,aiBatchSize:A,forceLocal:M,baselineExclude:z,collectFingerprints:C,skipRendering:U});Re({stackName:ge.stackName,map:ge.recommendationMap}),te+=ge.scannedResourceCount;for(let L of ge.scannedResourceIds)X.add(`${ge.stackName}:${L}`);ge.hasIssues&&(K=K4(ge.recommendationMap)),ge.hasSensitiveData&&(q=!0),!U&&(n==="summary"||n==="table")&&T.summary(ge.summary)}if(U)return{recommendationMaps:b,hasCriticalIssues:!1,hasSensitiveData:q,scannedResourceIds:X};if(Object.keys(b).length>0&&fe>1){let Ce=mm(b,te,X);if(n==="table"||n==="summary")T.section("Overall Analysis Summary","\u{1F4CA}"),T.summary(Ce),n==="table"&&(ul(b),T.section("Overall Analysis Summary (continued)","\u{1F4CA}"),T.summary(Ce));else if(n==="sarif"){let G=fm("consolidated",b),xe="consolidated_analysis_report.sarif";J4.writeFileSync(xe,JSON.stringify(G,null,2)),T.info(`\u{1F4C4} Consolidated SARIF report written to: ${xe}`)}else n==="github-actions"&&dm("consolidated",b,Ce.severityCounts,te)}else if(n==="table"||n==="summary")if(Object.keys(b).length>0){let Ce=mm(b,te,X);T.section("Overall Analysis Summary","\u{1F4CA}"),T.summary(Ce),n==="table"&&(ul(b),T.section("Overall Analysis Summary (continued)","\u{1F4CA}"),T.summary(Ce))}else T.success("No issues found across all stacks!");return{recommendationMaps:b,hasCriticalIssues:!!f&&K||q&&!v,hasSensitiveData:q,scannedResourceIds:X}}});var Em,NS,Q4=D(()=>{"use strict";Em={staticAnalysis:!0,basicServiceChecks:!0,localAnalysis:!0,jsonOutput:!0,tableOutput:!0,aiRecommendations:!1,githubIntegration:!1,teamCollaboration:!1,advancedOutputFormats:!1,customRules:!1,prioritySupport:!1,ciCdIntegration:!1},NS={staticAnalysis:!0,basicServiceChecks:!0,localAnalysis:!0,jsonOutput:!0,tableOutput:!0,aiRecommendations:!0,githubIntegration:!0,teamCollaboration:!0,advancedOutputFormats:!0,customRules:!0,prioritySupport:!0,ciCdIntegration:!0}});var hl,bX,SX,Rm,X4=D(()=>{"use strict";Q4();lt();hl=new Map,bX=new Set(["free","pro","enterprise","trial"]),SX=t=>{try{let e=t.split(".");if(e.length!==3)return;let s=JSON.parse(Buffer.from(e[1],"base64").toString());return s.tier&&bX.has(s.tier)?s.tier:void 0}catch{return}},Rm=async(t,e)=>{if(!t)return{isValid:!0,tier:"free",features:Em};if(hl.has(t)){let s=hl.get(t);if(s.expiresAt&&s.expiresAt>new Date)return s;hl.delete(t)}if(e){yp.info("\u2705 License validated via JWT token from login");let n=SX(e)??"free",r=n==="pro"||n==="trial"||n==="enterprise"?NS:Em,i={isValid:!0,tier:n,expiresAt:new Date(Date.now()+3600*1e3),features:r};return hl.set(t,i),i}if(process.env.NODE_ENV==="development"&&process.env.CDK_INSIGHTS_DEV_MODE==="true"){yp.warn("\u26A0\uFE0F Development mode enabled - Pro features available for testing only");let s={isValid:!0,tier:"pro",expiresAt:new Date(Date.now()+24*60*60*1e3),features:NS};return hl.set(t,s),s}return yp.warn("\u26A0\uFE0F License key provided but no valid authentication token"),{isValid:!1,tier:"free",features:Em}}});var eM,tM=D(()=>{"use strict";$b();lt();eM=async t=>{let s={requestId:`enhanced-quota-${Date.now()}`,functionName:"validateEnhancedLicenseQuota"};re.info("\u{1F50D} Starting enhanced license quota validation",s,{requestedResources:t.requestedResources,hasLicenseKey:!!t.licenseKey,hasUsageData:!!t.usageData});try{if(t.licenseInfo||t.usageData){let l=0;t.licenseInfo&&t.licenseInfo.currentPeriodUsage!==void 0&&t.licenseInfo.currentPeriodUsage!==null?(l=Number(t.licenseInfo.currentPeriodUsage),re.info("\u{1F4CA} Using currentPeriodUsage from license (per-cycle source of truth)",s,{currentPeriodUsage:l})):t.usageData&&t.usageData.totalResourcesAnalyzed>0&&(l=t.usageData.totalResourcesAnalyzed,re.info("\u{1F4CA} Using usage data from login (fallback \u2014 no currentPeriodUsage in license info)",s,{totalResourcesAnalyzed:t.usageData.totalResourcesAnalyzed,totalTokens:t.usageData.totalTokens,usageCount:t.usageData.usageCount}));let d=200,p=!0,f=!1;if(t.licenseInfo){let k=t.licenseInfo.licenseType||t.licenseInfo.tier;if(t.licenseInfo.status==="TRIAL"||t.licenseInfo.tier==="trial"){p=!0,d=t.licenseInfo.trialUsageLimit||t.licenseInfo.maxUsage||200;let A=t.licenseInfo.trialEnd||t.licenseInfo.expiresAt;A&&(f=Math.floor(Date.now()/1e3)>A)}else p=!1,k==="ENTERPRISE"?d=el.DEFAULT_TEAM_AI_INSIGHTS_PER_SEAT*10:k==="TEAM"?d=el.DEFAULT_TEAM_AI_INSIGHTS_PER_SEAT:k==="FREE"?d=Number(t.licenseInfo.maxUsage)||el.DEFAULT_FREE_AI_INSIGHTS:d=el.DEFAULT_PRO_AI_INSIGHTS}let m=Math.max(0,d-l),g=l+t.requestedResources>d,h=Math.floor(d*.8),v=Math.floor(d*.9),x=!0,S=!0,w=!0,E,P;if(f)x=!1,S=!1,w=!1,E="Trial license has expired",P="https://cdkinsights.dev/pricing";else if(g&&p){x=!1,S=!0,w=!1;let k=t.allowOveruse?" Note: --allow-overuse does not apply to trial licenses which have a hard usage limit.":"";E=`AI analysis would exceed your Free account allowance. You have used ${l}/${d} AI credits and are requesting ${t.requestedResources} more.${k}`,P="https://cdkinsights.dev/pricing"}else g&&!p?t.allowOveruse?(x=!0,S=!0,w=!0,E=`You have used ${l}/${d} AI credits this billing period. Proceeding with AI analysis as --allow-overuse is enabled.`):(x=!0,S=!0,w=!1,E=`AI analysis would exceed your monthly AI credit allowance (${l}/${d} used). AI is paused until your next billing cycle \u2014 static scans continue to work. Use --allow-overuse to proceed anyway.`):p&&l>=v&&t.requestedResources>10&&(x=!1,S=!0,w=!1,E=`Large AI analysis requests are blocked when approaching your Free account allowance. You have used ${l}/${d} AI credits.`,P="https://cdkinsights.dev/pricing");return p&&l>=h&&l<d&&re.info("Trial usage approaching limit - will be displayed in enhanced UI",s,{currentResources:l,maxResources:d,warningThreshold:h}),re.info("\u2705 Enhanced license quota validation completed successfully",s,{canProceed:x,canRunStaticAnalysis:S,canRunAIAnalysis:w,currentResources:l,maxResources:d,remainingResources:m,isTrial:p,trialExpired:f}),{canProceed:x,canRunStaticAnalysis:S,canRunAIAnalysis:w,quota:{currentResourcesAnalyzed:l,maxResources:d,remainingResources:m,isTrial:p,trialExpired:f,wouldExceed:g,warningThreshold:h,hardStopThreshold:v,currentTokens:t.usageData?t.usageData.totalTokens:t.licenseInfo?Number(t.licenseInfo.totalResourcesAnalyzed||0):0,maxTokens:1e6,remainingTokens:t.usageData?Math.max(0,1e6-t.usageData.totalTokens):1e6},reason:E,upgradePath:P,usageData:t.usageData}}re.warn("\u274C No usage data available, using fallback validation",s);let n;if(t.licenseInfo){let l=Number(t.licenseInfo.currentPeriodUsage||0),d=Number(t.licenseInfo.totalResourcesAnalyzed||0),p=d>0?d:l;p>0&&(n={totalTokens:p,totalResourcesAnalyzed:p,totalCost:0,usageCount:1,successfulUsageCount:1,failedUsageCount:0,firstUsageAt:Number(t.licenseInfo.createdAt),lastUsageAt:Number(t.licenseInfo.lastUsageAt||t.licenseInfo.updatedAt)},re.info("\u{1F4CA} Using usage data from license info",s,{totalResourcesAnalyzed:n.totalResourcesAnalyzed,totalTokens:n.totalTokens}))}let r=200,i=!0,o=!1;if(t.licenseInfo){let l=t.licenseInfo.licenseType||t.licenseInfo.tier;if(t.licenseInfo.status==="TRIAL"||t.licenseInfo.tier==="trial"){i=!0,r=t.licenseInfo.maxUsage?Number(t.licenseInfo.maxUsage):200;let d=t.licenseInfo.trialEnd||t.licenseInfo.expiresAt;d&&(o=Math.floor(Date.now()/1e3)>d)}else i=!1,l==="ENTERPRISE"?r=1e5:r=1e4}let a=n?n.totalResourcesAnalyzed:0,c=Math.max(0,r-a),u=a+t.requestedResources>r;return{canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!0,quota:{currentResourcesAnalyzed:a,maxResources:r,remainingResources:c,isTrial:i,trialExpired:o,wouldExceed:u,warningThreshold:Math.floor(r*.8),hardStopThreshold:Math.floor(r*.9),currentTokens:n?n.totalTokens:0,maxTokens:1e6,remainingTokens:1e6},reason:n?"Using usage data from license info":"No usage data available - proceeding with analysis",usageData:n||void 0}}catch(n){return re.error("Enhanced license quota validation failed",s,n instanceof Error?n:new Error(String(n))),{canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,quota:{currentResourcesAnalyzed:0,maxResources:t.licenseInfo&&t.licenseInfo.maxUsage||200,remainingResources:t.licenseInfo&&t.licenseInfo.maxUsage||200,isTrial:t.licenseInfo?t.licenseInfo.status==="TRIAL"||t.licenseInfo.tier==="trial":!0,trialExpired:!1,wouldExceed:!1,warningThreshold:Math.floor((t.licenseInfo&&t.licenseInfo.maxUsage||200)*.8),hardStopThreshold:Math.floor((t.licenseInfo&&t.licenseInfo.maxUsage||200)*.9),currentTokens:0,maxTokens:1e6,remainingTokens:1e6},reason:"Enhanced quota validation failed - proceeding with analysis"}}}});var $S,WS,sM,vX,CX,DX,nM,rM=D(()=>{"use strict";Cm();$S=()=>({CRITICAL:0,HIGH:0,MEDIUM:0,LOW:0}),WS=()=>({"Operational Excellence":0,Security:0,"Cost Optimization":0,Reliability:0,"Performance Efficiency":0,Sustainability:0}),sM=t=>{let e=t.indexOf(":");return e===-1?{stackName:"",resourceId:t}:{stackName:t.slice(0,e),resourceId:t.slice(e+1)}},vX=t=>({issue:t.issue,recommendation:t.recommendation,severity:t.severity,wafPillar:t.wafPillar||"Security",foundBy:t.foundBy||"cdkInsights",ruleId:t.ruleId,codeSnippet:t.codeSnippet,constructPath:t.constructPath,constructType:t.constructType,sourceLocation:t.sourceLocation?{filePath:t.sourceLocation.filePath,line:t.sourceLocation.line,column:t.sourceLocation.column,confidence:t.sourceLocation.confidence}:void 0,aiConfidence:t.aiConfidence}),CX=(t,e)=>({resourceId:t.resourceId,logicalId:t.logicalId,cdkPath:t.cdkPath,friendlyName:t.friendlyName,resourceName:t.resourceName,constructType:t.constructType,serviceCategory:t.serviceCategory,tags:t.tags,sourceLocation:t.sourceLocation?{filePath:t.sourceLocation.filePath,line:t.sourceLocation.line,column:t.sourceLocation.column,confidence:t.sourceLocation.confidence??"medium"}:void 0,findings:e.map(vX)}),DX=(t,e,s)=>{e[t.severity]=(e[t.severity]??0)+1,s[t.wafPillar]=(s[t.wafPillar]??0)+1},nM=t=>{let e=new Map;for(let u of t.scannedResourceIds){let{stackName:l,resourceId:d}=sM(u);if(!l)continue;let p=e.get(l);p||(p={stackName:l,totalResources:0,scannedResourceIds:[],severityCounts:$S(),wafPillarCounts:WS(),resources:[]},e.set(l,p)),p.scannedResourceIds.push(d),p.totalResources+=1}for(let[u,l]of Object.entries(t.recommendationMaps)){let{stackName:d}=sM(u);if(!d)continue;let p=e.get(d);p||(p={stackName:d,totalResources:0,scannedResourceIds:[],severityCounts:$S(),wafPillarCounts:WS(),resources:[]},e.set(d,p));let f=[...l.sources?.cdkInsights?.issues??[],...l.sources?.cdkNag?.issues??[]];if(f.length===0)continue;let m=CX(l,f);p.resources.push(m);for(let g of m.findings)DX(g,p.severityCounts,p.wafPillarCounts)}let s=[],n=$S(),r=WS(),i=0,o=0,a=0;for(let u of e.values()){s.push(u),i+=u.totalResources,a+=u.resources.length;for(let l of Object.keys(u.severityCounts))n[l]=(n[l]??0)+u.severityCounts[l],o+=u.severityCounts[l];for(let l of Object.keys(u.wafPillarCounts))r[l]=(r[l]??0)+u.wafPillarCounts[l]}let c={totalResources:i,totalFindings:o,resourcesWithFindings:a,severityCounts:n,wafPillarCounts:r};return{schemaVersion:ml,scanId:t.scanId,cliVersion:t.cliVersion,scanStartedAt:t.scanStartedAt.toISOString(),scanCompletedAt:t.scanCompletedAt.toISOString(),aiAnalysis:t.aiAnalysis,stacks:s,totals:c}}});var _m,wX,AX,EX,Im,iM,oM,aM=D(()=>{"use strict";_m=require("node:crypto");Jn();Cm();qa();lt();({version:wX}=ll()),AX=1e4,EX=t=>(0,_m.createHash)("sha256").update(t).digest("hex").slice(0,32),Im=t=>({skipped:!0,reason:t}),iM=async t=>{if(!t.enabled)return Im("disabled");if(!t.licenseKey)return Im("no-license-key");if(!t.authToken)return Im("no-auth-token");let e=Wn();if(!e)return Im("no-api-base");let s={schemaVersion:ml,scanId:t.report.scanId,hashedLicenseId:EX(t.licenseKey),tier:t.tier??"free",cliVersion:wX,platform:process.platform,scanStartedAt:t.report.scanStartedAt,scanCompletedAt:t.report.scanCompletedAt,report:t.report};try{let n=await Rt.post(`${e}/v1/scans`,s,{timeout:AX,headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.authToken}`,"x-cdk-insights-client":"cli"},validateStatus:r=>r>=200&&r<300});return{skipped:!1,success:!0,scanId:n.data.scanId??s.scanId,viewUrl:n.data.viewUrl,retentionDays:n.data.retentionDays}}catch(n){let r=n;if(r.code==="ECONNABORTED"||r.code==="ETIMEDOUT")return{skipped:!1,success:!1,reason:"timeout"};if(!r.response)return{skipped:!1,success:!1,reason:"network"};let i=r.response.status,o=r.response.data?.message;return i>=400&&i<500?{skipped:!1,success:!1,reason:"rejected",serverMessage:o}:{skipped:!1,success:!1,reason:"server-error",serverMessage:o}}},oM=()=>(0,_m.randomUUID)()});var cM,RX,IX,_X,gl,jS,US=D(()=>{"use strict";cM=require("node:crypto");Jn();qa();lt();({version:RX}=ll()),IX=1500,_X=t=>(0,cM.createHash)("sha256").update(t).digest("hex").slice(0,32),gl=async({enabled:t,licenseKey:e,authToken:s,tier:n,event:r})=>{if(!t||!e)return;let i=Wn();if(!i)return;let o={hashedLicenseId:_X(e),tier:n??"free",cliVersion:RX,platform:process.platform,emittedAt:new Date().toISOString(),event:r};try{await Rt.post(`${i}/v1/telemetry/events`,o,{timeout:IX,headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{},"x-cdk-insights-client":"cli"}})}catch{}},jS=t=>{let e={CRITICAL:0,HIGH:0,MEDIUM:0,LOW:0};for(let s of t){let n=(s.severity??"").toUpperCase();(n==="CRITICAL"||n==="HIGH"||n==="MEDIUM"||n==="LOW")&&(e[n]+=1)}return e}});var uM,yl,lM,kX,FX,dM,pM=D(()=>{"use strict";uM={free:0,trial:0,pro:1,team:2},yl={"nova-lite":{alias:"nova-lite",bedrockModelId:"amazon.nova-lite-v1:0",displayName:"Amazon Nova Lite",minTier:"free",quotaMultiplier:.5,description:"Fastest and cheapest option, good for simple checks"},"mistral-14b":{alias:"mistral-14b",bedrockModelId:"mistral.ministral-3-14b-instruct",displayName:"Mistral Ministral 14B",minTier:"pro",quotaMultiplier:1,description:"Balanced quality and cost \u2014 current default for Pro"},"llama-3-3-70b":{alias:"llama-3-3-70b",bedrockModelId:"us.meta.llama3-3-70b-instruct-v1:0",displayName:"Llama 3.3 70B",minTier:"pro",quotaMultiplier:2,description:"Stronger reasoning + code understanding than Mistral 14B"},"haiku-4-5":{alias:"haiku-4-5",bedrockModelId:"us.anthropic.claude-haiku-4-5-20251001-v1:0",displayName:"Claude Haiku 4.5",minTier:"pro",quotaMultiplier:4,description:"High-quality findings for security-critical infra"},"sonnet-4-6":{alias:"sonnet-4-6",bedrockModelId:"us.anthropic.claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",minTier:"pro",quotaMultiplier:16,description:"Top-tier reasoning for complex architectures"}},lM={free:"nova-lite",trial:"nova-lite",pro:"mistral-14b",team:"mistral-14b"},kX=t=>typeof t=="string"&&t in yl,FX=(t,e)=>{if(!e)return!0;let s=yl[t].minTier;return uM[e]>=uM[s]},dM=t=>{let{flag:e,cdkContext:s,userConfig:n,tier:r}=t,i=[{value:e,source:"flag"},{value:s,source:"cdkContext"},{value:n,source:"userConfig"}];for(let{value:a,source:c}of i){if(!a||!kX(a))continue;if(FX(a,r))return{alias:a,bedrockModelId:yl[a].bedrockModelId,source:c,downgradedFromTierGate:!1};let u=r?lM[r]:"mistral-14b";return{alias:u,bedrockModelId:yl[u].bedrockModelId,source:"tierDefault",downgradedFromTierGate:!0,requestedAlias:a}}let o=r?lM[r]:"mistral-14b";return{alias:o,bedrockModelId:yl[o].bedrockModelId,source:"tierDefault",downgradedFromTierGate:!1}}});var zt,TX,fM,PX,LX,xl,mM,hM=D(()=>{"use strict";za();zt={stackName:"",services:[],redact:!1,summaryOnly:!1,synth:!1,ruleFilter:[],failOnCritical:!0,ci:!1,all:!1,yes:!1,reset:!1,github:!1,noCache:!1,allowOveruse:!1,cache:{enabled:!0,ttl:6*60*60*1e3,maxSize:1e3}},TX=t=>["json","table","markdown","summary","sarif","github-actions"].includes(t)?t:(console.warn(`\u26A0\uFE0F Invalid output format "${t}", defaulting to "table"`),"table"),fM=t=>Array.isArray(t)?t.filter(e=>typeof e=="string"):typeof t=="string"?t.split(",").map(e=>e.trim()).filter(Boolean):[],PX=t=>fM(t).map(s=>s.trim()).filter(Boolean).map(s=>s.toLowerCase()==="all"?"All services":s).filter(s=>Ga(s)),LX=t=>{if(!t||typeof t!="object"||Array.isArray(t))return zt.cache;let e=t,s={enabled:zt.cache.enabled,ttl:zt.cache.ttl,maxSize:zt.cache.maxSize};return typeof e.enabled=="boolean"&&(s.enabled=e.enabled),typeof e.ttl=="number"&&e.ttl>0?s.ttl=e.ttl:e.ttl&&console.warn(`\u26A0\uFE0F Invalid cache TTL "${e.ttl}", using default ${zt.cache.ttl}ms`),typeof e.maxSize=="number"&&e.maxSize>0?s.maxSize=e.maxSize:e.maxSize&&console.warn(`\u26A0\uFE0F Invalid cache maxSize "${e.maxSize}", using default ${zt.cache.maxSize}`),s},xl=(t,e)=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let s=t.toLowerCase();if(s==="true"||s==="1"||s==="yes")return!0;if(s==="false"||s==="0"||s==="no")return!1}return e},mM=(t,e)=>{let s=e.output||e.format||t.output,n=s?TX(s):void 0,r=e.withIssue??t.withIssue;return n!=="markdown"&&r&&(console.warn("\u26A0\uFE0F GitHub issues are only supported with markdown output. Disabling withIssue."),r=!1),{stackName:e.stackName??t.stackName??zt.stackName,output:n,format:n,services:PX(e.services??t.services??zt.services),withIssue:r,redact:xl(e.redact??t.redact,zt.redact),summaryOnly:xl(e.summaryOnly??t.summaryOnly,zt.summaryOnly),synth:xl(e.synth??t.synth,zt.synth),ruleFilter:fM(e.ruleFilter??t.ruleFilter??zt.ruleFilter),ignoreRules:t.ignoreRules??[],ignorePaths:t.ignorePaths??[],failOnCritical:xl(e.failOnCritical??t.failOnCritical,zt.failOnCritical),ci:e.ci??zt.ci,all:e.all??zt.all,yes:e.yes??zt.yes,reset:e.reset??zt.reset,github:e.github??zt.github,noCache:e.noCache??zt.noCache,allowOveruse:xl(e.allowOveruse??t.allowOveruse,zt.allowOveruse),cache:LX(e.cache??t.cache??zt.cache),local:e.local??!1,prComment:e.prComment??!1,warnSensitive:e.warnSensitive??!1,diff:e.diff??!1,writeBaseline:e.writeBaseline??!1,baseline:e.baseline,watch:e.watch??!1,ai:t.ai}}});function Sl(t){if(!t||typeof t!="object"||Array.isArray(t))return t;let e={};for(let[s,n]of Object.entries(t))BX.has(s)||(n&&typeof n=="object"&&!Array.isArray(n)?e[s]=Sl(n):Array.isArray(n)?e[s]=n.map(r=>r&&typeof r=="object"&&!Array.isArray(r)?Sl(r):r):e[s]=n);return e}var Ur,gM,bl,OX,MX,BX,yM,Yo,xM,qn,vl,km,Cl=D(()=>{"use strict";Ur=oe(require("node:fs")),gM=oe(require("node:path"));za();lt();bl=gM.join(process.cwd(),".cdk-insights.json"),OX=/^[a-zA-Z0-9_-]+$/,MX=/^[a-zA-Z0-9_. -]+$/,BX=new Set(["__proto__","constructor","prototype"]);yM={enabled:!0,warnOnly:!1,allowPatterns:[],ignoreProperties:[],strictMode:!1},Yo={services:[],redact:!1,summaryOnly:!1,synth:!1,ruleFilter:[],feedback:!0,failOnCritical:!0,noCache:!1,allowOveruse:!1,sensitiveDataDetection:yM,cache:{enabled:!0,ttl:6*60*60*1e3,maxSize:1e3}},xM=t=>{if(!t||typeof t!="object"||Array.isArray(t))return re.warn("\u274C Invalid configuration format, using defaults"),Yo;let e={...Yo},s=t;if(typeof s.stackName=="string"&&s.stackName.length>0&&(OX.test(s.stackName)?e.stackName=s.stackName:re.warn(`\u26A0\uFE0F Ignoring unsafe stackName "${s.stackName}" \u2014 only alphanumeric, hyphens, and underscores are allowed`)),typeof s.output=="string"&&["json","table","markdown","summary","sarif","github-actions"].includes(s.output)?e.output=s.output:s.output&&re.warn(`\u26A0\uFE0F Invalid output format "${s.output}", skipping output setting`),Array.isArray(s.services)&&(e.services=s.services.filter(n=>typeof n=="string").map(n=>n.toLowerCase()==="all"?"All services":n).filter(n=>Ga(n))),typeof s.withIssue=="boolean"&&(e.withIssue=s.withIssue),typeof s.redact=="boolean"&&(e.redact=s.redact),typeof s.summaryOnly=="boolean"&&(e.summaryOnly=s.summaryOnly),typeof s.synth=="boolean"&&(e.synth=s.synth),Array.isArray(s.ruleFilter)&&(e.ruleFilter=s.ruleFilter.filter(n=>typeof n=="string"&&n.length>0&&n.length<=100&&MX.test(n))),typeof s.feedback=="boolean"&&(e.feedback=s.feedback),typeof s.failOnCritical=="boolean"&&(e.failOnCritical=s.failOnCritical),typeof s.noCache=="boolean"&&(e.noCache=s.noCache),typeof s.allowOveruse=="boolean"&&(e.allowOveruse=s.allowOveruse),s.ai&&typeof s.ai=="object"&&!Array.isArray(s.ai)){let n=s.ai,r={};typeof n.model=="string"&&n.model.length>0&&(r.model=n.model),typeof n.batchSize=="number"&&Number.isFinite(n.batchSize)&&n.batchSize>0?r.batchSize=Math.floor(n.batchSize):n.batchSize!==void 0&&re.warn(`\u26A0\uFE0F Ignoring invalid ai.batchSize "${n.batchSize}" \u2014 must be a positive number.`),(r.model||r.batchSize!==void 0)&&(e.ai=r)}if(s.telemetry&&typeof s.telemetry=="object"&&!Array.isArray(s.telemetry)){let n=s.telemetry;typeof n.enabled=="boolean"&&(e.telemetry={enabled:n.enabled})}if(s.scanHistory&&typeof s.scanHistory=="object"&&!Array.isArray(s.scanHistory)){let n=s.scanHistory;typeof n.enabled=="boolean"&&(e.scanHistory={enabled:n.enabled})}if(s.cache&&typeof s.cache=="object"&&!Array.isArray(s.cache)){let n=s.cache;e.cache={...Yo.cache},typeof n.enabled=="boolean"&&(e.cache.enabled=n.enabled),typeof n.ttl=="number"&&n.ttl>0?e.cache.ttl=n.ttl:n.ttl&&re.warn(`\u26A0\uFE0F Invalid cache TTL "${n.ttl}", using default ${Yo.cache?.ttl}ms`),typeof n.maxSize=="number"&&n.maxSize>0?e.cache.maxSize=n.maxSize:n.maxSize&&re.warn(`\u26A0\uFE0F Invalid cache maxSize "${n.maxSize}", using default ${Yo.cache?.maxSize}`)}if(s.sensitiveDataDetection&&typeof s.sensitiveDataDetection=="object"&&!Array.isArray(s.sensitiveDataDetection)){let n=s.sensitiveDataDetection;e.sensitiveDataDetection={...yM},typeof n.enabled=="boolean"&&(e.sensitiveDataDetection.enabled=n.enabled),typeof n.warnOnly=="boolean"&&(e.sensitiveDataDetection.warnOnly=n.warnOnly),typeof n.strictMode=="boolean"&&(e.sensitiveDataDetection.strictMode=n.strictMode),Array.isArray(n.allowPatterns)&&(e.sensitiveDataDetection.allowPatterns=n.allowPatterns.filter(r=>typeof r=="string")),Array.isArray(n.ignoreProperties)&&(e.sensitiveDataDetection.ignoreProperties=n.ignoreProperties.filter(r=>typeof r=="string"))}return Array.isArray(s.ignoreRules)&&(e.ignoreRules=s.ignoreRules.filter(n=>typeof n=="string"&&n.length>0)),Array.isArray(s.ignorePaths)&&(e.ignorePaths=s.ignorePaths.filter(n=>typeof n=="string"&&n.length>0)),e},qn=()=>{if(!Ur.existsSync(bl))return Yo;try{let t=Ur.readFileSync(bl,"utf-8"),e=Sl(JSON.parse(t));return xM(e)}catch(t){let e=t;return re.error(`\u274C Error loading configuration: ${e.message}`),re.info("\u{1F4DD} Using default configuration"),Yo}},vl=t=>{try{let e=xM(t);Ur.writeFileSync(bl,JSON.stringify(e,null,2),"utf-8"),re.info("\u{1F4BE} Configuration saved successfully")}catch(e){let s=e;re.error(`\u274C Error saving configuration: ${s.message}`)}},km=()=>{try{Ur.existsSync(bl)&&(Ur.unlinkSync(bl),re.info("\u{1F5D1}\uFE0F Configuration file removed"))}catch(t){let e=t;re.error(`\u274C Error removing configuration: ${e.message}`)}}});var Dl=O((B1e,DM)=>{"use strict";var NX=require("path"),dr="\\\\/",bM=`[^${dr}]`,$X=0,Hr="\\.",WX="\\+",jX="\\?",Fm="\\/",UX="(?=.)",SM="[^/]",HS=`(?:${Fm}|$)`,vM=`(?:^|${Fm})`,GS=`${Hr}{1,2}${HS}`,HX=`(?!${Hr})`,GX=`(?!${vM}${GS})`,zX=`(?!${Hr}{0,1}${HS})`,qX=`(?!${GS})`,VX=`[^.${Fm}]`,KX=`${SM}*?`,CM={DOT_LITERAL:Hr,PLUS_LITERAL:WX,QMARK_LITERAL:jX,SLASH_LITERAL:Fm,ONE_CHAR:UX,QMARK:SM,END_ANCHOR:HS,DOTS_SLASH:GS,NO_DOT:HX,NO_DOTS:GX,NO_DOT_SLASH:zX,NO_DOTS_SLASH:qX,QMARK_NO_DOT:VX,STAR:KX,START_ANCHOR:vM},ZX={...CM,SLASH_LITERAL:`[${dr}]`,QMARK:bM,STAR:`${bM}*?`,DOTS_SLASH:`${Hr}{1,2}(?:[${dr}]|$)`,NO_DOT:`(?!${Hr})`,NO_DOTS:`(?!(?:^|[${dr}])${Hr}{1,2}(?:[${dr}]|$))`,NO_DOT_SLASH:`(?!${Hr}{0,1}(?:[${dr}]|$))`,NO_DOTS_SLASH:`(?!${Hr}{1,2}(?:[${dr}]|$))`,QMARK_NO_DOT:`[^.${dr}]`,START_ANCHOR:`(?:^|[${dr}])`,END_ANCHOR:`(?:[${dr}]|$)`},YX={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};DM.exports={DEFAULT_MAX_EXTGLOB_RECURSION:$X,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:YX,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:NX.sep,extglobChars(t){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===!0?ZX:CM}}});var Tm=O(Ms=>{"use strict";var JX=require("path"),QX=process.platform==="win32",{REGEX_BACKSLASH:XX,REGEX_REMOVE_BACKSLASH:eee,REGEX_SPECIAL_CHARS:tee,REGEX_SPECIAL_CHARS_GLOBAL:see}=Dl();Ms.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);Ms.hasRegexChars=t=>tee.test(t);Ms.isRegexChar=t=>t.length===1&&Ms.hasRegexChars(t);Ms.escapeRegex=t=>t.replace(see,"\\$1");Ms.toPosixSlashes=t=>t.replace(XX,"/");Ms.removeBackslashes=t=>t.replace(eee,e=>e==="\\"?"":e);Ms.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};Ms.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:QX===!0||JX.sep==="\\";Ms.escapeLast=(t,e,s)=>{let n=t.lastIndexOf(e,s);return n===-1?t:t[n-1]==="\\"?Ms.escapeLast(t,e,n-1):`${t.slice(0,n)}\\${t.slice(n)}`};Ms.removePrefix=(t,e={})=>{let s=t;return s.startsWith("./")&&(s=s.slice(2),e.prefix="./"),s};Ms.wrapOutput=(t,e={},s={})=>{let n=s.contains?"":"^",r=s.contains?"":"$",i=`${n}(?:${t})${r}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var FM=O(($1e,kM)=>{"use strict";var wM=Tm(),{CHAR_ASTERISK:zS,CHAR_AT:nee,CHAR_BACKWARD_SLASH:wl,CHAR_COMMA:ree,CHAR_DOT:qS,CHAR_EXCLAMATION_MARK:VS,CHAR_FORWARD_SLASH:_M,CHAR_LEFT_CURLY_BRACE:KS,CHAR_LEFT_PARENTHESES:ZS,CHAR_LEFT_SQUARE_BRACKET:iee,CHAR_PLUS:oee,CHAR_QUESTION_MARK:AM,CHAR_RIGHT_CURLY_BRACE:aee,CHAR_RIGHT_PARENTHESES:EM,CHAR_RIGHT_SQUARE_BRACKET:cee}=Dl(),RM=t=>t===_M||t===wl,IM=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},uee=(t,e)=>{let s=e||{},n=t.length-1,r=s.parts===!0||s.scanToEnd===!0,i=[],o=[],a=[],c=t,u=-1,l=0,d=0,p=!1,f=!1,m=!1,g=!1,h=!1,v=!1,x=!1,S=!1,w=!1,E=!1,P=0,k,A,M={value:"",depth:0,isGlob:!1},z=()=>u>=n,C=()=>c.charCodeAt(u+1),U=()=>(k=A,c.charCodeAt(++u));for(;u<n;){A=U();let K;if(A===wl){x=M.backslashes=!0,A=U(),A===KS&&(v=!0);continue}if(v===!0||A===KS){for(P++;z()!==!0&&(A=U());){if(A===wl){x=M.backslashes=!0,U();continue}if(A===KS){P++;continue}if(v!==!0&&A===qS&&(A=U())===qS){if(p=M.isBrace=!0,m=M.isGlob=!0,E=!0,r===!0)continue;break}if(v!==!0&&A===ree){if(p=M.isBrace=!0,m=M.isGlob=!0,E=!0,r===!0)continue;break}if(A===aee&&(P--,P===0)){v=!1,p=M.isBrace=!0,E=!0;break}}if(r===!0)continue;break}if(A===_M){if(i.push(u),o.push(M),M={value:"",depth:0,isGlob:!1},E===!0)continue;if(k===qS&&u===l+1){l+=2;continue}d=u+1;continue}if(s.noext!==!0&&(A===oee||A===nee||A===zS||A===AM||A===VS)===!0&&C()===ZS){if(m=M.isGlob=!0,g=M.isExtglob=!0,E=!0,A===VS&&u===l&&(w=!0),r===!0){for(;z()!==!0&&(A=U());){if(A===wl){x=M.backslashes=!0,A=U();continue}if(A===EM){m=M.isGlob=!0,E=!0;break}}continue}break}if(A===zS){if(k===zS&&(h=M.isGlobstar=!0),m=M.isGlob=!0,E=!0,r===!0)continue;break}if(A===AM){if(m=M.isGlob=!0,E=!0,r===!0)continue;break}if(A===iee){for(;z()!==!0&&(K=U());){if(K===wl){x=M.backslashes=!0,U();continue}if(K===cee){f=M.isBracket=!0,m=M.isGlob=!0,E=!0;break}}if(r===!0)continue;break}if(s.nonegate!==!0&&A===VS&&u===l){S=M.negated=!0,l++;continue}if(s.noparen!==!0&&A===ZS){if(m=M.isGlob=!0,r===!0){for(;z()!==!0&&(A=U());){if(A===ZS){x=M.backslashes=!0,A=U();continue}if(A===EM){E=!0;break}}continue}break}if(m===!0){if(E=!0,r===!0)continue;break}}s.noext===!0&&(g=!1,m=!1);let _=c,Y="",y="";l>0&&(Y=c.slice(0,l),c=c.slice(l),d-=l),_&&m===!0&&d>0?(_=c.slice(0,d),y=c.slice(d)):m===!0?(_="",y=c):_=c,_&&_!==""&&_!=="/"&&_!==c&&RM(_.charCodeAt(_.length-1))&&(_=_.slice(0,-1)),s.unescape===!0&&(y&&(y=wM.removeBackslashes(y)),_&&x===!0&&(_=wM.removeBackslashes(_)));let b={prefix:Y,input:t,start:l,base:_,glob:y,isBrace:p,isBracket:f,isGlob:m,isExtglob:g,isGlobstar:h,negated:S,negatedExtglob:w};if(s.tokens===!0&&(b.maxDepth=0,RM(A)||o.push(M),b.tokens=o),s.parts===!0||s.tokens===!0){let K;for(let q=0;q<i.length;q++){let te=K?K+1:l,X=i[q],ee=t.slice(te,X);s.tokens&&(q===0&&l!==0?(o[q].isPrefix=!0,o[q].value=Y):o[q].value=ee,IM(o[q]),b.maxDepth+=o[q].depth),(q!==0||ee!=="")&&a.push(ee),K=X}if(K&&K+1<t.length){let q=t.slice(K+1);a.push(q),s.tokens&&(o[o.length-1].value=q,IM(o[o.length-1]),b.maxDepth+=o[o.length-1].depth)}b.slashes=i,b.parts=a}return b};kM.exports=uee});var MM=O((W1e,OM)=>{"use strict";var Al=Dl(),bs=Tm(),{MAX_LENGTH:Pm,POSIX_REGEX_SOURCE:lee,REGEX_NON_SPECIAL_CHARS:dee,REGEX_SPECIAL_CHARS_BACKREF:pee,REPLACEMENTS:TM}=Al,fee=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let s=`[${t.join("-")}]`;try{new RegExp(s)}catch{return t.map(r=>bs.escapeRegex(r)).join("..")}return s},Ec=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,PM=t=>{let e=[],s=0,n=0,r=0,i="",o=!1;for(let a of t){if(o===!0){i+=a,o=!1;continue}if(a==="\\"){i+=a,o=!0;continue}if(a==='"'){r=r===1?0:1,i+=a;continue}if(r===0){if(a==="[")s++;else if(a==="]"&&s>0)s--;else if(s===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){e.push(i),i="";continue}}}i+=a}return e.push(i),e},mee=t=>{let e=!1;for(let s of t){if(e===!0){e=!1;continue}if(s==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(s))return!1}return!0},LM=t=>{let e=t.trim(),s=!0;for(;s===!0;)s=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),s=!0);if(mee(e))return e.replace(/\\(.)/g,"$1")},hee=t=>{let e=t.map(LM).filter(Boolean);for(let s=0;s<e.length;s++)for(let n=s+1;n<e.length;n++){let r=e[s],i=e[n],o=r[0];if(!(!o||r!==o.repeat(r.length)||i!==o.repeat(i.length))&&(r===i||r.startsWith(i)||i.startsWith(r)))return!0}return!1},YS=(t,e=!0)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let s=0,n=0,r=0,i=!1;for(let o=1;o<t.length;o++){let a=t[o];if(i===!0){i=!1;continue}if(a==="\\"){i=!0;continue}if(a==='"'){r=r===1?0:1;continue}if(r!==1){if(a==="["){s++;continue}if(a==="]"&&s>0){s--;continue}if(!(s>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return e===!0&&o!==t.length-1?void 0:{type:t[0],body:t.slice(2,o),end:o}}}}},gee=t=>{let e=0,s=[];for(;e<t.length;){let r=YS(t.slice(e),!1);if(!r||r.type!=="*")return;let i=PM(r.body).map(a=>a.trim());if(i.length!==1)return;let o=LM(i[0]);if(!o||o.length!==1)return;s.push(o),e+=r.end+1}return s.length<1?void 0:`${s.length===1?bs.escapeRegex(s[0]):`[${s.map(r=>bs.escapeRegex(r)).join("")}]`}*`},yee=t=>{let e=0,s=t.trim(),n=YS(s);for(;n;)e++,s=n.body.trim(),n=YS(s);return e},xee=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let s=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Al.DEFAULT_MAX_EXTGLOB_RECURSION,n=PM(t).map(r=>r.trim());if(n.length>1&&(n.some(r=>r==="")||n.some(r=>/^[*?]+$/.test(r))||hee(n)))return{risky:!0};for(let r of n){let i=gee(r);if(i)return{risky:!0,safeOutput:i};if(yee(r)>s)return{risky:!0}}return{risky:!1}},JS=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=TM[t]||t;let s={...e},n=typeof s.maxLength=="number"?Math.min(Pm,s.maxLength):Pm,r=t.length;if(r>n)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:s.prepend||""},o=[i],a=s.capture?"":"?:",c=bs.isWindows(e),u=Al.globChars(c),l=Al.extglobChars(u),{DOT_LITERAL:d,PLUS_LITERAL:p,SLASH_LITERAL:f,ONE_CHAR:m,DOTS_SLASH:g,NO_DOT:h,NO_DOT_SLASH:v,NO_DOTS_SLASH:x,QMARK:S,QMARK_NO_DOT:w,STAR:E,START_ANCHOR:P}=u,k=L=>`(${a}(?:(?!${P}${L.dot?g:d}).)*?)`,A=s.dot?"":h,M=s.dot?S:w,z=s.bash===!0?k(s):E;s.capture&&(z=`(${z})`),typeof s.noext=="boolean"&&(s.noextglob=s.noext);let C={input:t,index:-1,start:0,dot:s.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};t=bs.removePrefix(t,C),r=t.length;let U=[],_=[],Y=[],y=i,b,K=()=>C.index===r-1,q=C.peek=(L=1)=>t[C.index+L],te=C.advance=()=>t[++C.index]||"",X=()=>t.slice(C.index+1),ee=(L="",ae=0)=>{C.consumed+=L,C.index+=ae},fe=L=>{C.output+=L.output!=null?L.output:L.value,ee(L.value)},Re=()=>{let L=1;for(;q()==="!"&&(q(2)!=="("||q(3)==="?");)te(),C.start++,L++;return L%2===0?!1:(C.negated=!0,C.start++,!0)},se=L=>{C[L]++,Y.push(L)},Ce=L=>{C[L]--,Y.pop()},G=L=>{if(y.type==="globstar"){let ae=C.braces>0&&(L.type==="comma"||L.type==="brace"),W=L.extglob===!0||U.length&&(L.type==="pipe"||L.type==="paren");L.type!=="slash"&&L.type!=="paren"&&!ae&&!W&&(C.output=C.output.slice(0,-y.output.length),y.type="star",y.value="*",y.output=z,C.output+=y.output)}if(U.length&&L.type!=="paren"&&(U[U.length-1].inner+=L.value),(L.value||L.output)&&fe(L),y&&y.type==="text"&&L.type==="text"){y.value+=L.value,y.output=(y.output||"")+L.value;return}L.prev=y,o.push(L),y=L},xe=(L,ae)=>{let W={...l[ae],conditions:1,inner:""};W.prev=y,W.parens=C.parens,W.output=C.output,W.startIndex=C.index,W.tokensIndex=o.length;let ue=(s.capture?"(":"")+W.open;se("parens"),G({type:L,value:ae,output:C.output?"":m}),G({type:"paren",extglob:!0,value:te(),output:ue}),U.push(W)},ge=L=>{let ae=t.slice(L.startIndex,C.index+1),W=t.slice(L.startIndex+2,C.index),ue=xee(W,s);if((L.type==="plus"||L.type==="star")&&ue.risky){let I=ue.safeOutput?(L.output?"":m)+(s.capture?`(${ue.safeOutput})`:ue.safeOutput):void 0,H=o[L.tokensIndex];H.type="text",H.value=ae,H.output=I||bs.escapeRegex(ae);for(let ce=L.tokensIndex+1;ce<o.length;ce++)o[ce].value="",o[ce].output="",delete o[ce].suffix;C.output=L.output+H.output,C.backtrack=!0,G({type:"paren",extglob:!0,value:b,output:""}),Ce("parens");return}let De=L.close+(s.capture?")":""),Be;if(L.type==="negate"){let I=z;if(L.inner&&L.inner.length>1&&L.inner.includes("/")&&(I=k(s)),(I!==z||K()||/^\)+$/.test(X()))&&(De=L.close=`)$))${I}`),L.inner.includes("*")&&(Be=X())&&/^\.[^\\/.]+$/.test(Be)){let H=JS(Be,{...e,fastpaths:!1}).output;De=L.close=`)${H})${I})`}L.prev.type==="bos"&&(C.negatedExtglob=!0)}G({type:"paren",extglob:!0,value:b,output:De}),Ce("parens")};if(s.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let L=!1,ae=t.replace(pee,(W,ue,De,Be,I,H)=>Be==="\\"?(L=!0,W):Be==="?"?ue?ue+Be+(I?S.repeat(I.length):""):H===0?M+(I?S.repeat(I.length):""):S.repeat(De.length):Be==="."?d.repeat(De.length):Be==="*"?ue?ue+Be+(I?z:""):z:ue?W:`\\${W}`);return L===!0&&(s.unescape===!0?ae=ae.replace(/\\/g,""):ae=ae.replace(/\\+/g,W=>W.length%2===0?"\\\\":W?"\\":"")),ae===t&&s.contains===!0?(C.output=t,C):(C.output=bs.wrapOutput(ae,C,e),C)}for(;!K();){if(b=te(),b==="\0")continue;if(b==="\\"){let W=q();if(W==="/"&&s.bash!==!0||W==="."||W===";")continue;if(!W){b+="\\",G({type:"text",value:b});continue}let ue=/^\\+/.exec(X()),De=0;if(ue&&ue[0].length>2&&(De=ue[0].length,C.index+=De,De%2!==0&&(b+="\\")),s.unescape===!0?b=te():b+=te(),C.brackets===0){G({type:"text",value:b});continue}}if(C.brackets>0&&(b!=="]"||y.value==="["||y.value==="[^")){if(s.posix!==!1&&b===":"){let W=y.value.slice(1);if(W.includes("[")&&(y.posix=!0,W.includes(":"))){let ue=y.value.lastIndexOf("["),De=y.value.slice(0,ue),Be=y.value.slice(ue+2),I=lee[Be];if(I){y.value=De+I,C.backtrack=!0,te(),!i.output&&o.indexOf(y)===1&&(i.output=m);continue}}}(b==="["&&q()!==":"||b==="-"&&q()==="]")&&(b=`\\${b}`),b==="]"&&(y.value==="["||y.value==="[^")&&(b=`\\${b}`),s.posix===!0&&b==="!"&&y.value==="["&&(b="^"),y.value+=b,fe({value:b});continue}if(C.quotes===1&&b!=='"'){b=bs.escapeRegex(b),y.value+=b,fe({value:b});continue}if(b==='"'){C.quotes=C.quotes===1?0:1,s.keepQuotes===!0&&G({type:"text",value:b});continue}if(b==="("){se("parens"),G({type:"paren",value:b});continue}if(b===")"){if(C.parens===0&&s.strictBrackets===!0)throw new SyntaxError(Ec("opening","("));let W=U[U.length-1];if(W&&C.parens===W.parens+1){ge(U.pop());continue}G({type:"paren",value:b,output:C.parens?")":"\\)"}),Ce("parens");continue}if(b==="["){if(s.nobracket===!0||!X().includes("]")){if(s.nobracket!==!0&&s.strictBrackets===!0)throw new SyntaxError(Ec("closing","]"));b=`\\${b}`}else se("brackets");G({type:"bracket",value:b});continue}if(b==="]"){if(s.nobracket===!0||y&&y.type==="bracket"&&y.value.length===1){G({type:"text",value:b,output:`\\${b}`});continue}if(C.brackets===0){if(s.strictBrackets===!0)throw new SyntaxError(Ec("opening","["));G({type:"text",value:b,output:`\\${b}`});continue}Ce("brackets");let W=y.value.slice(1);if(y.posix!==!0&&W[0]==="^"&&!W.includes("/")&&(b=`/${b}`),y.value+=b,fe({value:b}),s.literalBrackets===!1||bs.hasRegexChars(W))continue;let ue=bs.escapeRegex(y.value);if(C.output=C.output.slice(0,-y.value.length),s.literalBrackets===!0){C.output+=ue,y.value=ue;continue}y.value=`(${a}${ue}|${y.value})`,C.output+=y.value;continue}if(b==="{"&&s.nobrace!==!0){se("braces");let W={type:"brace",value:b,output:"(",outputIndex:C.output.length,tokensIndex:C.tokens.length};_.push(W),G(W);continue}if(b==="}"){let W=_[_.length-1];if(s.nobrace===!0||!W){G({type:"text",value:b,output:b});continue}let ue=")";if(W.dots===!0){let De=o.slice(),Be=[];for(let I=De.length-1;I>=0&&(o.pop(),De[I].type!=="brace");I--)De[I].type!=="dots"&&Be.unshift(De[I].value);ue=fee(Be,s),C.backtrack=!0}if(W.comma!==!0&&W.dots!==!0){let De=C.output.slice(0,W.outputIndex),Be=C.tokens.slice(W.tokensIndex);W.value=W.output="\\{",b=ue="\\}",C.output=De;for(let I of Be)C.output+=I.output||I.value}G({type:"brace",value:b,output:ue}),Ce("braces"),_.pop();continue}if(b==="|"){U.length>0&&U[U.length-1].conditions++,G({type:"text",value:b});continue}if(b===","){let W=b,ue=_[_.length-1];ue&&Y[Y.length-1]==="braces"&&(ue.comma=!0,W="|"),G({type:"comma",value:b,output:W});continue}if(b==="/"){if(y.type==="dot"&&C.index===C.start+1){C.start=C.index+1,C.consumed="",C.output="",o.pop(),y=i;continue}G({type:"slash",value:b,output:f});continue}if(b==="."){if(C.braces>0&&y.type==="dot"){y.value==="."&&(y.output=d);let W=_[_.length-1];y.type="dots",y.output+=b,y.value+=b,W.dots=!0;continue}if(C.braces+C.parens===0&&y.type!=="bos"&&y.type!=="slash"){G({type:"text",value:b,output:d});continue}G({type:"dot",value:b,output:d});continue}if(b==="?"){if(!(y&&y.value==="(")&&s.noextglob!==!0&&q()==="("&&q(2)!=="?"){xe("qmark",b);continue}if(y&&y.type==="paren"){let ue=q(),De=b;if(ue==="<"&&!bs.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(y.value==="("&&!/[!=<:]/.test(ue)||ue==="<"&&!/<([!=]|\w+>)/.test(X()))&&(De=`\\${b}`),G({type:"text",value:b,output:De});continue}if(s.dot!==!0&&(y.type==="slash"||y.type==="bos")){G({type:"qmark",value:b,output:w});continue}G({type:"qmark",value:b,output:S});continue}if(b==="!"){if(s.noextglob!==!0&&q()==="("&&(q(2)!=="?"||!/[!=<:]/.test(q(3)))){xe("negate",b);continue}if(s.nonegate!==!0&&C.index===0){Re();continue}}if(b==="+"){if(s.noextglob!==!0&&q()==="("&&q(2)!=="?"){xe("plus",b);continue}if(y&&y.value==="("||s.regex===!1){G({type:"plus",value:b,output:p});continue}if(y&&(y.type==="bracket"||y.type==="paren"||y.type==="brace")||C.parens>0){G({type:"plus",value:b});continue}G({type:"plus",value:p});continue}if(b==="@"){if(s.noextglob!==!0&&q()==="("&&q(2)!=="?"){G({type:"at",extglob:!0,value:b,output:""});continue}G({type:"text",value:b});continue}if(b!=="*"){(b==="$"||b==="^")&&(b=`\\${b}`);let W=dee.exec(X());W&&(b+=W[0],C.index+=W[0].length),G({type:"text",value:b});continue}if(y&&(y.type==="globstar"||y.star===!0)){y.type="star",y.star=!0,y.value+=b,y.output=z,C.backtrack=!0,C.globstar=!0,ee(b);continue}let L=X();if(s.noextglob!==!0&&/^\([^?]/.test(L)){xe("star",b);continue}if(y.type==="star"){if(s.noglobstar===!0){ee(b);continue}let W=y.prev,ue=W.prev,De=W.type==="slash"||W.type==="bos",Be=ue&&(ue.type==="star"||ue.type==="globstar");if(s.bash===!0&&(!De||L[0]&&L[0]!=="/")){G({type:"star",value:b,output:""});continue}let I=C.braces>0&&(W.type==="comma"||W.type==="brace"),H=U.length&&(W.type==="pipe"||W.type==="paren");if(!De&&W.type!=="paren"&&!I&&!H){G({type:"star",value:b,output:""});continue}for(;L.slice(0,3)==="/**";){let ce=t[C.index+4];if(ce&&ce!=="/")break;L=L.slice(3),ee("/**",3)}if(W.type==="bos"&&K()){y.type="globstar",y.value+=b,y.output=k(s),C.output=y.output,C.globstar=!0,ee(b);continue}if(W.type==="slash"&&W.prev.type!=="bos"&&!Be&&K()){C.output=C.output.slice(0,-(W.output+y.output).length),W.output=`(?:${W.output}`,y.type="globstar",y.output=k(s)+(s.strictSlashes?")":"|$)"),y.value+=b,C.globstar=!0,C.output+=W.output+y.output,ee(b);continue}if(W.type==="slash"&&W.prev.type!=="bos"&&L[0]==="/"){let ce=L[1]!==void 0?"|$":"";C.output=C.output.slice(0,-(W.output+y.output).length),W.output=`(?:${W.output}`,y.type="globstar",y.output=`${k(s)}${f}|${f}${ce})`,y.value+=b,C.output+=W.output+y.output,C.globstar=!0,ee(b+te()),G({type:"slash",value:"/",output:""});continue}if(W.type==="bos"&&L[0]==="/"){y.type="globstar",y.value+=b,y.output=`(?:^|${f}|${k(s)}${f})`,C.output=y.output,C.globstar=!0,ee(b+te()),G({type:"slash",value:"/",output:""});continue}C.output=C.output.slice(0,-y.output.length),y.type="globstar",y.output=k(s),y.value+=b,C.output+=y.output,C.globstar=!0,ee(b);continue}let ae={type:"star",value:b,output:z};if(s.bash===!0){ae.output=".*?",(y.type==="bos"||y.type==="slash")&&(ae.output=A+ae.output),G(ae);continue}if(y&&(y.type==="bracket"||y.type==="paren")&&s.regex===!0){ae.output=b,G(ae);continue}(C.index===C.start||y.type==="slash"||y.type==="dot")&&(y.type==="dot"?(C.output+=v,y.output+=v):s.dot===!0?(C.output+=x,y.output+=x):(C.output+=A,y.output+=A),q()!=="*"&&(C.output+=m,y.output+=m)),G(ae)}for(;C.brackets>0;){if(s.strictBrackets===!0)throw new SyntaxError(Ec("closing","]"));C.output=bs.escapeLast(C.output,"["),Ce("brackets")}for(;C.parens>0;){if(s.strictBrackets===!0)throw new SyntaxError(Ec("closing",")"));C.output=bs.escapeLast(C.output,"("),Ce("parens")}for(;C.braces>0;){if(s.strictBrackets===!0)throw new SyntaxError(Ec("closing","}"));C.output=bs.escapeLast(C.output,"{"),Ce("braces")}if(s.strictSlashes!==!0&&(y.type==="star"||y.type==="bracket")&&G({type:"maybe_slash",value:"",output:`${f}?`}),C.backtrack===!0){C.output="";for(let L of C.tokens)C.output+=L.output!=null?L.output:L.value,L.suffix&&(C.output+=L.suffix)}return C};JS.fastpaths=(t,e)=>{let s={...e},n=typeof s.maxLength=="number"?Math.min(Pm,s.maxLength):Pm,r=t.length;if(r>n)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${n}`);t=TM[t]||t;let i=bs.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:u,NO_DOT:l,NO_DOTS:d,NO_DOTS_SLASH:p,STAR:f,START_ANCHOR:m}=Al.globChars(i),g=s.dot?d:l,h=s.dot?p:l,v=s.capture?"":"?:",x={negated:!1,prefix:""},S=s.bash===!0?".*?":f;s.capture&&(S=`(${S})`);let w=A=>A.noglobstar===!0?S:`(${v}(?:(?!${m}${A.dot?u:o}).)*?)`,E=A=>{switch(A){case"*":return`${g}${c}${S}`;case".*":return`${o}${c}${S}`;case"*.*":return`${g}${S}${o}${c}${S}`;case"*/*":return`${g}${S}${a}${c}${h}${S}`;case"**":return g+w(s);case"**/*":return`(?:${g}${w(s)}${a})?${h}${c}${S}`;case"**/*.*":return`(?:${g}${w(s)}${a})?${h}${S}${o}${c}${S}`;case"**/.*":return`(?:${g}${w(s)}${a})?${o}${c}${S}`;default:{let M=/^(.*?)\.(\w+)$/.exec(A);if(!M)return;let z=E(M[1]);return z?z+o+M[2]:void 0}}},P=bs.removePrefix(t,x),k=E(P);return k&&s.strictSlashes!==!0&&(k+=`${a}?`),k};OM.exports=JS});var NM=O((j1e,BM)=>{"use strict";var bee=require("path"),See=FM(),QS=MM(),XS=Tm(),vee=Dl(),Cee=t=>t&&typeof t=="object"&&!Array.isArray(t),qt=(t,e,s=!1)=>{if(Array.isArray(t)){let l=t.map(p=>qt(p,e,s));return p=>{for(let f of l){let m=f(p);if(m)return m}return!1}}let n=Cee(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let r=e||{},i=XS.isWindows(e),o=n?qt.compileRe(t,e):qt.makeRe(t,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(r.ignore){let l={...e,ignore:null,onMatch:null,onResult:null};c=qt(r.ignore,l,s)}let u=(l,d=!1)=>{let{isMatch:p,match:f,output:m}=qt.test(l,o,e,{glob:t,posix:i}),g={glob:t,state:a,regex:o,posix:i,input:l,output:m,match:f,isMatch:p};return typeof r.onResult=="function"&&r.onResult(g),p===!1?(g.isMatch=!1,d?g:!1):c(l)?(typeof r.onIgnore=="function"&&r.onIgnore(g),g.isMatch=!1,d?g:!1):(typeof r.onMatch=="function"&&r.onMatch(g),d?g:!0)};return s&&(u.state=a),u};qt.test=(t,e,s,{glob:n,posix:r}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let i=s||{},o=i.format||(r?XS.toPosixSlashes:null),a=t===n,c=a&&o?o(t):t;return a===!1&&(c=o?o(t):t,a=c===n),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=qt.matchBase(t,e,s,r):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};qt.matchBase=(t,e,s,n=XS.isWindows(s))=>(e instanceof RegExp?e:qt.makeRe(e,s)).test(bee.basename(t));qt.isMatch=(t,e,s)=>qt(e,s)(t);qt.parse=(t,e)=>Array.isArray(t)?t.map(s=>qt.parse(s,e)):QS(t,{...e,fastpaths:!1});qt.scan=(t,e)=>See(t,e);qt.compileRe=(t,e,s=!1,n=!1)=>{if(s===!0)return t.output;let r=e||{},i=r.contains?"":"^",o=r.contains?"":"$",a=`${i}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let c=qt.toRegex(a,e);return n===!0&&(c.state=t),c};qt.makeRe=(t,e={},s=!1,n=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let r={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(r.output=QS.fastpaths(t,e)),r.output||(r=QS(t,e)),qt.compileRe(r,e,s,n)};qt.toRegex=(t,e)=>{try{let s=e||{};return new RegExp(t,s.flags||(s.nocase?"i":""))}catch(s){if(e&&e.debug===!0)throw s;return/$^/}};qt.constants=vee;BM.exports=qt});var WM=O((U1e,$M)=>{"use strict";$M.exports=NM()});var KM=O((H1e,VM)=>{"use strict";var Rl=require("fs"),{Readable:Dee}=require("stream"),El=require("path"),{promisify:Bm}=require("util"),ev=WM(),wee=Bm(Rl.readdir),Aee=Bm(Rl.stat),jM=Bm(Rl.lstat),Eee=Bm(Rl.realpath),Ree="!",zM="READDIRP_RECURSIVE_ERROR",Iee=new Set(["ENOENT","EPERM","EACCES","ELOOP",zM]),tv="files",qM="directories",Om="files_directories",Lm="all",UM=[tv,qM,Om,Lm],_ee=t=>Iee.has(t.code),[HM,kee]=process.versions.node.split(".").slice(0,2).map(t=>Number.parseInt(t,10)),Fee=process.platform==="win32"&&(HM>10||HM===10&&kee>=5),GM=t=>{if(t!==void 0){if(typeof t=="function")return t;if(typeof t=="string"){let e=ev(t.trim());return s=>e(s.basename)}if(Array.isArray(t)){let e=[],s=[];for(let n of t){let r=n.trim();r.charAt(0)===Ree?s.push(ev(r.slice(1))):e.push(ev(r))}return s.length>0?e.length>0?n=>e.some(r=>r(n.basename))&&!s.some(r=>r(n.basename)):n=>!s.some(r=>r(n.basename)):n=>e.some(r=>r(n.basename))}}},Mm=class t extends Dee{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:tv,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let s={...t.defaultOptions,...e},{root:n,type:r}=s;this._fileFilter=GM(s.fileFilter),this._directoryFilter=GM(s.directoryFilter);let i=s.lstat?jM:Aee;Fee?this._stat=o=>i(o,{bigint:!0}):this._stat=i,this._maxDepth=s.depth,this._wantsDir=[qM,Om,Lm].includes(r),this._wantsFile=[tv,Om,Lm].includes(r),this._wantsEverything=r===Lm,this._root=El.resolve(n),this._isDirent="Dirent"in Rl&&!s.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:s,depth:n,files:r=[]}=this.parent||{};if(r.length>0){let i=r.splice(0,e).map(o=>this._formatEntry(o,s));for(let o of await Promise.all(i)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(n<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,n+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}if(this.parent=await i,this.destroyed)return}}}catch(s){this.destroy(s)}finally{this.reading=!1}}}async _exploreDir(e,s){let n;try{n=await wee(e,this._rdOptions)}catch(r){this._onError(r)}return{files:n,depth:s,path:e}}async _formatEntry(e,s){let n;try{let r=this._isDirent?e.name:e,i=El.resolve(El.join(s,r));n={path:El.relative(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(r){this._onError(r)}return n}_onError(e){_ee(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let s=e&&e[this._statsProp];if(s){if(s.isFile())return"file";if(s.isDirectory())return"directory";if(s&&s.isSymbolicLink()){let n=e.fullPath;try{let r=await Eee(n),i=await jM(r);if(i.isFile())return"file";if(i.isDirectory()){let o=r.length;if(n.startsWith(r)&&n.substr(o,1)===El.sep){let a=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return a.code=zM,this._onError(a)}return"directory"}}catch(r){this._onError(r)}}}}_includeAsFile(e){let s=e&&e[this._statsProp];return s&&this._wantsEverything&&!s.isDirectory()}},Rc=(t,e={})=>{let s=e.entryType||e.type;if(s==="both"&&(s=Om),s&&(e.type=s),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(s&&!UM.includes(s))throw new Error(`readdirp: Invalid type passed. Use one of ${UM.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=t,new Mm(e)},Tee=(t,e={})=>new Promise((s,n)=>{let r=[];Rc(t,e).on("data",i=>r.push(i)).on("end",()=>s(r)).on("error",i=>n(i))});Rc.promise=Tee;Rc.ReaddirpStream=Mm;Rc.default=Rc;VM.exports=Rc});var Il=O((G1e,XM)=>{"use strict";var Pee=require("path"),pr="\\\\/",ZM=`[^${pr}]`,Lee=0,Gr="\\.",Oee="\\+",Mee="\\?",Nm="\\/",Bee="(?=.)",YM="[^/]",sv=`(?:${Nm}|$)`,JM=`(?:^|${Nm})`,nv=`${Gr}{1,2}${sv}`,Nee=`(?!${Gr})`,$ee=`(?!${JM}${nv})`,Wee=`(?!${Gr}{0,1}${sv})`,jee=`(?!${nv})`,Uee=`[^.${Nm}]`,Hee=`${YM}*?`,QM={DOT_LITERAL:Gr,PLUS_LITERAL:Oee,QMARK_LITERAL:Mee,SLASH_LITERAL:Nm,ONE_CHAR:Bee,QMARK:YM,END_ANCHOR:sv,DOTS_SLASH:nv,NO_DOT:Nee,NO_DOTS:$ee,NO_DOT_SLASH:Wee,NO_DOTS_SLASH:jee,QMARK_NO_DOT:Uee,STAR:Hee,START_ANCHOR:JM},Gee={...QM,SLASH_LITERAL:`[${pr}]`,QMARK:ZM,STAR:`${ZM}*?`,DOTS_SLASH:`${Gr}{1,2}(?:[${pr}]|$)`,NO_DOT:`(?!${Gr})`,NO_DOTS:`(?!(?:^|[${pr}])${Gr}{1,2}(?:[${pr}]|$))`,NO_DOT_SLASH:`(?!${Gr}{0,1}(?:[${pr}]|$))`,NO_DOTS_SLASH:`(?!${Gr}{1,2}(?:[${pr}]|$))`,QMARK_NO_DOT:`[^.${pr}]`,START_ANCHOR:`(?:^|[${pr}])`,END_ANCHOR:`(?:[${pr}]|$)`},zee={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};XM.exports={DEFAULT_MAX_EXTGLOB_RECURSION:Lee,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:zee,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:Pee.sep,extglobChars(t){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===!0?Gee:QM}}});var $m=O(Bs=>{"use strict";var qee=require("path"),Vee=process.platform==="win32",{REGEX_BACKSLASH:Kee,REGEX_REMOVE_BACKSLASH:Zee,REGEX_SPECIAL_CHARS:Yee,REGEX_SPECIAL_CHARS_GLOBAL:Jee}=Il();Bs.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);Bs.hasRegexChars=t=>Yee.test(t);Bs.isRegexChar=t=>t.length===1&&Bs.hasRegexChars(t);Bs.escapeRegex=t=>t.replace(Jee,"\\$1");Bs.toPosixSlashes=t=>t.replace(Kee,"/");Bs.removeBackslashes=t=>t.replace(Zee,e=>e==="\\"?"":e);Bs.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};Bs.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:Vee===!0||qee.sep==="\\";Bs.escapeLast=(t,e,s)=>{let n=t.lastIndexOf(e,s);return n===-1?t:t[n-1]==="\\"?Bs.escapeLast(t,e,n-1):`${t.slice(0,n)}\\${t.slice(n)}`};Bs.removePrefix=(t,e={})=>{let s=t;return s.startsWith("./")&&(s=s.slice(2),e.prefix="./"),s};Bs.wrapOutput=(t,e={},s={})=>{let n=s.contains?"":"^",r=s.contains?"":"$",i=`${n}(?:${t})${r}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var aB=O((q1e,oB)=>{"use strict";var eB=$m(),{CHAR_ASTERISK:rv,CHAR_AT:Qee,CHAR_BACKWARD_SLASH:_l,CHAR_COMMA:Xee,CHAR_DOT:iv,CHAR_EXCLAMATION_MARK:ov,CHAR_FORWARD_SLASH:iB,CHAR_LEFT_CURLY_BRACE:av,CHAR_LEFT_PARENTHESES:cv,CHAR_LEFT_SQUARE_BRACKET:ete,CHAR_PLUS:tte,CHAR_QUESTION_MARK:tB,CHAR_RIGHT_CURLY_BRACE:ste,CHAR_RIGHT_PARENTHESES:sB,CHAR_RIGHT_SQUARE_BRACKET:nte}=Il(),nB=t=>t===iB||t===_l,rB=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},rte=(t,e)=>{let s=e||{},n=t.length-1,r=s.parts===!0||s.scanToEnd===!0,i=[],o=[],a=[],c=t,u=-1,l=0,d=0,p=!1,f=!1,m=!1,g=!1,h=!1,v=!1,x=!1,S=!1,w=!1,E=!1,P=0,k,A,M={value:"",depth:0,isGlob:!1},z=()=>u>=n,C=()=>c.charCodeAt(u+1),U=()=>(k=A,c.charCodeAt(++u));for(;u<n;){A=U();let K;if(A===_l){x=M.backslashes=!0,A=U(),A===av&&(v=!0);continue}if(v===!0||A===av){for(P++;z()!==!0&&(A=U());){if(A===_l){x=M.backslashes=!0,U();continue}if(A===av){P++;continue}if(v!==!0&&A===iv&&(A=U())===iv){if(p=M.isBrace=!0,m=M.isGlob=!0,E=!0,r===!0)continue;break}if(v!==!0&&A===Xee){if(p=M.isBrace=!0,m=M.isGlob=!0,E=!0,r===!0)continue;break}if(A===ste&&(P--,P===0)){v=!1,p=M.isBrace=!0,E=!0;break}}if(r===!0)continue;break}if(A===iB){if(i.push(u),o.push(M),M={value:"",depth:0,isGlob:!1},E===!0)continue;if(k===iv&&u===l+1){l+=2;continue}d=u+1;continue}if(s.noext!==!0&&(A===tte||A===Qee||A===rv||A===tB||A===ov)===!0&&C()===cv){if(m=M.isGlob=!0,g=M.isExtglob=!0,E=!0,A===ov&&u===l&&(w=!0),r===!0){for(;z()!==!0&&(A=U());){if(A===_l){x=M.backslashes=!0,A=U();continue}if(A===sB){m=M.isGlob=!0,E=!0;break}}continue}break}if(A===rv){if(k===rv&&(h=M.isGlobstar=!0),m=M.isGlob=!0,E=!0,r===!0)continue;break}if(A===tB){if(m=M.isGlob=!0,E=!0,r===!0)continue;break}if(A===ete){for(;z()!==!0&&(K=U());){if(K===_l){x=M.backslashes=!0,U();continue}if(K===nte){f=M.isBracket=!0,m=M.isGlob=!0,E=!0;break}}if(r===!0)continue;break}if(s.nonegate!==!0&&A===ov&&u===l){S=M.negated=!0,l++;continue}if(s.noparen!==!0&&A===cv){if(m=M.isGlob=!0,r===!0){for(;z()!==!0&&(A=U());){if(A===cv){x=M.backslashes=!0,A=U();continue}if(A===sB){E=!0;break}}continue}break}if(m===!0){if(E=!0,r===!0)continue;break}}s.noext===!0&&(g=!1,m=!1);let _=c,Y="",y="";l>0&&(Y=c.slice(0,l),c=c.slice(l),d-=l),_&&m===!0&&d>0?(_=c.slice(0,d),y=c.slice(d)):m===!0?(_="",y=c):_=c,_&&_!==""&&_!=="/"&&_!==c&&nB(_.charCodeAt(_.length-1))&&(_=_.slice(0,-1)),s.unescape===!0&&(y&&(y=eB.removeBackslashes(y)),_&&x===!0&&(_=eB.removeBackslashes(_)));let b={prefix:Y,input:t,start:l,base:_,glob:y,isBrace:p,isBracket:f,isGlob:m,isExtglob:g,isGlobstar:h,negated:S,negatedExtglob:w};if(s.tokens===!0&&(b.maxDepth=0,nB(A)||o.push(M),b.tokens=o),s.parts===!0||s.tokens===!0){let K;for(let q=0;q<i.length;q++){let te=K?K+1:l,X=i[q],ee=t.slice(te,X);s.tokens&&(q===0&&l!==0?(o[q].isPrefix=!0,o[q].value=Y):o[q].value=ee,rB(o[q]),b.maxDepth+=o[q].depth),(q!==0||ee!=="")&&a.push(ee),K=X}if(K&&K+1<t.length){let q=t.slice(K+1);a.push(q),s.tokens&&(o[o.length-1].value=q,rB(o[o.length-1]),b.maxDepth+=o[o.length-1].depth)}b.slashes=i,b.parts=a}return b};oB.exports=rte});var pB=O((V1e,dB)=>{"use strict";var kl=Il(),Ss=$m(),{MAX_LENGTH:Wm,POSIX_REGEX_SOURCE:ite,REGEX_NON_SPECIAL_CHARS:ote,REGEX_SPECIAL_CHARS_BACKREF:ate,REPLACEMENTS:cB}=kl,cte=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let s=`[${t.join("-")}]`;try{new RegExp(s)}catch{return t.map(r=>Ss.escapeRegex(r)).join("..")}return s},Ic=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,uB=t=>{let e=[],s=0,n=0,r=0,i="",o=!1;for(let a of t){if(o===!0){i+=a,o=!1;continue}if(a==="\\"){i+=a,o=!0;continue}if(a==='"'){r=r===1?0:1,i+=a;continue}if(r===0){if(a==="[")s++;else if(a==="]"&&s>0)s--;else if(s===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){e.push(i),i="";continue}}}i+=a}return e.push(i),e},ute=t=>{let e=!1;for(let s of t){if(e===!0){e=!1;continue}if(s==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(s))return!1}return!0},lB=t=>{let e=t.trim(),s=!0;for(;s===!0;)s=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),s=!0);if(ute(e))return e.replace(/\\(.)/g,"$1")},lte=t=>{let e=t.map(lB).filter(Boolean);for(let s=0;s<e.length;s++)for(let n=s+1;n<e.length;n++){let r=e[s],i=e[n],o=r[0];if(!(!o||r!==o.repeat(r.length)||i!==o.repeat(i.length))&&(r===i||r.startsWith(i)||i.startsWith(r)))return!0}return!1},uv=(t,e=!0)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let s=0,n=0,r=0,i=!1;for(let o=1;o<t.length;o++){let a=t[o];if(i===!0){i=!1;continue}if(a==="\\"){i=!0;continue}if(a==='"'){r=r===1?0:1;continue}if(r!==1){if(a==="["){s++;continue}if(a==="]"&&s>0){s--;continue}if(!(s>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return e===!0&&o!==t.length-1?void 0:{type:t[0],body:t.slice(2,o),end:o}}}}},dte=t=>{let e=0,s=[];for(;e<t.length;){let r=uv(t.slice(e),!1);if(!r||r.type!=="*")return;let i=uB(r.body).map(a=>a.trim());if(i.length!==1)return;let o=lB(i[0]);if(!o||o.length!==1)return;s.push(o),e+=r.end+1}return s.length<1?void 0:`${s.length===1?Ss.escapeRegex(s[0]):`[${s.map(r=>Ss.escapeRegex(r)).join("")}]`}*`},pte=t=>{let e=0,s=t.trim(),n=uv(s);for(;n;)e++,s=n.body.trim(),n=uv(s);return e},fte=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let s=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:kl.DEFAULT_MAX_EXTGLOB_RECURSION,n=uB(t).map(r=>r.trim());if(n.length>1&&(n.some(r=>r==="")||n.some(r=>/^[*?]+$/.test(r))||lte(n)))return{risky:!0};for(let r of n){let i=dte(r);if(i)return{risky:!0,safeOutput:i};if(pte(r)>s)return{risky:!0}}return{risky:!1}},lv=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=cB[t]||t;let s={...e},n=typeof s.maxLength=="number"?Math.min(Wm,s.maxLength):Wm,r=t.length;if(r>n)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:s.prepend||""},o=[i],a=s.capture?"":"?:",c=Ss.isWindows(e),u=kl.globChars(c),l=kl.extglobChars(u),{DOT_LITERAL:d,PLUS_LITERAL:p,SLASH_LITERAL:f,ONE_CHAR:m,DOTS_SLASH:g,NO_DOT:h,NO_DOT_SLASH:v,NO_DOTS_SLASH:x,QMARK:S,QMARK_NO_DOT:w,STAR:E,START_ANCHOR:P}=u,k=L=>`(${a}(?:(?!${P}${L.dot?g:d}).)*?)`,A=s.dot?"":h,M=s.dot?S:w,z=s.bash===!0?k(s):E;s.capture&&(z=`(${z})`),typeof s.noext=="boolean"&&(s.noextglob=s.noext);let C={input:t,index:-1,start:0,dot:s.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};t=Ss.removePrefix(t,C),r=t.length;let U=[],_=[],Y=[],y=i,b,K=()=>C.index===r-1,q=C.peek=(L=1)=>t[C.index+L],te=C.advance=()=>t[++C.index]||"",X=()=>t.slice(C.index+1),ee=(L="",ae=0)=>{C.consumed+=L,C.index+=ae},fe=L=>{C.output+=L.output!=null?L.output:L.value,ee(L.value)},Re=()=>{let L=1;for(;q()==="!"&&(q(2)!=="("||q(3)==="?");)te(),C.start++,L++;return L%2===0?!1:(C.negated=!0,C.start++,!0)},se=L=>{C[L]++,Y.push(L)},Ce=L=>{C[L]--,Y.pop()},G=L=>{if(y.type==="globstar"){let ae=C.braces>0&&(L.type==="comma"||L.type==="brace"),W=L.extglob===!0||U.length&&(L.type==="pipe"||L.type==="paren");L.type!=="slash"&&L.type!=="paren"&&!ae&&!W&&(C.output=C.output.slice(0,-y.output.length),y.type="star",y.value="*",y.output=z,C.output+=y.output)}if(U.length&&L.type!=="paren"&&(U[U.length-1].inner+=L.value),(L.value||L.output)&&fe(L),y&&y.type==="text"&&L.type==="text"){y.value+=L.value,y.output=(y.output||"")+L.value;return}L.prev=y,o.push(L),y=L},xe=(L,ae)=>{let W={...l[ae],conditions:1,inner:""};W.prev=y,W.parens=C.parens,W.output=C.output,W.startIndex=C.index,W.tokensIndex=o.length;let ue=(s.capture?"(":"")+W.open;se("parens"),G({type:L,value:ae,output:C.output?"":m}),G({type:"paren",extglob:!0,value:te(),output:ue}),U.push(W)},ge=L=>{let ae=t.slice(L.startIndex,C.index+1),W=t.slice(L.startIndex+2,C.index),ue=fte(W,s);if((L.type==="plus"||L.type==="star")&&ue.risky){let I=ue.safeOutput?(L.output?"":m)+(s.capture?`(${ue.safeOutput})`:ue.safeOutput):void 0,H=o[L.tokensIndex];H.type="text",H.value=ae,H.output=I||Ss.escapeRegex(ae);for(let ce=L.tokensIndex+1;ce<o.length;ce++)o[ce].value="",o[ce].output="",delete o[ce].suffix;C.output=L.output+H.output,C.backtrack=!0,G({type:"paren",extglob:!0,value:b,output:""}),Ce("parens");return}let De=L.close+(s.capture?")":""),Be;if(L.type==="negate"){let I=z;if(L.inner&&L.inner.length>1&&L.inner.includes("/")&&(I=k(s)),(I!==z||K()||/^\)+$/.test(X()))&&(De=L.close=`)$))${I}`),L.inner.includes("*")&&(Be=X())&&/^\.[^\\/.]+$/.test(Be)){let H=lv(Be,{...e,fastpaths:!1}).output;De=L.close=`)${H})${I})`}L.prev.type==="bos"&&(C.negatedExtglob=!0)}G({type:"paren",extglob:!0,value:b,output:De}),Ce("parens")};if(s.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let L=!1,ae=t.replace(ate,(W,ue,De,Be,I,H)=>Be==="\\"?(L=!0,W):Be==="?"?ue?ue+Be+(I?S.repeat(I.length):""):H===0?M+(I?S.repeat(I.length):""):S.repeat(De.length):Be==="."?d.repeat(De.length):Be==="*"?ue?ue+Be+(I?z:""):z:ue?W:`\\${W}`);return L===!0&&(s.unescape===!0?ae=ae.replace(/\\/g,""):ae=ae.replace(/\\+/g,W=>W.length%2===0?"\\\\":W?"\\":"")),ae===t&&s.contains===!0?(C.output=t,C):(C.output=Ss.wrapOutput(ae,C,e),C)}for(;!K();){if(b=te(),b==="\0")continue;if(b==="\\"){let W=q();if(W==="/"&&s.bash!==!0||W==="."||W===";")continue;if(!W){b+="\\",G({type:"text",value:b});continue}let ue=/^\\+/.exec(X()),De=0;if(ue&&ue[0].length>2&&(De=ue[0].length,C.index+=De,De%2!==0&&(b+="\\")),s.unescape===!0?b=te():b+=te(),C.brackets===0){G({type:"text",value:b});continue}}if(C.brackets>0&&(b!=="]"||y.value==="["||y.value==="[^")){if(s.posix!==!1&&b===":"){let W=y.value.slice(1);if(W.includes("[")&&(y.posix=!0,W.includes(":"))){let ue=y.value.lastIndexOf("["),De=y.value.slice(0,ue),Be=y.value.slice(ue+2),I=ite[Be];if(I){y.value=De+I,C.backtrack=!0,te(),!i.output&&o.indexOf(y)===1&&(i.output=m);continue}}}(b==="["&&q()!==":"||b==="-"&&q()==="]")&&(b=`\\${b}`),b==="]"&&(y.value==="["||y.value==="[^")&&(b=`\\${b}`),s.posix===!0&&b==="!"&&y.value==="["&&(b="^"),y.value+=b,fe({value:b});continue}if(C.quotes===1&&b!=='"'){b=Ss.escapeRegex(b),y.value+=b,fe({value:b});continue}if(b==='"'){C.quotes=C.quotes===1?0:1,s.keepQuotes===!0&&G({type:"text",value:b});continue}if(b==="("){se("parens"),G({type:"paren",value:b});continue}if(b===")"){if(C.parens===0&&s.strictBrackets===!0)throw new SyntaxError(Ic("opening","("));let W=U[U.length-1];if(W&&C.parens===W.parens+1){ge(U.pop());continue}G({type:"paren",value:b,output:C.parens?")":"\\)"}),Ce("parens");continue}if(b==="["){if(s.nobracket===!0||!X().includes("]")){if(s.nobracket!==!0&&s.strictBrackets===!0)throw new SyntaxError(Ic("closing","]"));b=`\\${b}`}else se("brackets");G({type:"bracket",value:b});continue}if(b==="]"){if(s.nobracket===!0||y&&y.type==="bracket"&&y.value.length===1){G({type:"text",value:b,output:`\\${b}`});continue}if(C.brackets===0){if(s.strictBrackets===!0)throw new SyntaxError(Ic("opening","["));G({type:"text",value:b,output:`\\${b}`});continue}Ce("brackets");let W=y.value.slice(1);if(y.posix!==!0&&W[0]==="^"&&!W.includes("/")&&(b=`/${b}`),y.value+=b,fe({value:b}),s.literalBrackets===!1||Ss.hasRegexChars(W))continue;let ue=Ss.escapeRegex(y.value);if(C.output=C.output.slice(0,-y.value.length),s.literalBrackets===!0){C.output+=ue,y.value=ue;continue}y.value=`(${a}${ue}|${y.value})`,C.output+=y.value;continue}if(b==="{"&&s.nobrace!==!0){se("braces");let W={type:"brace",value:b,output:"(",outputIndex:C.output.length,tokensIndex:C.tokens.length};_.push(W),G(W);continue}if(b==="}"){let W=_[_.length-1];if(s.nobrace===!0||!W){G({type:"text",value:b,output:b});continue}let ue=")";if(W.dots===!0){let De=o.slice(),Be=[];for(let I=De.length-1;I>=0&&(o.pop(),De[I].type!=="brace");I--)De[I].type!=="dots"&&Be.unshift(De[I].value);ue=cte(Be,s),C.backtrack=!0}if(W.comma!==!0&&W.dots!==!0){let De=C.output.slice(0,W.outputIndex),Be=C.tokens.slice(W.tokensIndex);W.value=W.output="\\{",b=ue="\\}",C.output=De;for(let I of Be)C.output+=I.output||I.value}G({type:"brace",value:b,output:ue}),Ce("braces"),_.pop();continue}if(b==="|"){U.length>0&&U[U.length-1].conditions++,G({type:"text",value:b});continue}if(b===","){let W=b,ue=_[_.length-1];ue&&Y[Y.length-1]==="braces"&&(ue.comma=!0,W="|"),G({type:"comma",value:b,output:W});continue}if(b==="/"){if(y.type==="dot"&&C.index===C.start+1){C.start=C.index+1,C.consumed="",C.output="",o.pop(),y=i;continue}G({type:"slash",value:b,output:f});continue}if(b==="."){if(C.braces>0&&y.type==="dot"){y.value==="."&&(y.output=d);let W=_[_.length-1];y.type="dots",y.output+=b,y.value+=b,W.dots=!0;continue}if(C.braces+C.parens===0&&y.type!=="bos"&&y.type!=="slash"){G({type:"text",value:b,output:d});continue}G({type:"dot",value:b,output:d});continue}if(b==="?"){if(!(y&&y.value==="(")&&s.noextglob!==!0&&q()==="("&&q(2)!=="?"){xe("qmark",b);continue}if(y&&y.type==="paren"){let ue=q(),De=b;if(ue==="<"&&!Ss.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(y.value==="("&&!/[!=<:]/.test(ue)||ue==="<"&&!/<([!=]|\w+>)/.test(X()))&&(De=`\\${b}`),G({type:"text",value:b,output:De});continue}if(s.dot!==!0&&(y.type==="slash"||y.type==="bos")){G({type:"qmark",value:b,output:w});continue}G({type:"qmark",value:b,output:S});continue}if(b==="!"){if(s.noextglob!==!0&&q()==="("&&(q(2)!=="?"||!/[!=<:]/.test(q(3)))){xe("negate",b);continue}if(s.nonegate!==!0&&C.index===0){Re();continue}}if(b==="+"){if(s.noextglob!==!0&&q()==="("&&q(2)!=="?"){xe("plus",b);continue}if(y&&y.value==="("||s.regex===!1){G({type:"plus",value:b,output:p});continue}if(y&&(y.type==="bracket"||y.type==="paren"||y.type==="brace")||C.parens>0){G({type:"plus",value:b});continue}G({type:"plus",value:p});continue}if(b==="@"){if(s.noextglob!==!0&&q()==="("&&q(2)!=="?"){G({type:"at",extglob:!0,value:b,output:""});continue}G({type:"text",value:b});continue}if(b!=="*"){(b==="$"||b==="^")&&(b=`\\${b}`);let W=ote.exec(X());W&&(b+=W[0],C.index+=W[0].length),G({type:"text",value:b});continue}if(y&&(y.type==="globstar"||y.star===!0)){y.type="star",y.star=!0,y.value+=b,y.output=z,C.backtrack=!0,C.globstar=!0,ee(b);continue}let L=X();if(s.noextglob!==!0&&/^\([^?]/.test(L)){xe("star",b);continue}if(y.type==="star"){if(s.noglobstar===!0){ee(b);continue}let W=y.prev,ue=W.prev,De=W.type==="slash"||W.type==="bos",Be=ue&&(ue.type==="star"||ue.type==="globstar");if(s.bash===!0&&(!De||L[0]&&L[0]!=="/")){G({type:"star",value:b,output:""});continue}let I=C.braces>0&&(W.type==="comma"||W.type==="brace"),H=U.length&&(W.type==="pipe"||W.type==="paren");if(!De&&W.type!=="paren"&&!I&&!H){G({type:"star",value:b,output:""});continue}for(;L.slice(0,3)==="/**";){let ce=t[C.index+4];if(ce&&ce!=="/")break;L=L.slice(3),ee("/**",3)}if(W.type==="bos"&&K()){y.type="globstar",y.value+=b,y.output=k(s),C.output=y.output,C.globstar=!0,ee(b);continue}if(W.type==="slash"&&W.prev.type!=="bos"&&!Be&&K()){C.output=C.output.slice(0,-(W.output+y.output).length),W.output=`(?:${W.output}`,y.type="globstar",y.output=k(s)+(s.strictSlashes?")":"|$)"),y.value+=b,C.globstar=!0,C.output+=W.output+y.output,ee(b);continue}if(W.type==="slash"&&W.prev.type!=="bos"&&L[0]==="/"){let ce=L[1]!==void 0?"|$":"";C.output=C.output.slice(0,-(W.output+y.output).length),W.output=`(?:${W.output}`,y.type="globstar",y.output=`${k(s)}${f}|${f}${ce})`,y.value+=b,C.output+=W.output+y.output,C.globstar=!0,ee(b+te()),G({type:"slash",value:"/",output:""});continue}if(W.type==="bos"&&L[0]==="/"){y.type="globstar",y.value+=b,y.output=`(?:^|${f}|${k(s)}${f})`,C.output=y.output,C.globstar=!0,ee(b+te()),G({type:"slash",value:"/",output:""});continue}C.output=C.output.slice(0,-y.output.length),y.type="globstar",y.output=k(s),y.value+=b,C.output+=y.output,C.globstar=!0,ee(b);continue}let ae={type:"star",value:b,output:z};if(s.bash===!0){ae.output=".*?",(y.type==="bos"||y.type==="slash")&&(ae.output=A+ae.output),G(ae);continue}if(y&&(y.type==="bracket"||y.type==="paren")&&s.regex===!0){ae.output=b,G(ae);continue}(C.index===C.start||y.type==="slash"||y.type==="dot")&&(y.type==="dot"?(C.output+=v,y.output+=v):s.dot===!0?(C.output+=x,y.output+=x):(C.output+=A,y.output+=A),q()!=="*"&&(C.output+=m,y.output+=m)),G(ae)}for(;C.brackets>0;){if(s.strictBrackets===!0)throw new SyntaxError(Ic("closing","]"));C.output=Ss.escapeLast(C.output,"["),Ce("brackets")}for(;C.parens>0;){if(s.strictBrackets===!0)throw new SyntaxError(Ic("closing",")"));C.output=Ss.escapeLast(C.output,"("),Ce("parens")}for(;C.braces>0;){if(s.strictBrackets===!0)throw new SyntaxError(Ic("closing","}"));C.output=Ss.escapeLast(C.output,"{"),Ce("braces")}if(s.strictSlashes!==!0&&(y.type==="star"||y.type==="bracket")&&G({type:"maybe_slash",value:"",output:`${f}?`}),C.backtrack===!0){C.output="";for(let L of C.tokens)C.output+=L.output!=null?L.output:L.value,L.suffix&&(C.output+=L.suffix)}return C};lv.fastpaths=(t,e)=>{let s={...e},n=typeof s.maxLength=="number"?Math.min(Wm,s.maxLength):Wm,r=t.length;if(r>n)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${n}`);t=cB[t]||t;let i=Ss.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:u,NO_DOT:l,NO_DOTS:d,NO_DOTS_SLASH:p,STAR:f,START_ANCHOR:m}=kl.globChars(i),g=s.dot?d:l,h=s.dot?p:l,v=s.capture?"":"?:",x={negated:!1,prefix:""},S=s.bash===!0?".*?":f;s.capture&&(S=`(${S})`);let w=A=>A.noglobstar===!0?S:`(${v}(?:(?!${m}${A.dot?u:o}).)*?)`,E=A=>{switch(A){case"*":return`${g}${c}${S}`;case".*":return`${o}${c}${S}`;case"*.*":return`${g}${S}${o}${c}${S}`;case"*/*":return`${g}${S}${a}${c}${h}${S}`;case"**":return g+w(s);case"**/*":return`(?:${g}${w(s)}${a})?${h}${c}${S}`;case"**/*.*":return`(?:${g}${w(s)}${a})?${h}${S}${o}${c}${S}`;case"**/.*":return`(?:${g}${w(s)}${a})?${o}${c}${S}`;default:{let M=/^(.*?)\.(\w+)$/.exec(A);if(!M)return;let z=E(M[1]);return z?z+o+M[2]:void 0}}},P=Ss.removePrefix(t,x),k=E(P);return k&&s.strictSlashes!==!0&&(k+=`${a}?`),k};dB.exports=lv});var mB=O((K1e,fB)=>{"use strict";var mte=require("path"),hte=aB(),dv=pB(),pv=$m(),gte=Il(),yte=t=>t&&typeof t=="object"&&!Array.isArray(t),Vt=(t,e,s=!1)=>{if(Array.isArray(t)){let l=t.map(p=>Vt(p,e,s));return p=>{for(let f of l){let m=f(p);if(m)return m}return!1}}let n=yte(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let r=e||{},i=pv.isWindows(e),o=n?Vt.compileRe(t,e):Vt.makeRe(t,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(r.ignore){let l={...e,ignore:null,onMatch:null,onResult:null};c=Vt(r.ignore,l,s)}let u=(l,d=!1)=>{let{isMatch:p,match:f,output:m}=Vt.test(l,o,e,{glob:t,posix:i}),g={glob:t,state:a,regex:o,posix:i,input:l,output:m,match:f,isMatch:p};return typeof r.onResult=="function"&&r.onResult(g),p===!1?(g.isMatch=!1,d?g:!1):c(l)?(typeof r.onIgnore=="function"&&r.onIgnore(g),g.isMatch=!1,d?g:!1):(typeof r.onMatch=="function"&&r.onMatch(g),d?g:!0)};return s&&(u.state=a),u};Vt.test=(t,e,s,{glob:n,posix:r}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let i=s||{},o=i.format||(r?pv.toPosixSlashes:null),a=t===n,c=a&&o?o(t):t;return a===!1&&(c=o?o(t):t,a=c===n),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=Vt.matchBase(t,e,s,r):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};Vt.matchBase=(t,e,s,n=pv.isWindows(s))=>(e instanceof RegExp?e:Vt.makeRe(e,s)).test(mte.basename(t));Vt.isMatch=(t,e,s)=>Vt(e,s)(t);Vt.parse=(t,e)=>Array.isArray(t)?t.map(s=>Vt.parse(s,e)):dv(t,{...e,fastpaths:!1});Vt.scan=(t,e)=>hte(t,e);Vt.compileRe=(t,e,s=!1,n=!1)=>{if(s===!0)return t.output;let r=e||{},i=r.contains?"":"^",o=r.contains?"":"$",a=`${i}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let c=Vt.toRegex(a,e);return n===!0&&(c.state=t),c};Vt.makeRe=(t,e={},s=!1,n=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let r={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(r.output=dv.fastpaths(t,e)),r.output||(r=dv(t,e)),Vt.compileRe(r,e,s,n)};Vt.toRegex=(t,e)=>{try{let s=e||{};return new RegExp(t,s.flags||(s.nocase?"i":""))}catch(s){if(e&&e.debug===!0)throw s;return/$^/}};Vt.constants=gte;fB.exports=Vt});var gB=O((Z1e,hB)=>{"use strict";hB.exports=mB()});var fv=O((Y1e,yB)=>{yB.exports=function(t,e){if(typeof t!="string")throw new TypeError("expected path to be a string");if(t==="\\"||t==="/")return"/";var s=t.length;if(s<=1)return t;var n="";if(s>4&&t[3]==="\\"){var r=t[2];(r==="?"||r===".")&&t.slice(0,2)==="\\\\"&&(t=t.slice(2),n="//")}var i=t.split(/[/\\]+/);return e!==!1&&i[i.length-1]===""&&i.pop(),n+i.join("/")}});var DB=O((vB,CB)=>{"use strict";Object.defineProperty(vB,"__esModule",{value:!0});var SB=gB(),xte=fv(),xB="!",bte={returnIndex:!1},Ste=t=>Array.isArray(t)?t:[t],vte=(t,e)=>{if(typeof t=="function")return t;if(typeof t=="string"){let s=SB(t,e);return n=>t===n||s(n)}return t instanceof RegExp?s=>t.test(s):s=>!1},bB=(t,e,s,n)=>{let r=Array.isArray(s),i=r?s[0]:s;if(!r&&typeof i!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(i));let o=xte(i,!1);for(let c=0;c<e.length;c++){let u=e[c];if(u(o))return n?-1:!1}let a=r&&[o].concat(s.slice(1));for(let c=0;c<t.length;c++){let u=t[c];if(r?u(...a):u(o))return n?c:!0}return n?-1:!1},mv=(t,e,s=bte)=>{if(t==null)throw new TypeError("anymatch: specify first argument");let n=typeof s=="boolean"?{returnIndex:s}:s,r=n.returnIndex||!1,i=Ste(t),o=i.filter(c=>typeof c=="string"&&c.charAt(0)===xB).map(c=>c.slice(1)).map(c=>SB(c,n)),a=i.filter(c=>typeof c!="string"||typeof c=="string"&&c.charAt(0)!==xB).map(c=>vte(c,n));return e==null?(c,u=!1)=>bB(a,o,c,typeof u=="boolean"?u:!1):bB(a,o,e,r)};mv.default=mv;CB.exports=mv});var AB=O((J1e,wB)=>{wB.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var s;s=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(s[2])return!0;e=e.slice(s.index+s[0].length)}return!1}});var hv=O((Q1e,RB)=>{var Cte=AB(),EB={"{":"}","(":")","[":"]"},Dte=function(t){if(t[0]==="!")return!0;for(var e=0,s=-2,n=-2,r=-2,i=-2,o=-2;e<t.length;){if(t[e]==="*"||t[e+1]==="?"&&/[\].+)]/.test(t[e])||n!==-1&&t[e]==="["&&t[e+1]!=="]"&&(n<e&&(n=t.indexOf("]",e)),n>e&&(o===-1||o>n||(o=t.indexOf("\\",e),o===-1||o>n)))||r!==-1&&t[e]==="{"&&t[e+1]!=="}"&&(r=t.indexOf("}",e),r>e&&(o=t.indexOf("\\",e),o===-1||o>r))||i!==-1&&t[e]==="("&&t[e+1]==="?"&&/[:!=]/.test(t[e+2])&&t[e+3]!==")"&&(i=t.indexOf(")",e),i>e&&(o=t.indexOf("\\",e),o===-1||o>i))||s!==-1&&t[e]==="("&&t[e+1]!=="|"&&(s<e&&(s=t.indexOf("|",e)),s!==-1&&t[s+1]!==")"&&(i=t.indexOf(")",s),i>s&&(o=t.indexOf("\\",s),o===-1||o>i))))return!0;if(t[e]==="\\"){var a=t[e+1];e+=2;var c=EB[a];if(c){var u=t.indexOf(c,e);u!==-1&&(e=u+1)}if(t[e]==="!")return!0}else e++}return!1},wte=function(t){if(t[0]==="!")return!0;for(var e=0;e<t.length;){if(/[*?{}()[\]]/.test(t[e]))return!0;if(t[e]==="\\"){var s=t[e+1];e+=2;var n=EB[s];if(n){var r=t.indexOf(n,e);r!==-1&&(e=r+1)}if(t[e]==="!")return!0}else e++}return!1};RB.exports=function(e,s){if(typeof e!="string"||e==="")return!1;if(Cte(e))return!0;var n=Dte;return s&&s.strict===!1&&(n=wte),n(e)}});var _B=O((X1e,IB)=>{"use strict";var Ate=hv(),Ete=require("path").posix.dirname,Rte=require("os").platform()==="win32",gv="/",Ite=/\\/g,_te=/[\{\[].*[\}\]]$/,kte=/(^|[^\\])([\{\[]|\([^\)]+$)/,Fte=/\\([\!\*\?\|\[\]\(\)\{\}])/g;IB.exports=function(e,s){var n=Object.assign({flipBackslashes:!0},s);n.flipBackslashes&&Rte&&e.indexOf(gv)<0&&(e=e.replace(Ite,gv)),_te.test(e)&&(e+=gv),e+="a";do e=Ete(e);while(Ate(e)||kte.test(e));return e.replace(Fte,"$1")}});var jm=O(Rn=>{"use strict";Rn.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;Rn.find=(t,e)=>t.nodes.find(s=>s.type===e);Rn.exceedsLimit=(t,e,s=1,n)=>n===!1||!Rn.isInteger(t)||!Rn.isInteger(e)?!1:(Number(e)-Number(t))/Number(s)>=n;Rn.escapeNode=(t,e=0,s)=>{let n=t.nodes[e];n&&(s&&n.type===s||n.type==="open"||n.type==="close")&&n.escaped!==!0&&(n.value="\\"+n.value,n.escaped=!0)};Rn.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;Rn.isInvalidBrace=t=>t.type!=="brace"?!1:t.invalid===!0||t.dollar?!0:t.commas>>0+t.ranges>>0===0||t.open!==!0||t.close!==!0?(t.invalid=!0,!0):!1;Rn.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;Rn.reduce=t=>t.reduce((e,s)=>(s.type==="text"&&e.push(s.value),s.type==="range"&&(s.type="text"),e),[]);Rn.flatten=(...t)=>{let e=[],s=n=>{for(let r=0;r<n.length;r++){let i=n[r];if(Array.isArray(i)){s(i);continue}i!==void 0&&e.push(i)}return e};return s(t),e}});var Um=O((t_e,FB)=>{"use strict";var kB=jm();FB.exports=(t,e={})=>{let s=(n,r={})=>{let i=e.escapeInvalid&&kB.isInvalidBrace(r),o=n.invalid===!0&&e.escapeInvalid===!0,a="";if(n.value)return(i||o)&&kB.isOpenOrClose(n)?"\\"+n.value:n.value;if(n.value)return n.value;if(n.nodes)for(let c of n.nodes)a+=s(c);return a};return s(t)}});var PB=O((s_e,TB)=>{"use strict";TB.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var UB=O((n_e,jB)=>{"use strict";var LB=PB(),Jo=(t,e,s)=>{if(LB(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(LB(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let n={relaxZeros:!0,...s};typeof n.strictZeros=="boolean"&&(n.relaxZeros=n.strictZeros===!1);let r=String(n.relaxZeros),i=String(n.shorthand),o=String(n.capture),a=String(n.wrap),c=t+":"+e+"="+r+i+o+a;if(Jo.cache.hasOwnProperty(c))return Jo.cache[c].result;let u=Math.min(t,e),l=Math.max(t,e);if(Math.abs(u-l)===1){let g=t+"|"+e;return n.capture?`(${g})`:n.wrap===!1?g:`(?:${g})`}let d=WB(t)||WB(e),p={min:t,max:e,a:u,b:l},f=[],m=[];if(d&&(p.isPadded=d,p.maxLen=String(p.max).length),u<0){let g=l<0?Math.abs(l):1;m=OB(g,Math.abs(u),p,n),u=p.a=0}return l>=0&&(f=OB(u,l,p,n)),p.negatives=m,p.positives=f,p.result=Tte(m,f,n),n.capture===!0?p.result=`(${p.result})`:n.wrap!==!1&&f.length+m.length>1&&(p.result=`(?:${p.result})`),Jo.cache[c]=p,p.result};function Tte(t,e,s){let n=yv(t,e,"-",!1,s)||[],r=yv(e,t,"",!1,s)||[],i=yv(t,e,"-?",!0,s)||[];return n.concat(i).concat(r).join("|")}function Pte(t,e){let s=1,n=1,r=BB(t,s),i=new Set([e]);for(;t<=r&&r<=e;)i.add(r),s+=1,r=BB(t,s);for(r=NB(e+1,n)-1;t<r&&r<=e;)i.add(r),n+=1,r=NB(e+1,n)-1;return i=[...i],i.sort(Mte),i}function Lte(t,e,s){if(t===e)return{pattern:t,count:[],digits:0};let n=Ote(t,e),r=n.length,i="",o=0;for(let a=0;a<r;a++){let[c,u]=n[a];c===u?i+=c:c!=="0"||u!=="9"?i+=Bte(c,u,s):o++}return o&&(i+=s.shorthand===!0?"\\d":"[0-9]"),{pattern:i,count:[o],digits:r}}function OB(t,e,s,n){let r=Pte(t,e),i=[],o=t,a;for(let c=0;c<r.length;c++){let u=r[c],l=Lte(String(o),String(u),n),d="";if(!s.isPadded&&a&&a.pattern===l.pattern){a.count.length>1&&a.count.pop(),a.count.push(l.count[0]),a.string=a.pattern+$B(a.count),o=u+1;continue}s.isPadded&&(d=Nte(u,s,n)),l.string=d+l.pattern+$B(l.count),i.push(l),o=u+1,a=l}return i}function yv(t,e,s,n,r){let i=[];for(let o of t){let{string:a}=o;!n&&!MB(e,"string",a)&&i.push(s+a),n&&MB(e,"string",a)&&i.push(s+a)}return i}function Ote(t,e){let s=[];for(let n=0;n<t.length;n++)s.push([t[n],e[n]]);return s}function Mte(t,e){return t>e?1:e>t?-1:0}function MB(t,e,s){return t.some(n=>n[e]===s)}function BB(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function NB(t,e){return t-t%Math.pow(10,e)}function $B(t){let[e=0,s=""]=t;return s||e>1?`{${e+(s?","+s:"")}}`:""}function Bte(t,e,s){return`[${t}${e-t===1?"":"-"}${e}]`}function WB(t){return/^-?(0+)\d/.test(t)}function Nte(t,e,s){if(!e.isPadded)return t;let n=Math.abs(e.maxLen-String(t).length),r=s.relaxZeros!==!1;switch(n){case 0:return"";case 1:return r?"0?":"0";case 2:return r?"0{0,2}":"00";default:return r?`0{0,${n}}`:`0{${n}}`}}Jo.cache={};Jo.clearCache=()=>Jo.cache={};jB.exports=Jo});var Sv=O((r_e,ZB)=>{"use strict";var $te=require("util"),GB=UB(),HB=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),Wte=t=>e=>t===!0?Number(e):String(e),xv=t=>typeof t=="number"||typeof t=="string"&&t!=="",Fl=t=>Number.isInteger(+t),bv=t=>{let e=`${t}`,s=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++s]==="0";);return s>0},jte=(t,e,s)=>typeof t=="string"||typeof e=="string"?!0:s.stringify===!0,Ute=(t,e,s)=>{if(e>0){let n=t[0]==="-"?"-":"";n&&(t=t.slice(1)),t=n+t.padStart(n?e-1:e,"0")}return s===!1?String(t):t},Gm=(t,e)=>{let s=t[0]==="-"?"-":"";for(s&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return s?"-"+t:t},Hte=(t,e,s)=>{t.negatives.sort((a,c)=>a<c?-1:a>c?1:0),t.positives.sort((a,c)=>a<c?-1:a>c?1:0);let n=e.capture?"":"?:",r="",i="",o;return t.positives.length&&(r=t.positives.map(a=>Gm(String(a),s)).join("|")),t.negatives.length&&(i=`-(${n}${t.negatives.map(a=>Gm(String(a),s)).join("|")})`),r&&i?o=`${r}|${i}`:o=r||i,e.wrap?`(${n}${o})`:o},zB=(t,e,s,n)=>{if(s)return GB(t,e,{wrap:!1,...n});let r=String.fromCharCode(t);if(t===e)return r;let i=String.fromCharCode(e);return`[${r}-${i}]`},qB=(t,e,s)=>{if(Array.isArray(t)){let n=s.wrap===!0,r=s.capture?"":"?:";return n?`(${r}${t.join("|")})`:t.join("|")}return GB(t,e,s)},VB=(...t)=>new RangeError("Invalid range arguments: "+$te.inspect(...t)),KB=(t,e,s)=>{if(s.strictRanges===!0)throw VB([t,e]);return[]},Gte=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},zte=(t,e,s=1,n={})=>{let r=Number(t),i=Number(e);if(!Number.isInteger(r)||!Number.isInteger(i)){if(n.strictRanges===!0)throw VB([t,e]);return[]}r===0&&(r=0),i===0&&(i=0);let o=r>i,a=String(t),c=String(e),u=String(s);s=Math.max(Math.abs(s),1);let l=bv(a)||bv(c)||bv(u),d=l?Math.max(a.length,c.length,u.length):0,p=l===!1&&jte(t,e,n)===!1,f=n.transform||Wte(p);if(n.toRegex&&s===1)return zB(Gm(t,d),Gm(e,d),!0,n);let m={negatives:[],positives:[]},g=x=>m[x<0?"negatives":"positives"].push(Math.abs(x)),h=[],v=0;for(;o?r>=i:r<=i;)n.toRegex===!0&&s>1?g(r):h.push(Ute(f(r,v),d,p)),r=o?r-s:r+s,v++;return n.toRegex===!0?s>1?Hte(m,n,d):qB(h,null,{wrap:!1,...n}):h},qte=(t,e,s=1,n={})=>{if(!Fl(t)&&t.length>1||!Fl(e)&&e.length>1)return KB(t,e,n);let r=n.transform||(p=>String.fromCharCode(p)),i=`${t}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=i>o,c=Math.min(i,o),u=Math.max(i,o);if(n.toRegex&&s===1)return zB(c,u,!1,n);let l=[],d=0;for(;a?i>=o:i<=o;)l.push(r(i,d)),i=a?i-s:i+s,d++;return n.toRegex===!0?qB(l,null,{wrap:!1,options:n}):l},Hm=(t,e,s,n={})=>{if(e==null&&xv(t))return[t];if(!xv(t)||!xv(e))return KB(t,e,n);if(typeof s=="function")return Hm(t,e,1,{transform:s});if(HB(s))return Hm(t,e,0,s);let r={...n};return r.capture===!0&&(r.wrap=!0),s=s||r.step||1,Fl(s)?Fl(t)&&Fl(e)?zte(t,e,s,r):qte(t,e,Math.max(Math.abs(s),1),r):s!=null&&!HB(s)?Gte(s,r):Hm(t,e,1,s)};ZB.exports=Hm});var QB=O((i_e,JB)=>{"use strict";var Vte=Sv(),YB=jm(),Kte=(t,e={})=>{let s=(n,r={})=>{let i=YB.isInvalidBrace(r),o=n.invalid===!0&&e.escapeInvalid===!0,a=i===!0||o===!0,c=e.escapeInvalid===!0?"\\":"",u="";if(n.isOpen===!0)return c+n.value;if(n.isClose===!0)return console.log("node.isClose",c,n.value),c+n.value;if(n.type==="open")return a?c+n.value:"(";if(n.type==="close")return a?c+n.value:")";if(n.type==="comma")return n.prev.type==="comma"?"":a?n.value:"|";if(n.value)return n.value;if(n.nodes&&n.ranges>0){let l=YB.reduce(n.nodes),d=Vte(...l,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(d.length!==0)return l.length>1&&d.length>1?`(${d})`:d}if(n.nodes)for(let l of n.nodes)u+=s(l,n);return u};return s(t)};JB.exports=Kte});var tN=O((o_e,eN)=>{"use strict";var Zte=Sv(),XB=Um(),_c=jm(),Qo=(t="",e="",s=!1)=>{let n=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return s?_c.flatten(e).map(r=>`{${r}}`):e;for(let r of t)if(Array.isArray(r))for(let i of r)n.push(Qo(i,e,s));else for(let i of e)s===!0&&typeof i=="string"&&(i=`{${i}}`),n.push(Array.isArray(i)?Qo(r,i,s):r+i);return _c.flatten(n)},Yte=(t,e={})=>{let s=e.rangeLimit===void 0?1e3:e.rangeLimit,n=(r,i={})=>{r.queue=[];let o=i,a=i.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(r.invalid||r.dollar){a.push(Qo(a.pop(),XB(r,e)));return}if(r.type==="brace"&&r.invalid!==!0&&r.nodes.length===2){a.push(Qo(a.pop(),["{}"]));return}if(r.nodes&&r.ranges>0){let d=_c.reduce(r.nodes);if(_c.exceedsLimit(...d,e.step,s))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let p=Zte(...d,e);p.length===0&&(p=XB(r,e)),a.push(Qo(a.pop(),p)),r.nodes=[];return}let c=_c.encloseBrace(r),u=r.queue,l=r;for(;l.type!=="brace"&&l.type!=="root"&&l.parent;)l=l.parent,u=l.queue;for(let d=0;d<r.nodes.length;d++){let p=r.nodes[d];if(p.type==="comma"&&r.type==="brace"){d===1&&u.push(""),u.push("");continue}if(p.type==="close"){a.push(Qo(a.pop(),u,c));continue}if(p.value&&p.type!=="open"){u.push(Qo(u.pop(),p.value));continue}p.nodes&&n(p,r)}return u};return _c.flatten(n(t))};eN.exports=Yte});var nN=O((a_e,sN)=>{"use strict";sN.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
|
|
451
451
|
`,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var cN=O((c_e,aN)=>{"use strict";var Jte=Um(),{MAX_LENGTH:rN,CHAR_BACKSLASH:vv,CHAR_BACKTICK:Qte,CHAR_COMMA:Xte,CHAR_DOT:ese,CHAR_LEFT_PARENTHESES:tse,CHAR_RIGHT_PARENTHESES:sse,CHAR_LEFT_CURLY_BRACE:nse,CHAR_RIGHT_CURLY_BRACE:rse,CHAR_LEFT_SQUARE_BRACKET:iN,CHAR_RIGHT_SQUARE_BRACKET:oN,CHAR_DOUBLE_QUOTE:ise,CHAR_SINGLE_QUOTE:ose,CHAR_NO_BREAK_SPACE:ase,CHAR_ZERO_WIDTH_NOBREAK_SPACE:cse}=nN(),use=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let s=e||{},n=typeof s.maxLength=="number"?Math.min(rN,s.maxLength):rN;if(t.length>n)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${n})`);let r={type:"root",input:t,nodes:[]},i=[r],o=r,a=r,c=0,u=t.length,l=0,d=0,p,f=()=>t[l++],m=g=>{if(g.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&g.type==="text"){a.value+=g.value;return}return o.nodes.push(g),g.parent=o,g.prev=a,a=g,g};for(m({type:"bos"});l<u;)if(o=i[i.length-1],p=f(),!(p===cse||p===ase)){if(p===vv){m({type:"text",value:(e.keepEscaping?p:"")+f()});continue}if(p===oN){m({type:"text",value:"\\"+p});continue}if(p===iN){c++;let g;for(;l<u&&(g=f());){if(p+=g,g===iN){c++;continue}if(g===vv){p+=f();continue}if(g===oN&&(c--,c===0))break}m({type:"text",value:p});continue}if(p===tse){o=m({type:"paren",nodes:[]}),i.push(o),m({type:"text",value:p});continue}if(p===sse){if(o.type!=="paren"){m({type:"text",value:p});continue}o=i.pop(),m({type:"text",value:p}),o=i[i.length-1];continue}if(p===ise||p===ose||p===Qte){let g=p,h;for(e.keepQuotes!==!0&&(p="");l<u&&(h=f());){if(h===vv){p+=h+f();continue}if(h===g){e.keepQuotes===!0&&(p+=h);break}p+=h}m({type:"text",value:p});continue}if(p===nse){d++;let h={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:d,commas:0,ranges:0,nodes:[]};o=m(h),i.push(o),m({type:"open",value:p});continue}if(p===rse){if(o.type!=="brace"){m({type:"text",value:p});continue}let g="close";o=i.pop(),o.close=!0,m({type:g,value:p}),d--,o=i[i.length-1];continue}if(p===Xte&&d>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:Jte(o)}]}m({type:"comma",value:p}),o.commas++;continue}if(p===ese&&d>0&&o.commas===0){let g=o.nodes;if(d===0||g.length===0){m({type:"text",value:p});continue}if(a.type==="dot"){if(o.range=[],a.value+=p,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){g.pop();let h=g[g.length-1];h.value+=a.value+p,a=h,o.ranges--;continue}m({type:"dot",value:p});continue}m({type:"text",value:p})}do if(o=i.pop(),o.type!=="root"){o.nodes.forEach(v=>{v.nodes||(v.type==="open"&&(v.isOpen=!0),v.type==="close"&&(v.isClose=!0),v.nodes||(v.type="text"),v.invalid=!0)});let g=i[i.length-1],h=g.nodes.indexOf(o);g.nodes.splice(h,1,...o.nodes)}while(i.length>0);return m({type:"eos"}),r};aN.exports=use});var dN=O((u_e,lN)=>{"use strict";var uN=Um(),lse=QB(),dse=tN(),pse=cN(),Qs=(t,e={})=>{let s=[];if(Array.isArray(t))for(let n of t){let r=Qs.create(n,e);Array.isArray(r)?s.push(...r):s.push(r)}else s=[].concat(Qs.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(s=[...new Set(s)]),s};Qs.parse=(t,e={})=>pse(t,e);Qs.stringify=(t,e={})=>uN(typeof t=="string"?Qs.parse(t,e):t,e);Qs.compile=(t,e={})=>(typeof t=="string"&&(t=Qs.parse(t,e)),lse(t,e));Qs.expand=(t,e={})=>{typeof t=="string"&&(t=Qs.parse(t,e));let s=dse(t,e);return e.noempty===!0&&(s=s.filter(Boolean)),e.nodupes===!0&&(s=[...new Set(s)]),s};Qs.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?Qs.compile(t,e):Qs.expand(t,e);lN.exports=Qs});var pN=O((l_e,fse)=>{fse.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]});var mN=O((d_e,fN)=>{fN.exports=pN()});var gN=O((p_e,hN)=>{"use strict";var mse=require("path"),hse=mN(),gse=new Set(hse);hN.exports=t=>gse.has(mse.extname(t).slice(1).toLowerCase())});var zm=O(Me=>{"use strict";var{sep:yse}=require("path"),{platform:Cv}=process,xse=require("os");Me.EV_ALL="all";Me.EV_READY="ready";Me.EV_ADD="add";Me.EV_CHANGE="change";Me.EV_ADD_DIR="addDir";Me.EV_UNLINK="unlink";Me.EV_UNLINK_DIR="unlinkDir";Me.EV_RAW="raw";Me.EV_ERROR="error";Me.STR_DATA="data";Me.STR_END="end";Me.STR_CLOSE="close";Me.FSEVENT_CREATED="created";Me.FSEVENT_MODIFIED="modified";Me.FSEVENT_DELETED="deleted";Me.FSEVENT_MOVED="moved";Me.FSEVENT_CLONED="cloned";Me.FSEVENT_UNKNOWN="unknown";Me.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;Me.FSEVENT_TYPE_FILE="file";Me.FSEVENT_TYPE_DIRECTORY="directory";Me.FSEVENT_TYPE_SYMLINK="symlink";Me.KEY_LISTENERS="listeners";Me.KEY_ERR="errHandlers";Me.KEY_RAW="rawEmitters";Me.HANDLER_KEYS=[Me.KEY_LISTENERS,Me.KEY_ERR,Me.KEY_RAW];Me.DOT_SLASH=`.${yse}`;Me.BACK_SLASH_RE=/\\/g;Me.DOUBLE_SLASH_RE=/\/\//;Me.SLASH_OR_BACK_SLASH_RE=/[/\\]/;Me.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;Me.REPLACER_RE=/^\.[/\\]/;Me.SLASH="/";Me.SLASH_SLASH="//";Me.BRACE_START="{";Me.BANG="!";Me.ONE_DOT=".";Me.TWO_DOTS="..";Me.STAR="*";Me.GLOBSTAR="**";Me.ROOT_GLOBSTAR="/**/*";Me.SLASH_GLOBSTAR="/**";Me.DIR_SUFFIX="Dir";Me.ANYMATCH_OPTS={dot:!0};Me.STRING_TYPE="string";Me.FUNCTION_TYPE="function";Me.EMPTY_STR="";Me.EMPTY_FN=()=>{};Me.IDENTITY_FN=t=>t;Me.isWindows=Cv==="win32";Me.isMacos=Cv==="darwin";Me.isLinux=Cv==="linux";Me.isIBMi=xse.type()==="OS400"});var CN=O((m_e,vN)=>{"use strict";var zr=require("fs"),as=require("path"),{promisify:Ol}=require("util"),bse=gN(),{isWindows:Sse,isLinux:vse,EMPTY_FN:Cse,EMPTY_STR:Dse,KEY_LISTENERS:kc,KEY_ERR:Dv,KEY_RAW:Tl,HANDLER_KEYS:wse,EV_CHANGE:Vm,EV_ADD:qm,EV_ADD_DIR:Ase,EV_ERROR:xN,STR_DATA:Ese,STR_END:Rse,BRACE_START:Ise,STAR:_se}=zm(),kse="watch",Fse=Ol(zr.open),bN=Ol(zr.stat),Tse=Ol(zr.lstat),Pse=Ol(zr.close),wv=Ol(zr.realpath),Lse={lstat:Tse,stat:bN},Ev=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},Pl=(t,e,s)=>{let n=t[e];n instanceof Set||(t[e]=n=new Set([n])),n.add(s)},Ose=t=>e=>{let s=t[e];s instanceof Set?s.clear():delete t[e]},Ll=(t,e,s)=>{let n=t[e];n instanceof Set?n.delete(s):n===s&&delete t[e]},SN=t=>t instanceof Set?t.size===0:!t,Km=new Map;function yN(t,e,s,n,r){let i=(o,a)=>{s(t),r(o,a,{watchedPath:t}),a&&t!==a&&Zm(as.resolve(t,a),kc,as.join(t,a))};try{return zr.watch(t,e,i)}catch(o){n(o)}}var Zm=(t,e,s,n,r)=>{let i=Km.get(t);i&&Ev(i[e],o=>{o(s,n,r)})},Mse=(t,e,s,n)=>{let{listener:r,errHandler:i,rawEmitter:o}=n,a=Km.get(e),c;if(!s.persistent)return c=yN(t,s,r,i,o),c.close.bind(c);if(a)Pl(a,kc,r),Pl(a,Dv,i),Pl(a,Tl,o);else{if(c=yN(t,s,Zm.bind(null,e,kc),i,Zm.bind(null,e,Tl)),!c)return;c.on(xN,async u=>{let l=Zm.bind(null,e,Dv);if(a.watcherUnusable=!0,Sse&&u.code==="EPERM")try{let d=await Fse(t,"r");await Pse(d),l(u)}catch{}else l(u)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:c},Km.set(e,a)}return()=>{Ll(a,kc,r),Ll(a,Dv,i),Ll(a,Tl,o),SN(a.listeners)&&(a.watcher.close(),Km.delete(e),wse.forEach(Ose(a)),a.watcher=void 0,Object.freeze(a))}},Av=new Map,Bse=(t,e,s,n)=>{let{listener:r,rawEmitter:i}=n,o=Av.get(e),a=new Set,c=new Set,u=o&&o.options;return u&&(u.persistent<s.persistent||u.interval>s.interval)&&(a=o.listeners,c=o.rawEmitters,zr.unwatchFile(e),o=void 0),o?(Pl(o,kc,r),Pl(o,Tl,i)):(o={listeners:r,rawEmitters:i,options:s,watcher:zr.watchFile(e,s,(l,d)=>{Ev(o.rawEmitters,f=>{f(Vm,e,{curr:l,prev:d})});let p=l.mtimeMs;(l.size!==d.size||p>d.mtimeMs||p===0)&&Ev(o.listeners,f=>f(t,l))})},Av.set(e,o)),()=>{Ll(o,kc,r),Ll(o,Tl,i),SN(o.listeners)&&(Av.delete(e),zr.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},Rv=class{constructor(e){this.fsw=e,this._boundHandleError=s=>e._handleError(s)}_watchWithNodeFs(e,s){let n=this.fsw.options,r=as.dirname(e),i=as.basename(e);this.fsw._getWatchedDir(r).add(i);let a=as.resolve(e),c={persistent:n.persistent};s||(s=Cse);let u;return n.usePolling?(c.interval=n.enableBinaryInterval&&bse(i)?n.binaryInterval:n.interval,u=Bse(e,a,c,{listener:s,rawEmitter:this.fsw._emitRaw})):u=Mse(e,a,c,{listener:s,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),u}_handleFile(e,s,n){if(this.fsw.closed)return;let r=as.dirname(e),i=as.basename(e),o=this.fsw._getWatchedDir(r),a=s;if(o.has(i))return;let c=async(l,d)=>{if(this.fsw._throttle(kse,e,5)){if(!d||d.mtimeMs===0)try{let p=await bN(e);if(this.fsw.closed)return;let f=p.atimeMs,m=p.mtimeMs;(!f||f<=m||m!==a.mtimeMs)&&this.fsw._emit(Vm,e,p),vse&&a.ino!==p.ino?(this.fsw._closeFile(l),a=p,this.fsw._addPathCloser(l,this._watchWithNodeFs(e,c))):a=p}catch{this.fsw._remove(r,i)}else if(o.has(i)){let p=d.atimeMs,f=d.mtimeMs;(!p||p<=f||f!==a.mtimeMs)&&this.fsw._emit(Vm,e,d),a=d}}},u=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(qm,e,0))return;this.fsw._emit(qm,e,s)}return u}async _handleSymlink(e,s,n,r){if(this.fsw.closed)return;let i=e.fullPath,o=this.fsw._getWatchedDir(s);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await wv(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(r)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(Vm,n,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(qm,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,s,n,r,i,o,a){if(e=as.join(e,Dse),!n.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let c=this.fsw._getWatchedDir(n.path),u=new Set,l=this.fsw._readdirp(e,{fileFilter:d=>n.filterPath(d),directoryFilter:d=>n.filterDir(d),depth:0}).on(Ese,async d=>{if(this.fsw.closed){l=void 0;return}let p=d.path,f=as.join(e,p);if(u.add(p),!(d.stats.isSymbolicLink()&&await this._handleSymlink(d,e,f,p))){if(this.fsw.closed){l=void 0;return}(p===r||!r&&!c.has(p))&&(this.fsw._incrReadyCount(),f=as.join(i,as.relative(i,f)),this._addToNodeFs(f,s,n,o+1))}}).on(xN,this._boundHandleError);return new Promise(d=>l.once(Rse,()=>{if(this.fsw.closed){l=void 0;return}let p=a?a.clear():!1;d(),c.getChildren().filter(f=>f!==e&&!u.has(f)&&(!n.hasGlob||n.filterPath({fullPath:as.resolve(e,f)}))).forEach(f=>{this.fsw._remove(e,f)}),l=void 0,p&&this._handleRead(e,!1,n,r,i,o,a)}))}async _handleDir(e,s,n,r,i,o,a){let c=this.fsw._getWatchedDir(as.dirname(e)),u=c.has(as.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!u&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(Ase,e,s),c.add(as.basename(e)),this.fsw._getWatchedDir(e);let l,d,p=this.fsw.options.depth;if((p==null||r<=p)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,n,o,i,e,r,l),this.fsw.closed))return;d=this._watchWithNodeFs(e,(f,m)=>{m&&m.mtimeMs===0||this._handleRead(f,!1,o,i,e,r,l)})}return d}async _addToNodeFs(e,s,n,r,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,r);!a.hasGlob&&n&&(a.hasGlob=n.hasGlob,a.globFilter=n.globFilter,a.filterPath=c=>n.filterPath(c),a.filterDir=c=>n.filterDir(c));try{let c=await Lse[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return o(),!1;let u=this.fsw.options.followSymlinks&&!e.includes(_se)&&!e.includes(Ise),l;if(c.isDirectory()){let d=as.resolve(e),p=u?await wv(e):e;if(this.fsw.closed||(l=await this._handleDir(a.watchPath,c,s,r,i,a,p),this.fsw.closed))return;d!==p&&p!==void 0&&this.fsw._symlinkPaths.set(d,p)}else if(c.isSymbolicLink()){let d=u?await wv(e):e;if(this.fsw.closed)return;let p=as.dirname(a.watchPath);if(this.fsw._getWatchedDir(p).add(a.watchPath),this.fsw._emit(qm,a.watchPath,c),l=await this._handleDir(p,c,s,r,e,a,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(as.resolve(e),d)}else l=this._handleFile(a.watchPath,c,s);return o(),this.fsw._addPathCloser(e,l),!1}catch(c){if(this.fsw._handleError(c))return o(),e}}};vN.exports=Rv});var _N=O((h_e,Ov)=>{"use strict";var Pv=require("fs"),cs=require("path"),{promisify:Lv}=require("util"),Fc;try{Fc=require("fsevents")}catch(t){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(t)}if(Fc){let t=process.version.match(/v(\d+)\.(\d+)/);if(t&&t[1]&&t[2]){let e=Number.parseInt(t[1],10),s=Number.parseInt(t[2],10);e===8&&s<16&&(Fc=void 0)}}var{EV_ADD:Iv,EV_CHANGE:Nse,EV_ADD_DIR:DN,EV_UNLINK:Ym,EV_ERROR:$se,STR_DATA:Wse,STR_END:jse,FSEVENT_CREATED:Use,FSEVENT_MODIFIED:Hse,FSEVENT_DELETED:Gse,FSEVENT_MOVED:zse,FSEVENT_UNKNOWN:qse,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:Vse,FSEVENT_TYPE_FILE:Kse,FSEVENT_TYPE_DIRECTORY:Ml,FSEVENT_TYPE_SYMLINK:IN,ROOT_GLOBSTAR:wN,DIR_SUFFIX:Zse,DOT_SLASH:AN,FUNCTION_TYPE:_v,EMPTY_FN:Yse,IDENTITY_FN:Jse}=zm(),Qse=t=>isNaN(t)?{}:{depth:t},Fv=Lv(Pv.stat),Xse=Lv(Pv.lstat),EN=Lv(Pv.realpath),ene={stat:Fv,lstat:Xse},Xo=new Map,tne=10,sne=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),nne=(t,e)=>({stop:Fc.watch(t,e)});function rne(t,e,s,n){let r=cs.extname(e)?cs.dirname(e):e,i=cs.dirname(r),o=Xo.get(r);ine(i)&&(r=i);let a=cs.resolve(t),c=a!==e,u=(d,p,f)=>{c&&(d=d.replace(e,a)),(d===a||!d.indexOf(a+cs.sep))&&s(d,p,f)},l=!1;for(let d of Xo.keys())if(e.indexOf(cs.resolve(d)+cs.sep)===0){r=d,o=Xo.get(r),l=!0;break}return o||l?o.listeners.add(u):(o={listeners:new Set([u]),rawEmitter:n,watcher:nne(r,(d,p)=>{if(!o.listeners.size||p&Vse)return;let f=Fc.getInfo(d,p);o.listeners.forEach(m=>{m(d,p,f)}),o.rawEmitter(f.event,d,f)})},Xo.set(r,o)),()=>{let d=o.listeners;if(d.delete(u),!d.size&&(Xo.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var ine=t=>{let e=0;for(let s of Xo.keys())if(s.indexOf(t)===0&&(e++,e>=tne))return!0;return!1},one=()=>Fc&&Xo.size<128,kv=(t,e)=>{let s=0;for(;!t.indexOf(e)&&(t=cs.dirname(t))!==e;)s++;return s},RN=(t,e)=>t.type===Ml&&e.isDirectory()||t.type===IN&&e.isSymbolicLink()||t.type===Kse&&e.isFile(),Tv=class{constructor(e){this.fsw=e}checkIgnored(e,s){let n=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,s))return n.add(e),s&&s.isDirectory()&&n.add(e+wN),!0;n.delete(e),n.delete(e+wN)}addOrChange(e,s,n,r,i,o,a,c){let u=i.has(o)?Nse:Iv;this.handleEvent(u,e,s,n,r,i,o,a,c)}async checkExists(e,s,n,r,i,o,a,c){try{let u=await Fv(e);if(this.fsw.closed)return;RN(a,u)?this.addOrChange(e,s,n,r,i,o,a,c):this.handleEvent(Ym,e,s,n,r,i,o,a,c)}catch(u){u.code==="EACCES"?this.addOrChange(e,s,n,r,i,o,a,c):this.handleEvent(Ym,e,s,n,r,i,o,a,c)}}handleEvent(e,s,n,r,i,o,a,c,u){if(!(this.fsw.closed||this.checkIgnored(s)))if(e===Ym){let l=c.type===Ml;(l||o.has(a))&&this.fsw._remove(i,a,l)}else{if(e===Iv){if(c.type===Ml&&this.fsw._getWatchedDir(s),c.type===IN&&u.followSymlinks){let d=u.depth===void 0?void 0:kv(n,r)+1;return this._addToFsEvents(s,!1,!0,d)}this.fsw._getWatchedDir(i).add(a)}let l=c.type===Ml?e+Zse:e;this.fsw._emit(l,s),l===DN&&this._addToFsEvents(s,!1,!0)}}_watchWithFsEvents(e,s,n,r){if(this.fsw.closed||this.fsw._isIgnored(e))return;let i=this.fsw.options,a=rne(e,s,async(c,u,l)=>{if(this.fsw.closed||i.depth!==void 0&&kv(c,s)>i.depth)return;let d=n(cs.join(e,cs.relative(e,c)));if(r&&!r(d))return;let p=cs.dirname(d),f=cs.basename(d),m=this.fsw._getWatchedDir(l.type===Ml?d:p);if(sne.has(u)||l.event===qse)if(typeof i.ignored===_v){let g;try{g=await Fv(d)}catch{}if(this.fsw.closed||this.checkIgnored(d,g))return;RN(l,g)?this.addOrChange(d,c,s,p,m,f,l,i):this.handleEvent(Ym,d,c,s,p,m,f,l,i)}else this.checkExists(d,c,s,p,m,f,l,i);else switch(l.event){case Use:case Hse:return this.addOrChange(d,c,s,p,m,f,l,i);case Gse:case zse:return this.checkExists(d,c,s,p,m,f,l,i)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,s,n,r){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(s))){this.fsw._symlinkPaths.set(s,!0),this.fsw._incrReadyCount();try{let i=await EN(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(i))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(i||e,o=>{let a=e;return i&&i!==AN?a=o.replace(i,e):o!==AN&&(a=cs.join(e,o)),n(a)},!1,r)}catch(i){if(this.fsw._handleError(i))return this.fsw._emitReady()}}}emitAdd(e,s,n,r,i){let o=n(e),a=s.isDirectory(),c=this.fsw._getWatchedDir(cs.dirname(o)),u=cs.basename(o);a&&this.fsw._getWatchedDir(o),!c.has(u)&&(c.add(u),(!r.ignoreInitial||i===!0)&&this.fsw._emit(a?DN:Iv,o,s))}initWatch(e,s,n,r){if(this.fsw.closed)return;let i=this._watchWithFsEvents(n.watchPath,cs.resolve(e||n.watchPath),r,n.globFilter);this.fsw._addPathCloser(s,i)}async _addToFsEvents(e,s,n,r){if(this.fsw.closed)return;let i=this.fsw.options,o=typeof s===_v?s:Jse,a=this.fsw._getWatchHelpers(e);try{let c=await ene[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))throw null;if(c.isDirectory()){if(a.globFilter||this.emitAdd(o(e),c,o,i,n),r&&r>i.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:u=>a.filterPath(u),directoryFilter:u=>a.filterDir(u),...Qse(i.depth-(r||0))}).on(Wse,u=>{if(this.fsw.closed||u.stats.isDirectory()&&!a.filterPath(u))return;let l=cs.join(a.watchPath,u.path),{fullPath:d}=u;if(a.followSymlinks&&u.stats.isSymbolicLink()){let p=i.depth===void 0?void 0:kv(l,cs.resolve(a.watchPath))+1;this._handleFsEventsSymlink(l,d,o,p)}else this.emitAdd(l,u.stats,o,i,n)}).on($se,Yse).on(jse,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,c,o,i,n),this.fsw._emitReady()}catch(c){(!c||this.fsw._handleError(c))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(i.persistent&&n!==!0)if(typeof s===_v)this.initWatch(void 0,e,a,o);else{let c;try{c=await EN(a.watchPath)}catch{}this.initWatch(c,e,a,o)}}};Ov.exports=Tv;Ov.exports.canUse=one});var WN=O(Yv=>{"use strict";var{EventEmitter:ane}=require("events"),Kv=require("fs"),St=require("path"),{promisify:MN}=require("util"),cne=KM(),jv=DB().default,une=_B(),Mv=hv(),lne=dN(),dne=fv(),pne=CN(),kN=_N(),{EV_ALL:Bv,EV_READY:fne,EV_ADD:Jm,EV_CHANGE:Bl,EV_UNLINK:FN,EV_ADD_DIR:mne,EV_UNLINK_DIR:hne,EV_RAW:gne,EV_ERROR:Nv,STR_CLOSE:yne,STR_END:xne,BACK_SLASH_RE:bne,DOUBLE_SLASH_RE:TN,SLASH_OR_BACK_SLASH_RE:Sne,DOT_RE:vne,REPLACER_RE:Cne,SLASH:$v,SLASH_SLASH:Dne,BRACE_START:wne,BANG:Uv,ONE_DOT:BN,TWO_DOTS:Ane,GLOBSTAR:Ene,SLASH_GLOBSTAR:Wv,ANYMATCH_OPTS:Hv,STRING_TYPE:Zv,FUNCTION_TYPE:Rne,EMPTY_STR:Gv,EMPTY_FN:Ine,isWindows:_ne,isMacos:kne,isIBMi:Fne}=zm(),Tne=MN(Kv.stat),Pne=MN(Kv.readdir),zv=(t=[])=>Array.isArray(t)?t:[t],NN=(t,e=[])=>(t.forEach(s=>{Array.isArray(s)?NN(s,e):e.push(s)}),e),PN=t=>{let e=NN(zv(t));if(!e.every(s=>typeof s===Zv))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map($N)},LN=t=>{let e=t.replace(bne,$v),s=!1;for(e.startsWith(Dne)&&(s=!0);e.match(TN);)e=e.replace(TN,$v);return s&&(e=$v+e),e},$N=t=>LN(St.normalize(LN(t))),ON=(t=Gv)=>e=>typeof e!==Zv?e:$N(St.isAbsolute(e)?e:St.join(t,e)),Lne=(t,e)=>St.isAbsolute(t)?t:t.startsWith(Uv)?Uv+St.join(e,t.slice(1)):St.join(e,t),Vn=(t,e)=>t[e]===void 0,qv=class{constructor(e,s){this.path=e,this._removeWatcher=s,this.items=new Set}add(e){let{items:s}=this;s&&e!==BN&&e!==Ane&&s.add(e)}async remove(e){let{items:s}=this;if(!s||(s.delete(e),s.size>0))return;let n=this.path;try{await Pne(n)}catch{this._removeWatcher&&this._removeWatcher(St.dirname(n),St.basename(n))}}has(e){let{items:s}=this;if(s)return s.has(e)}getChildren(){let{items:e}=this;if(e)return[...e.values()]}dispose(){this.items.clear(),delete this.path,delete this._removeWatcher,delete this.items,Object.freeze(this)}},One="stat",Mne="lstat",Vv=class{constructor(e,s,n,r){this.fsw=r,this.path=e=e.replace(Cne,Gv),this.watchPath=s,this.fullWatchPath=St.resolve(s),this.hasGlob=s!==e,e===Gv&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&n?void 0:!1,this.globFilter=this.hasGlob?jv(e,void 0,Hv):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=n,this.statMethod=n?One:Mne}checkGlobSymlink(e){return this.globSymlink===void 0&&(this.globSymlink=e.fullParentDir===this.fullWatchPath?!1:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}),this.globSymlink?e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath):e.fullPath}entryPath(e){return St.join(this.watchPath,St.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:s}=e;if(s&&s.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===Rne?this.globFilter(n):!0)&&this.fsw._isntIgnored(n,s)&&this.fsw._hasReadPermissions(s)}getDirParts(e){if(!this.hasGlob)return[];let s=[];return(e.includes(wne)?lne.expand(e):[e]).forEach(r=>{s.push(St.relative(this.watchPath,r).split(Sne))}),s}filterDir(e){if(this.hasGlob){let s=this.getDirParts(this.checkGlobSymlink(e)),n=!1;this.unmatchedGlob=!this.dirParts.some(r=>r.every((i,o)=>(i===Ene&&(n=!0),n||!s[0][o]||jv(i,s[0][o],Hv))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Qm=class extends ane{constructor(e){super();let s={};e&&Object.assign(s,e),this._watched=new Map,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._symlinkPaths=new Map,this._streams=new Set,this.closed=!1,Vn(s,"persistent")&&(s.persistent=!0),Vn(s,"ignoreInitial")&&(s.ignoreInitial=!1),Vn(s,"ignorePermissionErrors")&&(s.ignorePermissionErrors=!1),Vn(s,"interval")&&(s.interval=100),Vn(s,"binaryInterval")&&(s.binaryInterval=300),Vn(s,"disableGlobbing")&&(s.disableGlobbing=!1),s.enableBinaryInterval=s.binaryInterval!==s.interval,Vn(s,"useFsEvents")&&(s.useFsEvents=!s.usePolling),kN.canUse()||(s.useFsEvents=!1),Vn(s,"usePolling")&&!s.useFsEvents&&(s.usePolling=kne),Fne&&(s.usePolling=!0);let r=process.env.CHOKIDAR_USEPOLLING;if(r!==void 0){let c=r.toLowerCase();c==="false"||c==="0"?s.usePolling=!1:c==="true"||c==="1"?s.usePolling=!0:s.usePolling=!!c}let i=process.env.CHOKIDAR_INTERVAL;i&&(s.interval=Number.parseInt(i,10)),Vn(s,"atomic")&&(s.atomic=!s.usePolling&&!s.useFsEvents),s.atomic&&(this._pendingUnlinks=new Map),Vn(s,"followSymlinks")&&(s.followSymlinks=!0),Vn(s,"awaitWriteFinish")&&(s.awaitWriteFinish=!1),s.awaitWriteFinish===!0&&(s.awaitWriteFinish={});let o=s.awaitWriteFinish;o&&(o.stabilityThreshold||(o.stabilityThreshold=2e3),o.pollInterval||(o.pollInterval=100),this._pendingWrites=new Map),s.ignored&&(s.ignored=zv(s.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Ine,this._readyEmitted=!0,process.nextTick(()=>this.emit(fne)))},this._emitRaw=(...c)=>this.emit(gne,...c),this._readyEmitted=!1,this.options=s,s.useFsEvents?this._fsEventsHandler=new kN(this):this._nodeFsHandler=new pne(this),Object.freeze(s)}add(e,s,n){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=PN(e);return r&&(o=o.map(a=>{let c=Lne(a,r);return i||!Mv(a)?c:dne(c)})),o=o.filter(a=>a.startsWith(Uv)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+Wv),this._userIgnored=void 0,!0)),this.options.useFsEvents&&this._fsEventsHandler?(this._readyCount||(this._readyCount=o.length),this.options.persistent&&(this._readyCount+=o.length),o.forEach(a=>this._fsEventsHandler._addToFsEvents(a))):(this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!n,0,0,s);return c&&this._emitReady(),c})).then(a=>{this.closed||a.filter(c=>c).forEach(c=>{this.add(St.dirname(c),St.basename(s||c))})})),this}unwatch(e){if(this.closed)return this;let s=PN(e),{cwd:n}=this.options;return s.forEach(r=>{!St.isAbsolute(r)&&!this._closers.has(r)&&(n&&(r=St.join(n,r)),r=St.resolve(r)),this._closePath(r),this._ignoredPaths.add(r),this._watched.has(r)&&this._ignoredPaths.add(r+Wv),this._userIgnored=void 0}),this}close(){if(this.closed)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(s=>s.forEach(n=>{let r=n();r instanceof Promise&&e.push(r)})),this._streams.forEach(s=>s.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(s=>s.dispose()),["closers","watched","streams","symlinkPaths","throttled"].forEach(s=>{this[`_${s}`].clear()}),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((s,n)=>{let r=this.options.cwd?St.relative(this.options.cwd,n):n;e[r||BN]=s.getChildren().sort()}),e}emitWithAll(e,s){this.emit(...s),e!==Nv&&this.emit(Bv,...s)}async _emit(e,s,n,r,i){if(this.closed)return;let o=this.options;_ne&&(s=St.normalize(s)),o.cwd&&(s=St.relative(o.cwd,s));let a=[e,s];i!==void 0?a.push(n,r,i):r!==void 0?a.push(n,r):n!==void 0&&a.push(n);let c=o.awaitWriteFinish,u;if(c&&(u=this._pendingWrites.get(s)))return u.lastChange=new Date,this;if(o.atomic){if(e===FN)return this._pendingUnlinks.set(s,a),setTimeout(()=>{this._pendingUnlinks.forEach((l,d)=>{this.emit(...l),this.emit(Bv,...l),this._pendingUnlinks.delete(d)})},typeof o.atomic=="number"?o.atomic:100),this;e===Jm&&this._pendingUnlinks.has(s)&&(e=a[0]=Bl,this._pendingUnlinks.delete(s))}if(c&&(e===Jm||e===Bl)&&this._readyEmitted){let l=(d,p)=>{d?(e=a[0]=Nv,a[1]=d,this.emitWithAll(e,a)):p&&(a.length>2?a[2]=p:a.push(p),this.emitWithAll(e,a))};return this._awaitWriteFinish(s,c.stabilityThreshold,e,l),this}if(e===Bl&&!this._throttle(Bl,s,50))return this;if(o.alwaysStat&&n===void 0&&(e===Jm||e===mne||e===Bl)){let l=o.cwd?St.join(o.cwd,s):s,d;try{d=await Tne(l)}catch{}if(!d||this.closed)return;a.push(d)}return this.emitWithAll(e,a),this}_handleError(e){let s=e&&e.code;return e&&s!=="ENOENT"&&s!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||s!=="EPERM"&&s!=="EACCES")&&this.emit(Nv,e),e||this.closed}_throttle(e,s,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e),i=r.get(s);if(i)return i.count++,!1;let o,a=()=>{let u=r.get(s),l=u?u.count:0;return r.delete(s),clearTimeout(o),u&&clearTimeout(u.timeoutObject),l};o=setTimeout(a,n);let c={timeoutObject:o,clear:a,count:0};return r.set(s,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,s,n,r){let i,o=e;this.options.cwd&&!St.isAbsolute(e)&&(o=St.join(this.options.cwd,e));let a=new Date,c=u=>{Kv.stat(o,(l,d)=>{if(l||!this._pendingWrites.has(e)){l&&l.code!=="ENOENT"&&r(l);return}let p=Number(new Date);u&&d.size!==u.size&&(this._pendingWrites.get(e).lastChange=p);let f=this._pendingWrites.get(e);p-f.lastChange>=s?(this._pendingWrites.delete(e),r(void 0,d)):i=setTimeout(c,this.options.awaitWriteFinish.pollInterval,d)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(i),n)}),i=setTimeout(c,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,s){if(this.options.atomic&&vne.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,r=this.options.ignored,i=r&&r.map(ON(n)),o=zv(i).filter(c=>typeof c===Zv&&!Mv(c)).map(c=>c+Wv),a=this._getGlobIgnored().map(ON(n)).concat(i,o);this._userIgnored=jv(a,void 0,Hv)}return this._userIgnored([e,s])}_isntIgnored(e,s){return!this._isIgnored(e,s)}_getWatchHelpers(e,s){let n=s||this.options.disableGlobbing||!Mv(e)?e:une(e),r=this.options.followSymlinks;return new Vv(e,n,r,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let s=St.resolve(e);return this._watched.has(s)||this._watched.set(s,new qv(s,this._boundRemove)),this._watched.get(s)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let n=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(n.toString(8)[0],10))}_remove(e,s,n){let r=St.join(e,s),i=St.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!n&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,s,!0),this._getWatchedDir(r).getChildren().forEach(p=>this._remove(r,p));let c=this._getWatchedDir(e),u=c.has(s);c.remove(s),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let l=r;if(this.options.cwd&&(l=St.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(l)&&this._pendingWrites.get(l).cancelWait()===Jm)return;this._watched.delete(r),this._watched.delete(i);let d=n?hne:FN;u&&!this._isIgnored(r)&&this._emit(d,r),this.options.useFsEvents||this._closePath(r)}_closePath(e){this._closeFile(e);let s=St.dirname(e);this._getWatchedDir(s).remove(St.basename(e))}_closeFile(e){let s=this._closers.get(e);s&&(s.forEach(n=>n()),this._closers.delete(e))}_addPathCloser(e,s){if(!s)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(s)}_readdirp(e,s){if(this.closed)return;let n={type:Bv,alwaysStat:!0,lstat:!0,...s},r=cne(e,n);return this._streams.add(r),r.once(yne,()=>{r=void 0}),r.once(xne,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};Yv.FSWatcher=Qm;var Bne=(t,e)=>{let s=new Qm(e);return s.add(t),s};Yv.watch=Bne});var UN,fr,Nne,$ne,jN,Wne,HN,GN=D(()=>{"use strict";UN=oe(require("node:fs")),fr=oe(require("node:path")),Nne=["**/.*","**/.*/**","**/node_modules/**"],$ne="cdk.out",jN=t=>t===void 0?[]:Array.isArray(t)?t:[t],Wne=t=>{try{let e=UN.readFileSync(t,"utf-8");return JSON.parse(e)??{}}catch{return{}}},HN=(t=process.cwd())=>{let e=t,s=Wne(fr.join(e,"cdk.json")),n=jN(s.watch?.include),r=jN(s.watch?.exclude),i=s.output??$ne,o=n.length>0?n:[e],a=[...r,...Nne],c=fr.relative(e,fr.resolve(e,i));return c.length>0&&!c.startsWith(`..${fr.sep}`)&&!fr.isAbsolute(c)&&a.push(`${c}/**`),{include:o,exclude:a,rootDir:e}}});var VN={};ah(VN,{runWatchLoop:()=>Hne});var zN,qN,jne,Une,Hne,KN=D(()=>{"use strict";zN=oe(require("node:path")),qN=oe(WN());GN();Pf();$r();Qv();jne=300,Une=t=>({...t,local:!0,github:!1,withIssue:!1,prComment:!1,writeBaseline:!1,diff:!1,failOnCritical:!1,output:"table",format:"table"}),Hne=async t=>{let e=Une(t.config),{include:s,exclude:n,rootDir:r}=HN(),i=null,o=!1,a=!1,c=e.stackName==="All stacks"?void 0:e.stackName,u=async d=>{if(o){a=!0;return}o=!0;try{if(console.clear(),T.info(`\u{1F504} ${d}`),!Tf(c)){T.error("Synth failed \u2014 keeping last good results. Fix the error and save again.");return}await Jv(e,t.fingerprint,t.authToken,t.licenseInfo,t.usageData,t.project,t.licenseKey,!0),T.success(`\u2713 Done at ${new Date().toLocaleTimeString()}`)}catch(p){T.error(p instanceof Error?p.message:String(p))}finally{o=!1,a&&(a=!1,u("Re-running for change(s) received during last run"))}};T.info(`\u{1F440} Watch mode \u2014 watching ${s.length} include pattern(s) under ${r}`),T.comment(" AI analysis disabled in watch mode. Press Ctrl+C to exit.");let l=qN.default.watch(s,{cwd:r,ignored:n,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});await u("Initial scan"),l.on("all",(d,p)=>{i&&clearTimeout(i),i=setTimeout(()=>{let f=zN.relative(r,p)||p;u(`${d} ${f}`)},jne)}),l.on("error",d=>{T.error(`Watcher error: ${d instanceof Error?d.message:String(d)}`)}),await new Promise(d=>{let p=()=>{T.info(`
|
|
452
|
-
\u{1F44B} Stopping watcher.`),l.close().then(()=>d())};process.once("SIGINT",p),process.once("SIGTERM",p)})}});async function zne(t,e){let s=t.all?"All stacks":t.stackName||"All stacks",n=await bi({message:"Which stack would you like to analyze?",default:s,choices:e.map(c=>({name:c,value:c}))}),r=t.output||t.format||"table",i=await bi({message:"Choose output format:",choices:[{name:"\u{1F4CA} Table (default) - Human-readable table with colors",value:"table"},{name:"\u{1F4C4} Markdown - GitHub-compatible markdown report",value:"markdown"},{name:"\u{1F527} JSON - Structured data for CI/CD integration",value:"json"},{name:"\u{1F4CB} Summary - Brief overview with counts",value:"summary"}],default:r}),o=t.services&&t.services.length>0?t.services:["All services"],a=await Ey({message:"Which AWS services would you like to analyze? (Use <space> to toggle, <enter> to confirm)",choices:[{name:"\u{1F50D} All services (recommended)",value:"All services",checked:o.includes("All services")},{name:"\u{1F510} IAM - Identity and Access Management",value:"IAM",checked:o.includes("IAM")},{name:"\u{1F4E6} S3 - Simple Storage Service",value:"S3",checked:o.includes("S3")},{name:"\u26A1 Lambda - Serverless Functions",value:"Lambda",checked:o.includes("Lambda")},{name:"\u{1F5C4}\uFE0F DynamoDB - NoSQL Database",value:"DynamoDB",checked:o.includes("DynamoDB")},{name:"\u{1F5C4}\uFE0F RDS - Relational Database",value:"RDS",checked:o.includes("RDS")},{name:"\u{1F5A5}\uFE0F EC2 - Virtual Machines",value:"EC2",checked:o.includes("EC2")},{name:"\u{1F4E2} SNS - Simple Notification Service",value:"SNS",checked:o.includes("SNS")},{name:"\u{1F4E8} SQS - Simple Queue Service",value:"SQS",checked:o.includes("SQS")},{name:"\u{1F504} Step Functions - Workflow Orchestration",value:"StepFunctions",checked:o.includes("StepFunctions")},{name:"\u{1F4DD} CloudTrail - API Logging",value:"CloudTrail",checked:o.includes("CloudTrail")},{name:"\u{1F310} API Gateway - REST APIs",value:"ApiGateway",checked:o.includes("ApiGateway")},{name:"\u{1F511} Secrets Manager - Secret Management",value:"SecretsManager",checked:o.includes("SecretsManager")},{name:"\u{1F510} KMS - Key Management",value:"KMS",checked:o.includes("KMS")},{name:"\u{1F4E1} EventBridge - Event Routing",value:"EventBridge",checked:o.includes("EventBridge")},{name:"\u{1F310} CloudFront - Content Delivery Network",value:"CloudFront",checked:o.includes("CloudFront")},{name:"\u2696\uFE0F ELB - Elastic Load Balancing",value:"ELB",checked:o.includes("ELB")},{name:"\u{1F433} ECS - Elastic Container Service",value:"ECS",checked:o.includes("ECS")},{name:"\u{1F464} Cognito - User Authentication",value:"Cognito",checked:o.includes("Cognito")},{name:"\u{1F6E1}\uFE0F WAF - Web Application Firewall",value:"WAF",checked:o.includes("WAF")},{name:"\u{1F4CA} CloudWatch - Monitoring & Logging",value:"CloudWatch",checked:o.includes("CloudWatch")},{name:"\u{1F30D} Route53 - DNS Management",value:"Route53",checked:o.includes("Route53")},{name:"\u26A1 ElastiCache - In-Memory Caching",value:"ElastiCache",checked:o.includes("ElastiCache")},{name:"\u{1F4E6} ECR - Container Registry",value:"ECR",checked:o.includes("ECR")},{name:"\u{1F50E} OpenSearch - Search & Analytics",value:"OpenSearch",checked:o.includes("OpenSearch")},{name:"\u{1F50F} ACM - Certificate Manager",value:"ACM",checked:o.includes("ACM")},{name:"\u{1F4BE} Backup - Backup Management",value:"Backup",checked:o.includes("Backup")},{name:"\u{1F517} VPC - Virtual Private Cloud",value:"VPC",checked:o.includes("VPC")},{name:"\u{1F30A} Kinesis - Real-time Streaming",value:"Kinesis",checked:o.includes("Kinesis")},{name:"\u{1F4F1} AppSync - GraphQL APIs",value:"AppSync",checked:o.includes("AppSync")},{name:"\u2638\uFE0F EKS - Kubernetes Service",value:"EKS",checked:o.includes("EKS")},{name:"\u{1F4C8} Redshift - Data Warehouse",value:"Redshift",checked:o.includes("Redshift")},{name:"\u{1F4EC} MSK - Managed Kafka",value:"MSK",checked:o.includes("MSK")},{name:"\u{1F9EA} Glue - ETL & Data Catalog",value:"Glue",checked:o.includes("Glue")}]});return{stackName:n,output:i,services:a}}async function Jv(t,e,s,n,r,i,o,a,c,u,l,d){let{stackName:p,output:f,services:m,withIssue:g,ruleFilter:h,failOnCritical:v}=t,x=p==="All stacks"?void 0:p,{stacks:S,inlineFindings:w,pathToLogicalId:E,recommendationMapPerStack:P,assetSourcePaths:k,acknowledgementsPerStack:A,cdkVersion:M,supportsBoxTraces:z,cdkContext:C,resourceIdMetadata:U}=jf(x),_=Object.keys(S).length;T.success(`Synthesis complete. Found ${_} stack${_===1?"":"s"} to analyze.`),M&&!z&&T.info(`Detected aws-cdk-lib ${M}. Upgrade to >= 2.252.0 for per-property source locations on deferred values.`);let Y=Object.values(S).reduce((xe,ge)=>{let L=Object.entries(ge.Resources||{}).filter(([,ae])=>!ae.Type.startsWith("AWS::CDK::"));return xe+L.length},0);Y>0?T.info(`\u{1F50D} Preparing to analyze ${Y} total resources across ${_} stacks...`):T.warning("No user resources found in stacks. Make sure your CDK app is properly configured.");let y=null,b=!!s;if(a&&(b=!1,T.info("\u{1F3E0} Running in local mode - static analysis only")),o&&!a){T.info("\u{1F50D} Checking license quota...");let xe=n.licenseType==="FREE"||n.status==="TRIAL",ge=n.totalResourcesAnalyzed||0,L=n.trialUsageLimit||n.maxUsage||200,ae=Number.isNaN(ge)?0:ge,W=Number.isNaN(L)?200:L;if(xe&&ae>=W)b=!1,y={canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,quota:{currentResourcesAnalyzed:ae,maxResources:W,remainingResources:Math.max(0,W-ae),isTrial:!0,trialExpired:!1},reason:`Trial AI credit allowance exceeded (${ae}/${W} used)`,upgradePath:"https://cdkinsights.dev/pricing"},T.warning("\u26A0\uFE0F Trial AI credit allowance exceeded \u2014 falling back to static scans only"),T.comment(" Upgrade to Pro for 5,000 AI credits per month");else if(y=await eM({licenseKey:o,requestedResources:Y,allowOveruse:t.allowOveruse,usageData:r,licenseInfo:n}),b=!!s&&(y?.canRunAIAnalysis??!0),y?.quota?.isTrial){let ue=y.quota.currentResourcesAnalyzed,De=y.quota.maxResources;ue>=De&&(y={...y,canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,reason:`Trial AI credit allowance exceeded (${ue}/${De} used) \u2014 falling back to static scans only`},b=!1)}y?.quota?.isTrial&&T.displayTrialStatus({currentResourcesAnalyzed:y.quota.currentResourcesAnalyzed,maxResources:y.quota.maxResources,remainingResources:y.quota.remainingResources,isTrial:y.quota.isTrial,trialExpired:y.quota.trialExpired,trialStart:n.trialStart,trialEnd:n.trialEnd,tier:n.tier}),!b&&y?.quota?T.displayQuotaWarning({currentResourcesAnalyzed:y.quota.currentResourcesAnalyzed,maxResources:y.quota.maxResources,requestedResources:Y,remainingResources:y.quota.remainingResources,isTrial:y.quota.isTrial}):b&&o&&T.success("AI analysis enabled - you'll receive comprehensive recommendations")}let K=wp(t.services),q=K.services;K.removedAllServices?re.debug(`Services normalization: removed "All services", using: ${q.join(", ")}`):K.defaultedToAll&&re.debug('Services normalization: defaulting to "All services"');let te=c||{},X=t.warnSensitive||te.warnOnly||!1,ee=(()=>{let xe=C?.["cdkInsights:aiModel"];return typeof xe=="string"?xe:void 0})(),fe=dM({flag:t.model,cdkContext:ee,userConfig:typeof t.ai?.model=="string"?t.ai?.model:void 0,tier:n?.tier});fe.downgradedFromTierGate?T.warning(`\u26A0\uFE0F Requested AI model "${fe.requestedAlias}" is not available on your tier \u2014 using "${fe.alias}" instead.`):fe.source!=="tierDefault"&&T.comment(`\u{1F916} AI model: ${fe.alias} (from ${fe.source})`);let Re=t.ai?.batchSize,se=typeof Re=="number"&&Number.isFinite(Re)?Math.max(1,Math.floor(Re)):void 0;se&&se>1&&T.comment(`\u{1F9FA} AI batching: ${se} resources per call`);let Ce={stacks:S,inlineFindings:w,pathToLogicalId:E,recommendationMapPerStack:P,assetSourcePaths:k,acknowledgementsPerStack:A,output:JN(t),services:q,withIssue:t.withIssue,ruleFilter:t.ruleFilter||[],ignoreRules:t.ignoreRules||[],ignorePaths:t.ignorePaths||[],failOnCritical:t.failOnCritical,authToken:s,fingerprint:e,tier:n?.tier,quotaValidation:y||null,noCache:t.noCache||!1,cache:{enabled:t.cache?.enabled??!0,ttl:t.cache?.ttl??3e5,maxSize:t.cache?.maxSize??5e3},allowOveruse:t.allowOveruse||!1,warnSensitive:X,sensitiveDataDetection:{disabled:te.enabled===!1,ignoreProperties:te.ignoreProperties||[],allowPatterns:te.allowPatterns||[],strictMode:te.strictMode||!1},cdkContext:C,resourceIdMetadata:U,aiModelId:fe.bedrockModelId,aiBatchSize:se,forceLocal:a,baselineExclude:u,collectFingerprints:l,skipRendering:d};return{...await Am(Ce),totalResources:Y}}var ZN,YN,Gne,JN,QN,Qv=D(()=>{"use strict";ZN=oe(require("node:fs")),YN=oe(require("node:path"));Kx();Jn();Kd();Bk();Qx();Wk();Zk();Pf();za();KF();kb();BS();X4();qa();Y0();Zd();tM();tb();lt();rM();aM();US();$r();pM();hM();Cl();Gne=()=>{let t=YN.resolve(process.cwd(),"cdk.out");return ZN.existsSync(t)},JN=t=>t.summaryOnly?"summary":t.format==="json"||t.output==="json"?"json":t.format==="markdown"||t.output==="markdown"?"markdown":t.format==="summary"||t.output==="summary"?"summary":t.format==="sarif"||t.output==="sarif"?"sarif":t.format==="github-actions"||t.output==="github-actions"?"github-actions":"table";QN={command:"scan [stackName]",describe:"Scan CDK stacks for best practices and security issues",builder:t=>t.positional("stackName",{type:"string",describe:"Name of the stack to analyze"}).option("ci",{type:"boolean",default:!1}).option("withIssue",{type:"boolean",description:"Create GitHub issues from findings?"}).option("output",{alias:"o",type:"string",choices:["json","table","markdown","summary","sarif","github-actions"]}).option("all",{type:"boolean",description:"Analyze all CDK stacks,",default:!1}).option("services",{type:"array",string:!0,description:"Only run checks for these services (e.g. IAM, S3, Lambda)"}).option("format",{type:"string",choices:["json","table","markdown","summary","sarif","github-actions"],describe:"Alias for --output (preferred)"}).option("yes",{type:"boolean",description:"Skip prompts and use saved/default values,",default:!1,alias:"y"}).option("reset",{type:"boolean",description:"Clear saved config and start fresh"}).option("redact",{type:"boolean",description:"Redact sensitive resource names in output",default:!1}).option("summaryOnly",{type:"boolean",description:"Only show summary in console output",default:!1}).option("synth",{type:"boolean",description:"Run cdk synth before analysis",default:!1}).option("watch",{type:"boolean",description:"Watch CDK files and re-run static analysis on save. AI, baseline writes, GitHub issues, PR comments and scan history are disabled in watch mode. Reuses cdk.json `watch.include` / `watch.exclude` (same as `cdk watch`).",default:!1}).option("failOnCritical",{type:"boolean",description:"Exit with code 1 if critical issues are found (defaults to true)",default:!0}).option("ruleFilter",{type:"array",string:!0,describe:"Filter findings to only include matching rule IDs or categories (e.g. AwsSolutions-IAM4, Security)"}).option("github",{describe:"Create GitHub issues for findings,",type:"boolean",default:!1}).option("noCache",{describe:"Disable cache and force fresh analysis",type:"boolean",default:!1}).option("allowOveruse",{describe:"Allow AI analysis even when exceeding paid allowance (extra usage will be charged)",type:"boolean",default:!1}).option("local",{describe:"Run static analysis only (skip AI analysis even with a valid license)",type:"boolean",default:!1}).option("warnSensitive",{describe:"Treat sensitive data as warning instead of critical (will not fail CI)",type:"boolean",default:!1}).option("prComment",{describe:"Post analysis summary as a PR comment (GitHub Actions only)",type:"boolean",default:!1}).option("model",{describe:"AI model alias for analysis (e.g. nova-lite, mistral-14b, llama-3-3-70b). Overrides cdk.json and user config. Tier-gated.",type:"string"}).option("diff",{describe:"Only show findings new since the saved baseline (.cdk-insights-baseline.json). Existing findings still appear in summaries but never fail CI.",type:"boolean",default:!1}).option("writeBaseline",{describe:"Write the current findings to .cdk-insights-baseline.json (or --baseline path) and exit 0 regardless of severity. Skips findings rendering.",type:"boolean",default:!1}).option("baseline",{describe:"Path to the baseline file. Defaults to .cdk-insights-baseline.json in cwd. Used by both --diff and --writeBaseline.",type:"string"}),handler:async t=>{try{let e=t.output||t.format;if((e==="json"||e==="sarif")&&(process.env.CDK_INSIGHTS_QUIET_STDOUT="1"),t.reset){km(),re.info("\u{1F5D1}\uFE0F Cleared saved CLI preferences.");return}let s=Nu(),n=s.fingerprint,r=s.project;(!n||n.length===0)&&(T.error("Failed to generate system fingerprint for authentication."),T.comment(" This may indicate a permissions issue with reading system information."),process.exit(1));let i=process.env.CDK_INSIGHTS_LICENSE_KEY,o,a,c;if(i){let _=await KI(i,n,r);_?(o=_.token,a=_.usageData,c=_.licenseInfo||await Rm(i,o),_.fingerprint?n=_.fingerprint:n=Nu(o).fingerprint):(T.warning("\u26A0\uFE0F License validation failed. Running in free tier mode."),T.comment(" Check your license key and internet connection."),c=await Rm(i,void 0))}else c=await Rm(void 0,void 0);let u=`${c?.tier??"free"} tier`;T.info(`\u{1F50D} CDK Insights (${u})`),c.tier==="free"&&!i&&(T.comment("\u{1F4A1} Upgrade to Pro for AI-powered recommendations and GitHub integration"),T.comment(" Visit: https://cdkinsights.dev"));let l=qn(),d=mM(l,t),p=d.ci||vr();if(p&&!d.ci){let _=wR();T.info(`Detected CI environment${_?`: ${_}`:""}`)}let f=!p&&AR();if(p&&!d.stackName&&!d.all&&(d.all=!0),p&&!d.output&&(d.output="json"),d.watch){(d.writeBaseline||d.diff)&&(T.error("--watch cannot be combined with --writeBaseline or --diff."),T.comment(" Run those modes one-shot, then start `cdk-insights scan --watch` for the live loop."),process.exit(2));let _=["json","sarif","github-actions","markdown"],Y=d.output??d.format;Y&&_.includes(Y)&&T.warning(`--watch ignores --output ${Y}; using table output.`),d.output="table",d.format="table",d.local=!0,d.failOnCritical=!1,!d.stackName&&!d.all&&(d.stackName="All stacks");let{runWatchLoop:y}=await Promise.resolve().then(()=>(KN(),VN));await y({config:d,fingerprint:n,authToken:o,licenseInfo:c,usageData:a,project:r,licenseKey:i});return}Gne()||(T.info("\u26A1 No cdk.out directory found. Running cdk synth..."),Tf()||(T.error("Failed to synthesize CDK stacks."),T.comment(" Make sure your CDK app compiles correctly."),process.exit(1)));let m=$k();m.length===0&&(T.error("No CDK stacks found in cdk.out directory."),T.comment(' Make sure you have run "cdk synth" and that your CDK app defines at least one stack.'),T.comment(" If cdk.out exists, check that it contains valid CloudFormation templates."),process.exit(1));let g=["All stacks",...m],h=d;if((t.github||h.withIssue)&&(Sr.isFeatureEnabled("githubIntegration",c.tier)?T.success("\u{1F517} GitHub integration enabled"):(T.error("GitHub integration is not available for your current tier"),T.comment(Vd("githubIntegration",c.tier,"GitHub integration")),process.exit(1))),f&&!d.yes){let _=await zne(d,g);h={...d,..._}}h.all&&(h.stackName="All stacks"),h.stackName||(h.stackName="All stacks"),f&&h.output||(h.output=JN(h)),h.format=h.output,(h.output==="json"||h.output==="sarif")&&(process.env.CDK_INSIGHTS_QUIET_STDOUT="1"),f&&h.output==="markdown"&&h.withIssue===void 0?h.withIssue=await pc({message:"Create GitHub issues from findings? (only available with markdown output)",default:!1}):h.withIssue===void 0&&(h.withIssue=!1),h.output==="table"&&(h.withIssue=!1);let v,x=0;if(h.diff)try{let _=Yx(h.baseline);_?(v=new Set(_.fingerprints),x=_.fingerprints.length,T.info(`\u{1F4D0} Diff against baseline (${_.fingerprints.length} known findings; ${_.generatedAt}).`)):T.warning("No baseline file found. Run `cdk-insights scan --writeBaseline` to create one. Showing all findings.")}catch(_){T.error(_ instanceof Error?_.message:"Failed to load baseline file."),process.exit(2)}let S=h.writeBaseline?new Set:void 0,w=h.writeBaseline===!0,E=oM(),P=new Date,k=await Jv(h,n,o,c,a,r,i,h.local,l.sensitiveDataDetection,v,S,w),A=l.telemetry?.enabled===!0&&!!i;if(h.diff&&v){let _=0,Y=[];for(let y of Object.values(k.recommendationMaps||{})){if(!y?.sources)continue;let b=[...y.sources.cdkInsights?.issues??[],...y.sources.cdkNag?.issues??[]];_+=b.length,Y.push(...b)}if(T.info(`\u{1F4D0} Diff result: ${_} new finding${_===1?"":"s"} (${x} existing, suppressed).`),A){let y=(()=>{try{return Yx(h.baseline)}catch{return null}})();gl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"diff_run",newFindings:_,existingSuppressed:x,newSeverities:jS(Y),baselineGeneratedAt:y?.generatedAt,failedOnCritical:!!k.hasCriticalIssues}})}}if(h.writeBaseline&&S){let _="1.28.0",{path:Y,count:y}=Mk([...S],{cliVersion:_,overridePath:h.baseline});if(T.success(`\u{1F4CC} Wrote baseline of ${y} finding${y===1?"":"s"} to ${Y}.`),T.comment(" On the next run, pass --diff to see only new findings since this point."),A){let b=[],K={},q=new Set;for(let te of Object.values(k.recommendationMaps||{})){if(!te?.sources)continue;let X=[...te.sources.cdkInsights?.issues??[],...te.sources.cdkNag?.issues??[]];b.push(...X);for(let fe of X){let Re=fe.ruleId,se=/^([A-Za-z][A-Za-z0-9-]+):\s/.exec(fe.issue??""),Ce=Re||se?.[1]||"unknown";K[Ce]=(K[Ce]??0)+1}let ee=te.type;ee?.startsWith("AWS::")&&q.add(ee.split("::")[1])}gl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"baseline_written",totalFindings:y,severityCounts:jS(b),ruleHistogram:K,uniqueServices:q.size}})}return}let M=[],z=k.recommendationMaps||{},C=new Set;for(let[_,Y]of Object.entries(z)){let y=Y,b=_.includes(":")?_.substring(_.indexOf(":")+1):_,K=_.includes(":")?_.substring(0,_.indexOf(":")):"";K&&C.add(K);let q=[...y.sources.cdkInsights?.issues??[],...y.sources.cdkNag?.issues??[]];for(let te of q)M.push({resourceId:b,issue:te.issue,recommendation:te.recommendation,severity:te.severity,wafPillar:te.wafPillar||"Security",foundBy:te.foundBy||"cdkInsights",constructPath:te.constructPath,codeSnippet:te.codeSnippet,sourceLocation:te.sourceLocation,ruleId:te.ruleId,context:te.context,constructType:te.constructType||y.constructType})}if(h.prComment)if(Af()){T.info("Posting analysis summary to PR...");let _=[...C],Y={stackNames:_.length>0?_:[h.stackName||"Unknown"],resourceCount:k.totalResources,issues:M,reportUrl:void 0,aiEnabled:!h.local&&!!i,tier:c?.tier||"free"},y=await sb({data:Y,updateExisting:!0});y.success?T.success("PR comment posted successfully"):T.warning(`Failed to post PR comment: ${y.error}`)}else T.warning("PR comment requested but not in GitHub Actions PR context. Skipping."),T.comment(" PR comments require: GitHub Actions + pull_request event + GITHUB_TOKEN permissions");if(T.success(`Analysis complete! ${h.withIssue?"GitHub issues have been created for the findings.":"Review the findings above."}`),l.scanHistory?.enabled===!0&&i&&o&&!h.writeBaseline){let _="1.28.0",Y=new Date,y=!h.local&&!!i,b=nM({scanId:E,cliVersion:_,recommendationMaps:k.recommendationMaps||{},scannedResourceIds:k.scannedResourceIds??new Set,scanStartedAt:P,scanCompletedAt:Y,aiAnalysis:{ran:y}});T.info("\u{1F4E4} Uploading scan to CDK Insights...");let K=await iM({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,report:b});if(!K.skipped)if(K.success)T.success(`Uploaded as scan ${K.scanId}`),K.viewUrl&&T.comment(` View: ${K.viewUrl}`),K.retentionDays&&T.comment(` Retained for ${K.retentionDays} day${K.retentionDays===1?"":"s"} \u2014 adjust in scanHistory settings.`),T.comment(" You opted in via .cdk-insights.json. To opt out, set scanHistory.enabled = false.");else{let q=K.serverMessage??K.reason??"unknown";T.warning(`Could not upload scan to CDK Insights (${q}). Run continues normally.`)}}if(l.feedback!==!1&&f&&o&&M.length>0)try{let _=await bi({message:"Was this analysis helpful?",choices:[{name:"Yes, helpful!",value:"helpful"},{name:"Actionable - I'll fix these",value:"actionable"},{name:"Not helpful",value:"not_helpful"},{name:"Inaccurate findings",value:"inaccurate"},{name:"Skip",value:"skip"}],default:"skip"});if(_!=="skip"){let Y=Wn(),b=VF({apiClient:{post:async(q,te)=>{let{data:X}=await Rt.post(`${Y}${q}`,te,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-cdk-insights-fingerprint":n,"x-cdk-insights-client":"cli"},timeout:1e4});return X}}}),K={};for(let[q,te]of Object.entries(k.recommendationMaps||{})){let X=te,ee=q.includes(":")?q.substring(q.indexOf(":")+1):q;X.type&&(K[ee]=X.type)}if(_==="helpful")b.markReportAsHelpful(M,K).catch(()=>{}),T.comment(" Thanks for your feedback!");else{let q=M.map(te=>({issue:te,rating:_,resourceType:K[te.resourceId]}));b.submitBatchFeedback(q).catch(()=>{}),T.comment(" Thanks for your feedback!")}}}catch{}else f||T.comment(" Have feedback? Let us know: https://cdkinsights.dev/feedback?source=cli");k.hasCriticalIssues&&(k.hasSensitiveData&&!h.warnSensitive?(T.error("Sensitive data detected. Exiting with code 1."),T.comment(" Use --warn-sensitive to continue without failing, or fix the issues.")):T.error("Critical issues found. Exiting with code 1."),await new Promise(_=>{process.stdout.write("")?_():process.stdout.once("drain",_)}),process.exit(1))}catch(e){let{message:s}=e;T.error(`An error occurred during analysis: ${s||e}`),process.exit(1)}}}});var Tc,l5,u5,are,d5,p5=D(()=>{"use strict";Tc=oe(require("node:fs")),l5=oe(require("node:path")),u5="@aws-cdk/core:stackTrace",are=t=>{let e;try{e=JSON.parse(t)}catch{return{status:"invalid-json"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"invalid-json"};let s=e,n=s.context,r=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{};if(r[u5]===!0)return{status:"already-set",updated:t};r[u5]=!0;let i={...s,context:r},o=t.endsWith(`
|
|
452
|
+
\u{1F44B} Stopping watcher.`),l.close().then(()=>d())};process.once("SIGINT",p),process.once("SIGTERM",p)})}});async function zne(t,e){let s=t.all?"All stacks":t.stackName||"All stacks",n=await bi({message:"Which stack would you like to analyze?",default:s,choices:e.map(c=>({name:c,value:c}))}),r=t.output||t.format||"table",i=await bi({message:"Choose output format:",choices:[{name:"\u{1F4CA} Table (default) - Human-readable table with colors",value:"table"},{name:"\u{1F4C4} Markdown - GitHub-compatible markdown report",value:"markdown"},{name:"\u{1F527} JSON - Structured data for CI/CD integration",value:"json"},{name:"\u{1F4CB} Summary - Brief overview with counts",value:"summary"}],default:r}),o=t.services&&t.services.length>0?t.services:["All services"],a=await Ey({message:"Which AWS services would you like to analyze? (Use <space> to toggle, <enter> to confirm)",choices:[{name:"\u{1F50D} All services (recommended)",value:"All services",checked:o.includes("All services")},{name:"\u{1F510} IAM - Identity and Access Management",value:"IAM",checked:o.includes("IAM")},{name:"\u{1F4E6} S3 - Simple Storage Service",value:"S3",checked:o.includes("S3")},{name:"\u26A1 Lambda - Serverless Functions",value:"Lambda",checked:o.includes("Lambda")},{name:"\u{1F5C4}\uFE0F DynamoDB - NoSQL Database",value:"DynamoDB",checked:o.includes("DynamoDB")},{name:"\u{1F5C4}\uFE0F RDS - Relational Database",value:"RDS",checked:o.includes("RDS")},{name:"\u{1F5A5}\uFE0F EC2 - Virtual Machines",value:"EC2",checked:o.includes("EC2")},{name:"\u{1F4E2} SNS - Simple Notification Service",value:"SNS",checked:o.includes("SNS")},{name:"\u{1F4E8} SQS - Simple Queue Service",value:"SQS",checked:o.includes("SQS")},{name:"\u{1F504} Step Functions - Workflow Orchestration",value:"StepFunctions",checked:o.includes("StepFunctions")},{name:"\u{1F4DD} CloudTrail - API Logging",value:"CloudTrail",checked:o.includes("CloudTrail")},{name:"\u{1F310} API Gateway - REST APIs",value:"ApiGateway",checked:o.includes("ApiGateway")},{name:"\u{1F511} Secrets Manager - Secret Management",value:"SecretsManager",checked:o.includes("SecretsManager")},{name:"\u{1F510} KMS - Key Management",value:"KMS",checked:o.includes("KMS")},{name:"\u{1F4E1} EventBridge - Event Routing",value:"EventBridge",checked:o.includes("EventBridge")},{name:"\u{1F310} CloudFront - Content Delivery Network",value:"CloudFront",checked:o.includes("CloudFront")},{name:"\u2696\uFE0F ELB - Elastic Load Balancing",value:"ELB",checked:o.includes("ELB")},{name:"\u{1F433} ECS - Elastic Container Service",value:"ECS",checked:o.includes("ECS")},{name:"\u{1F464} Cognito - User Authentication",value:"Cognito",checked:o.includes("Cognito")},{name:"\u{1F6E1}\uFE0F WAF - Web Application Firewall",value:"WAF",checked:o.includes("WAF")},{name:"\u{1F4CA} CloudWatch - Monitoring & Logging",value:"CloudWatch",checked:o.includes("CloudWatch")},{name:"\u{1F30D} Route53 - DNS Management",value:"Route53",checked:o.includes("Route53")},{name:"\u26A1 ElastiCache - In-Memory Caching",value:"ElastiCache",checked:o.includes("ElastiCache")},{name:"\u{1F4E6} ECR - Container Registry",value:"ECR",checked:o.includes("ECR")},{name:"\u{1F50E} OpenSearch - Search & Analytics",value:"OpenSearch",checked:o.includes("OpenSearch")},{name:"\u{1F50F} ACM - Certificate Manager",value:"ACM",checked:o.includes("ACM")},{name:"\u{1F4BE} Backup - Backup Management",value:"Backup",checked:o.includes("Backup")},{name:"\u{1F517} VPC - Virtual Private Cloud",value:"VPC",checked:o.includes("VPC")},{name:"\u{1F30A} Kinesis - Real-time Streaming",value:"Kinesis",checked:o.includes("Kinesis")},{name:"\u{1F4F1} AppSync - GraphQL APIs",value:"AppSync",checked:o.includes("AppSync")},{name:"\u2638\uFE0F EKS - Kubernetes Service",value:"EKS",checked:o.includes("EKS")},{name:"\u{1F4C8} Redshift - Data Warehouse",value:"Redshift",checked:o.includes("Redshift")},{name:"\u{1F4EC} MSK - Managed Kafka",value:"MSK",checked:o.includes("MSK")},{name:"\u{1F9EA} Glue - ETL & Data Catalog",value:"Glue",checked:o.includes("Glue")}]});return{stackName:n,output:i,services:a}}async function Jv(t,e,s,n,r,i,o,a,c,u,l,d){let{stackName:p,output:f,services:m,withIssue:g,ruleFilter:h,failOnCritical:v}=t,x=p==="All stacks"?void 0:p,{stacks:S,inlineFindings:w,pathToLogicalId:E,recommendationMapPerStack:P,assetSourcePaths:k,acknowledgementsPerStack:A,cdkVersion:M,supportsBoxTraces:z,cdkContext:C,resourceIdMetadata:U}=jf(x),_=Object.keys(S).length;T.success(`Synthesis complete. Found ${_} stack${_===1?"":"s"} to analyze.`),M&&!z&&T.info(`Detected aws-cdk-lib ${M}. Upgrade to >= 2.252.0 for per-property source locations on deferred values.`);let Y=Object.values(S).reduce((xe,ge)=>{let L=Object.entries(ge.Resources||{}).filter(([,ae])=>!ae.Type.startsWith("AWS::CDK::"));return xe+L.length},0);Y>0?T.info(`\u{1F50D} Preparing to analyze ${Y} total resources across ${_} stacks...`):T.warning("No user resources found in stacks. Make sure your CDK app is properly configured.");let y=null,b=!!s;if(a&&(b=!1,T.info("\u{1F3E0} Running in local mode - static analysis only")),o&&!a){T.info("\u{1F50D} Checking license quota...");let xe=n.licenseType==="FREE"||n.status==="TRIAL",ge=n.totalResourcesAnalyzed||0,L=n.trialUsageLimit||n.maxUsage||200,ae=Number.isNaN(ge)?0:ge,W=Number.isNaN(L)?200:L;if(xe&&ae>=W)b=!1,y={canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,quota:{currentResourcesAnalyzed:ae,maxResources:W,remainingResources:Math.max(0,W-ae),isTrial:!0,trialExpired:!1},reason:`Trial AI credit allowance exceeded (${ae}/${W} used)`,upgradePath:"https://cdkinsights.dev/pricing"},T.warning("\u26A0\uFE0F Trial AI credit allowance exceeded \u2014 falling back to static scans only"),T.comment(" Upgrade to Pro for 5,000 AI credits per month");else if(y=await eM({licenseKey:o,requestedResources:Y,allowOveruse:t.allowOveruse,usageData:r,licenseInfo:n}),b=!!s&&(y?.canRunAIAnalysis??!0),y?.quota?.isTrial){let ue=y.quota.currentResourcesAnalyzed,De=y.quota.maxResources;ue>=De&&(y={...y,canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,reason:`Trial AI credit allowance exceeded (${ue}/${De} used) \u2014 falling back to static scans only`},b=!1)}y?.quota?.isTrial&&T.displayTrialStatus({currentResourcesAnalyzed:y.quota.currentResourcesAnalyzed,maxResources:y.quota.maxResources,remainingResources:y.quota.remainingResources,isTrial:y.quota.isTrial,trialExpired:y.quota.trialExpired,trialStart:n.trialStart,trialEnd:n.trialEnd,tier:n.tier}),!b&&y?.quota?T.displayQuotaWarning({currentResourcesAnalyzed:y.quota.currentResourcesAnalyzed,maxResources:y.quota.maxResources,requestedResources:Y,remainingResources:y.quota.remainingResources,isTrial:y.quota.isTrial}):b&&o&&T.success("AI analysis enabled - you'll receive comprehensive recommendations")}let K=wp(t.services),q=K.services;K.removedAllServices?re.debug(`Services normalization: removed "All services", using: ${q.join(", ")}`):K.defaultedToAll&&re.debug('Services normalization: defaulting to "All services"');let te=c||{},X=t.warnSensitive||te.warnOnly||!1,ee=(()=>{let xe=C?.["cdkInsights:aiModel"];return typeof xe=="string"?xe:void 0})(),fe=dM({flag:t.model,cdkContext:ee,userConfig:typeof t.ai?.model=="string"?t.ai?.model:void 0,tier:n?.tier});fe.downgradedFromTierGate?T.warning(`\u26A0\uFE0F Requested AI model "${fe.requestedAlias}" is not available on your tier \u2014 using "${fe.alias}" instead.`):fe.source!=="tierDefault"&&T.comment(`\u{1F916} AI model: ${fe.alias} (from ${fe.source})`);let Re=t.ai?.batchSize,se=typeof Re=="number"&&Number.isFinite(Re)?Math.max(1,Math.floor(Re)):void 0;se&&se>1&&T.comment(`\u{1F9FA} AI batching: ${se} resources per call`);let Ce={stacks:S,inlineFindings:w,pathToLogicalId:E,recommendationMapPerStack:P,assetSourcePaths:k,acknowledgementsPerStack:A,output:JN(t),services:q,withIssue:t.withIssue,ruleFilter:t.ruleFilter||[],ignoreRules:t.ignoreRules||[],ignorePaths:t.ignorePaths||[],failOnCritical:t.failOnCritical,authToken:s,fingerprint:e,tier:n?.tier,quotaValidation:y||null,noCache:t.noCache||!1,cache:{enabled:t.cache?.enabled??!0,ttl:t.cache?.ttl??3e5,maxSize:t.cache?.maxSize??5e3},allowOveruse:t.allowOveruse||!1,warnSensitive:X,sensitiveDataDetection:{disabled:te.enabled===!1,ignoreProperties:te.ignoreProperties||[],allowPatterns:te.allowPatterns||[],strictMode:te.strictMode||!1},cdkContext:C,resourceIdMetadata:U,aiModelId:fe.bedrockModelId,aiBatchSize:se,forceLocal:a,baselineExclude:u,collectFingerprints:l,skipRendering:d};return{...await Am(Ce),totalResources:Y}}var ZN,YN,Gne,JN,QN,Qv=D(()=>{"use strict";ZN=oe(require("node:fs")),YN=oe(require("node:path"));Kx();Jn();Kd();Bk();Qx();Wk();Zk();Pf();za();KF();kb();BS();X4();qa();Y0();Zd();tM();tb();lt();rM();aM();US();$r();pM();hM();Cl();Gne=()=>{let t=YN.resolve(process.cwd(),"cdk.out");return ZN.existsSync(t)},JN=t=>t.summaryOnly?"summary":t.format==="json"||t.output==="json"?"json":t.format==="markdown"||t.output==="markdown"?"markdown":t.format==="summary"||t.output==="summary"?"summary":t.format==="sarif"||t.output==="sarif"?"sarif":t.format==="github-actions"||t.output==="github-actions"?"github-actions":"table";QN={command:"scan [stackName]",describe:"Scan CDK stacks for best practices and security issues",builder:t=>t.positional("stackName",{type:"string",describe:"Name of the stack to analyze"}).option("ci",{type:"boolean",default:!1}).option("withIssue",{type:"boolean",description:"Create GitHub issues from findings?"}).option("output",{alias:"o",type:"string",choices:["json","table","markdown","summary","sarif","github-actions"]}).option("all",{type:"boolean",description:"Analyze all CDK stacks,",default:!1}).option("services",{type:"array",string:!0,description:"Only run checks for these services (e.g. IAM, S3, Lambda)"}).option("format",{type:"string",choices:["json","table","markdown","summary","sarif","github-actions"],describe:"Alias for --output (preferred)"}).option("yes",{type:"boolean",description:"Skip prompts and use saved/default values,",default:!1,alias:"y"}).option("reset",{type:"boolean",description:"Clear saved config and start fresh"}).option("redact",{type:"boolean",description:"Redact sensitive resource names in output",default:!1}).option("summaryOnly",{type:"boolean",description:"Only show summary in console output",default:!1}).option("synth",{type:"boolean",description:"Run cdk synth before analysis",default:!1}).option("watch",{type:"boolean",description:"Watch CDK files and re-run static analysis on save. AI, baseline writes, GitHub issues, PR comments and scan history are disabled in watch mode. Reuses cdk.json `watch.include` / `watch.exclude` (same as `cdk watch`).",default:!1}).option("failOnCritical",{type:"boolean",description:"Exit with code 1 if critical issues are found (defaults to true)",default:!0}).option("ruleFilter",{type:"array",string:!0,describe:"Filter findings to only include matching rule IDs or categories (e.g. AwsSolutions-IAM4, Security)"}).option("github",{describe:"Create GitHub issues for findings,",type:"boolean",default:!1}).option("noCache",{describe:"Disable cache and force fresh analysis",type:"boolean",default:!1}).option("allowOveruse",{describe:"Allow AI analysis even when exceeding paid allowance (extra usage will be charged)",type:"boolean",default:!1}).option("local",{describe:"Run static analysis only (skip AI analysis even with a valid license)",type:"boolean",default:!1}).option("warnSensitive",{describe:"Treat sensitive data as warning instead of critical (will not fail CI)",type:"boolean",default:!1}).option("prComment",{describe:"Post analysis summary as a PR comment (GitHub Actions only)",type:"boolean",default:!1}).option("model",{describe:"AI model alias for analysis (e.g. nova-lite, mistral-14b, llama-3-3-70b). Overrides cdk.json and user config. Tier-gated.",type:"string"}).option("diff",{describe:"Only show findings new since the saved baseline (.cdk-insights-baseline.json). Existing findings still appear in summaries but never fail CI.",type:"boolean",default:!1}).option("writeBaseline",{describe:"Write the current findings to .cdk-insights-baseline.json (or --baseline path) and exit 0 regardless of severity. Skips findings rendering.",type:"boolean",default:!1}).option("baseline",{describe:"Path to the baseline file. Defaults to .cdk-insights-baseline.json in cwd. Used by both --diff and --writeBaseline.",type:"string"}),handler:async t=>{try{let e=t.output||t.format;if((e==="json"||e==="sarif")&&(process.env.CDK_INSIGHTS_QUIET_STDOUT="1"),t.reset){km(),re.info("\u{1F5D1}\uFE0F Cleared saved CLI preferences.");return}let s=Nu(),n=s.fingerprint,r=s.project;(!n||n.length===0)&&(T.error("Failed to generate system fingerprint for authentication."),T.comment(" This may indicate a permissions issue with reading system information."),process.exit(1));let i=process.env.CDK_INSIGHTS_LICENSE_KEY,o,a,c;if(i){let _=await KI(i,n,r);_?(o=_.token,a=_.usageData,c=_.licenseInfo||await Rm(i,o),_.fingerprint?n=_.fingerprint:n=Nu(o).fingerprint):(T.warning("\u26A0\uFE0F License validation failed. Running in free tier mode."),T.comment(" Check your license key and internet connection."),c=await Rm(i,void 0))}else c=await Rm(void 0,void 0);let u=`${c?.tier??"free"} tier`;T.info(`\u{1F50D} CDK Insights (${u})`),c.tier==="free"&&!i&&(T.comment("\u{1F4A1} Upgrade to Pro for AI-powered recommendations and GitHub integration"),T.comment(" Visit: https://cdkinsights.dev"));let l=qn(),d=mM(l,t),p=d.ci||vr();if(p&&!d.ci){let _=wR();T.info(`Detected CI environment${_?`: ${_}`:""}`)}let f=!p&&AR();if(p&&!d.stackName&&!d.all&&(d.all=!0),p&&!d.output&&(d.output="json"),d.watch){(d.writeBaseline||d.diff)&&(T.error("--watch cannot be combined with --writeBaseline or --diff."),T.comment(" Run those modes one-shot, then start `cdk-insights scan --watch` for the live loop."),process.exit(2));let _=["json","sarif","github-actions","markdown"],Y=d.output??d.format;Y&&_.includes(Y)&&T.warning(`--watch ignores --output ${Y}; using table output.`),d.output="table",d.format="table",d.local=!0,d.failOnCritical=!1,!d.stackName&&!d.all&&(d.stackName="All stacks");let{runWatchLoop:y}=await Promise.resolve().then(()=>(KN(),VN));await y({config:d,fingerprint:n,authToken:o,licenseInfo:c,usageData:a,project:r,licenseKey:i});return}Gne()||(T.info("\u26A1 No cdk.out directory found. Running cdk synth..."),Tf()||(T.error("Failed to synthesize CDK stacks."),T.comment(" Make sure your CDK app compiles correctly."),process.exit(1)));let m=$k();m.length===0&&(T.error("No CDK stacks found in cdk.out directory."),T.comment(' Make sure you have run "cdk synth" and that your CDK app defines at least one stack.'),T.comment(" If cdk.out exists, check that it contains valid CloudFormation templates."),process.exit(1));let g=["All stacks",...m],h=d;if((t.github||h.withIssue)&&(Sr.isFeatureEnabled("githubIntegration",c.tier)?T.success("\u{1F517} GitHub integration enabled"):(T.error("GitHub integration is not available for your current tier"),T.comment(Vd("githubIntegration",c.tier,"GitHub integration")),process.exit(1))),f&&!d.yes){let _=await zne(d,g);h={...d,..._}}h.all&&(h.stackName="All stacks"),h.stackName||(h.stackName="All stacks"),f&&h.output||(h.output=JN(h)),h.format=h.output,(h.output==="json"||h.output==="sarif")&&(process.env.CDK_INSIGHTS_QUIET_STDOUT="1"),f&&h.output==="markdown"&&h.withIssue===void 0?h.withIssue=await pc({message:"Create GitHub issues from findings? (only available with markdown output)",default:!1}):h.withIssue===void 0&&(h.withIssue=!1),h.output==="table"&&(h.withIssue=!1);let v,x=0;if(h.diff)try{let _=Yx(h.baseline);_?(v=new Set(_.fingerprints),x=_.fingerprints.length,T.info(`\u{1F4D0} Diff against baseline (${_.fingerprints.length} known findings; ${_.generatedAt}).`)):T.warning("No baseline file found. Run `cdk-insights scan --writeBaseline` to create one. Showing all findings.")}catch(_){T.error(_ instanceof Error?_.message:"Failed to load baseline file."),process.exit(2)}let S=h.writeBaseline?new Set:void 0,w=h.writeBaseline===!0,E=oM(),P=new Date,k=await Jv(h,n,o,c,a,r,i,h.local,l.sensitiveDataDetection,v,S,w),A=l.telemetry?.enabled===!0&&!!i;if(h.diff&&v){let _=0,Y=[];for(let y of Object.values(k.recommendationMaps||{})){if(!y?.sources)continue;let b=[...y.sources.cdkInsights?.issues??[],...y.sources.cdkNag?.issues??[]];_+=b.length,Y.push(...b)}if(T.info(`\u{1F4D0} Diff result: ${_} new finding${_===1?"":"s"} (${x} existing, suppressed).`),A){let y=(()=>{try{return Yx(h.baseline)}catch{return null}})();gl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"diff_run",newFindings:_,existingSuppressed:x,newSeverities:jS(Y),baselineGeneratedAt:y?.generatedAt,failedOnCritical:!!k.hasCriticalIssues}})}}if(h.writeBaseline&&S){let _="1.29.0",{path:Y,count:y}=Mk([...S],{cliVersion:_,overridePath:h.baseline});if(T.success(`\u{1F4CC} Wrote baseline of ${y} finding${y===1?"":"s"} to ${Y}.`),T.comment(" On the next run, pass --diff to see only new findings since this point."),A){let b=[],K={},q=new Set;for(let te of Object.values(k.recommendationMaps||{})){if(!te?.sources)continue;let X=[...te.sources.cdkInsights?.issues??[],...te.sources.cdkNag?.issues??[]];b.push(...X);for(let fe of X){let Re=fe.ruleId,se=/^([A-Za-z][A-Za-z0-9-]+):\s/.exec(fe.issue??""),Ce=Re||se?.[1]||"unknown";K[Ce]=(K[Ce]??0)+1}let ee=te.type;ee?.startsWith("AWS::")&&q.add(ee.split("::")[1])}gl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"baseline_written",totalFindings:y,severityCounts:jS(b),ruleHistogram:K,uniqueServices:q.size}})}return}let M=[],z=k.recommendationMaps||{},C=new Set;for(let[_,Y]of Object.entries(z)){let y=Y,b=_.includes(":")?_.substring(_.indexOf(":")+1):_,K=_.includes(":")?_.substring(0,_.indexOf(":")):"";K&&C.add(K);let q=[...y.sources.cdkInsights?.issues??[],...y.sources.cdkNag?.issues??[]];for(let te of q)M.push({resourceId:b,issue:te.issue,recommendation:te.recommendation,severity:te.severity,wafPillar:te.wafPillar||"Security",foundBy:te.foundBy||"cdkInsights",constructPath:te.constructPath,codeSnippet:te.codeSnippet,sourceLocation:te.sourceLocation,ruleId:te.ruleId,context:te.context,constructType:te.constructType||y.constructType})}if(h.prComment)if(Af()){T.info("Posting analysis summary to PR...");let _=[...C],Y={stackNames:_.length>0?_:[h.stackName||"Unknown"],resourceCount:k.totalResources,issues:M,reportUrl:void 0,aiEnabled:!h.local&&!!i,tier:c?.tier||"free"},y=await sb({data:Y,updateExisting:!0});y.success?T.success("PR comment posted successfully"):T.warning(`Failed to post PR comment: ${y.error}`)}else T.warning("PR comment requested but not in GitHub Actions PR context. Skipping."),T.comment(" PR comments require: GitHub Actions + pull_request event + GITHUB_TOKEN permissions");if(T.success(`Analysis complete! ${h.withIssue?"GitHub issues have been created for the findings.":"Review the findings above."}`),l.scanHistory?.enabled===!0&&i&&o&&!h.writeBaseline){let _="1.29.0",Y=new Date,y=!h.local&&!!i,b=nM({scanId:E,cliVersion:_,recommendationMaps:k.recommendationMaps||{},scannedResourceIds:k.scannedResourceIds??new Set,scanStartedAt:P,scanCompletedAt:Y,aiAnalysis:{ran:y}});T.info("\u{1F4E4} Uploading scan to CDK Insights...");let K=await iM({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,report:b});if(!K.skipped)if(K.success)T.success(`Uploaded as scan ${K.scanId}`),K.viewUrl&&T.comment(` View: ${K.viewUrl}`),K.retentionDays&&T.comment(` Retained for ${K.retentionDays} day${K.retentionDays===1?"":"s"} \u2014 adjust in scanHistory settings.`),T.comment(" You opted in via .cdk-insights.json. To opt out, set scanHistory.enabled = false.");else{let q=K.serverMessage??K.reason??"unknown";T.warning(`Could not upload scan to CDK Insights (${q}). Run continues normally.`)}}if(l.feedback!==!1&&f&&o&&M.length>0)try{let _=await bi({message:"Was this analysis helpful?",choices:[{name:"Yes, helpful!",value:"helpful"},{name:"Actionable - I'll fix these",value:"actionable"},{name:"Not helpful",value:"not_helpful"},{name:"Inaccurate findings",value:"inaccurate"},{name:"Skip",value:"skip"}],default:"skip"});if(_!=="skip"){let Y=Wn(),b=VF({apiClient:{post:async(q,te)=>{let{data:X}=await Rt.post(`${Y}${q}`,te,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-cdk-insights-fingerprint":n,"x-cdk-insights-client":"cli"},timeout:1e4});return X}}}),K={};for(let[q,te]of Object.entries(k.recommendationMaps||{})){let X=te,ee=q.includes(":")?q.substring(q.indexOf(":")+1):q;X.type&&(K[ee]=X.type)}if(_==="helpful")b.markReportAsHelpful(M,K).catch(()=>{}),T.comment(" Thanks for your feedback!");else{let q=M.map(te=>({issue:te,rating:_,resourceType:K[te.resourceId]}));b.submitBatchFeedback(q).catch(()=>{}),T.comment(" Thanks for your feedback!")}}}catch{}else f||T.comment(" Have feedback? Let us know: https://cdkinsights.dev/feedback?source=cli");k.hasCriticalIssues&&(k.hasSensitiveData&&!h.warnSensitive?(T.error("Sensitive data detected. Exiting with code 1."),T.comment(" Use --warn-sensitive to continue without failing, or fix the issues.")):T.error("Critical issues found. Exiting with code 1."),await new Promise(_=>{process.stdout.write("")?_():process.stdout.once("drain",_)}),process.exit(1))}catch(e){let{message:s}=e;T.error(`An error occurred during analysis: ${s||e}`),process.exit(1)}}}});var Tc,l5,u5,are,d5,p5=D(()=>{"use strict";Tc=oe(require("node:fs")),l5=oe(require("node:path")),u5="@aws-cdk/core:stackTrace",are=t=>{let e;try{e=JSON.parse(t)}catch{return{status:"invalid-json"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"invalid-json"};let s=e,n=s.context,r=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{};if(r[u5]===!0)return{status:"already-set",updated:t};r[u5]=!0;let i={...s,context:r},o=t.endsWith(`
|
|
453
453
|
`)?`
|
|
454
454
|
`:"";return{status:"added",updated:`${JSON.stringify(i,null,2)}${o}`}},d5=t=>{let e=l5.join(t,"cdk.json");if(!Tc.existsSync(e))return{status:"missing",cdkJsonPath:e};let s=Tc.readFileSync(e,"utf-8"),n=are(s);return n.status==="invalid-json"?{status:"invalid-json",cdkJsonPath:e}:n.status==="already-set"?{status:"already-set",cdkJsonPath:e}:(Tc.writeFileSync(e,n.updated,"utf-8"),{status:"added",cdkJsonPath:e})}});var S5=oe(lh()),ih=require("node:child_process"),v5=oe(require("node:path")),C5=require("node:util");Jn();var D5=oe(Hg());var Ld=require("assert");var _j={right:Lj,center:Oj},kj=0,Rd=1,Fj=2,Id=3,Gg=class{constructor(e){var s;this.width=e.width,this.wrap=(s=e.wrap)!==null&&s!==void 0?s:!0,this.rows=[]}span(...e){let s=this.div(...e);s.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0&&this.div(""),this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]=="string")return this.applyLayoutDSL(e[0]);let s=e.map(n=>typeof n=="string"?this.colFromString(n):n);return this.rows.push(s),s}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]=="string"&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let s=e.split(`
|
|
455
455
|
`).map(r=>r.split(" ")),n=0;return s.forEach(r=>{r.length>1&&Us.stringWidth(r[0])>n&&(n=Math.min(Math.floor(this.width*.5),Us.stringWidth(r[0])))}),s.forEach(r=>{this.div(...r.map((i,o)=>({text:i.trim(),padding:this.measurePadding(i),width:o===0&&r.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let s=Us.stripAnsi(e);return[0,s.match(/\s*$/)[0].length,0,s.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach(s=>{this.rowToString(s,e)}),e.filter(s=>!s.hidden).map(s=>s.text).join(`
|
|
@@ -544,7 +544,7 @@ ${s}
|
|
|
544
544
|
`)?`${e}.env
|
|
545
545
|
`:`${e}
|
|
546
546
|
.env
|
|
547
|
-
`;mt.writeFileSync(t,r,"utf-8"),T.info("Added .env to .gitignore")}},r5={"cdk-insights":"cdk-insights scan","cdk-insights:all":"cdk-insights scan --all","cdk-insights:
|
|
547
|
+
`;mt.writeFileSync(t,r,"utf-8"),T.info("Added .env to .gitignore")}},r5={"cdk-insights":"cdk-insights scan","cdk-insights:all":"cdk-insights scan --all","cdk-insights:watch":"cdk-insights scan --watch","cdk-insights:ci":"cdk-insights scan --all --output json --failOnCritical"},ore={"cdk-insights:json":"cdk-insights scan --output json","cdk-insights:markdown":"cdk-insights scan --output markdown","cdk-insights:summary":"cdk-insights scan --output summary","cdk-insights:issue":"cdk-insights scan --output markdown --with-issue"},a5={command:"init",describe:"Initialize CDK Insights in your project by adding npm scripts",builder:t=>t.option("force",{alias:"f",type:"boolean",describe:"Overwrite existing scripts",default:!1}).option("all",{alias:"a",type:"boolean",describe:"Add all optional scripts",default:!1}).option("dry-run",{type:"boolean",describe:"Show what would be added without making changes",default:!1}).option("skip-license",{type:"boolean",describe:"Skip license key setup prompt",default:!1}).option("license-key",{alias:"l",type:"string",describe:"License key to save to .env file"}),handler:async t=>{let e=Xs.join(process.cwd(),"package.json");mt.existsSync(e)||(T.error("No package.json found in current directory. Run this command from your project root."),process.exit(1));let s;try{let p=mt.readFileSync(e,"utf-8");s=JSON.parse(p)}catch{T.error("Failed to read package.json"),process.exit(1)}if(!mt.existsSync(Xs.join(process.cwd(),"cdk.json"))){if(console.log(""),T.warning("No cdk.json found in this directory."),T.comment(" cdk-insights expects to run inside a CDK app. `cdk-insights scan` will"),T.comment(" fail until you run it from a CDK project (or pass --path)."),process.stdin.isTTY&&!t.dryRun){let p=await nh(" Continue with init anyway? (y/N): ");if(!/^(y|yes)$/i.test(p??"")){T.info("Aborted. Re-run from your CDK project root.");return}}else T.comment(" Continuing \u2014 re-run from your CDK project root if needed.");console.log("")}s.scripts||(s.scripts={});let r=t.all?{...r5,...ore}:r5,i=[],o=[];for(let[p]of Object.entries(r))s.scripts[p]?t.force?o.push(p):i.push(p):o.push(p);if(i.length>0&&!t.force){T.warning("The following scripts already exist:");for(let p of i)T.comment(` - ${p}: "${s.scripts[p]}"`);T.info("Use --force to overwrite existing scripts.")}if(o.length===0){T.info("No new scripts to add. Your project is already set up!");return}T.info(t.dryRun?"Scripts that would be added:":"Adding scripts:"),console.log("");for(let p of o){let f=r[p];console.log(` "${p}": "${f}"`)}if(console.log(""),t.dryRun){let p=Xs.join(process.cwd(),".cdk-insights.json"),f=Xs.join(process.cwd(),".env"),m=Xs.join(process.cwd(),".gitignore");if(console.log(""),T.info(".cdk-insights.json:"),mt.existsSync(p))T.comment(` already present at ${p} \u2014 would be left untouched`);else{T.comment(` would be created at ${p} with:`);let g={output:"table",failOnCritical:!0,services:[],ruleFilter:[]};for(let h of JSON.stringify(g,null,2).split(`
|
|
548
548
|
`))console.log(` ${h}`)}console.log(""),T.info(".env:"),t.licenseKey&&typeof t.licenseKey=="string"?(T.comment(" --license-key was supplied \u2014 the key would be saved to .env (created if missing)"),mt.existsSync(m)?mt.readFileSync(m,"utf-8").split(`
|
|
549
549
|
`).some(v=>v.trim()===".env"||v.trim()===".env*")||T.comment(` .gitignore at ${m} would have .env appended`):T.comment(` .gitignore would be created at ${m} with .env entry`)):process.env.CDK_INSIGHTS_LICENSE_KEY||mt.existsSync(f)&&mt.readFileSync(f,"utf-8").includes("CDK_INSIGHTS_LICENSE_KEY=")?T.comment(" existing license key detected \u2014 .env would be left untouched"):t.skipLicense?T.comment(" --skip-license was supplied \u2014 no license setup would run"):process.stdin.isTTY?T.comment(" would prompt interactively for a license key (TTY detected)"):T.comment(" non-interactive run \u2014 would print manual instructions and skip"),console.log(""),T.info("Telemetry:"),process.stdin.isTTY?T.comment(" would prompt interactively \u2014 your y/N answer would be saved to .cdk-insights.json"):T.comment(" non-interactive run \u2014 would leave telemetry off (default)"),console.log(""),T.info("Dry run complete. No changes made.");return}for(let p of o)s.scripts[p]=r[p];try{mt.writeFileSync(e,`${JSON.stringify(s,null,2)}
|
|
550
550
|
`,"utf-8")}catch{T.error("Failed to write package.json"),process.exit(1)}T.success(`Added ${o.length} script(s) to package.json`),console.log("");let a={scriptsAdded:o.length,configFileCreated:!1,telemetry:"non-interactive",license:"non-interactive"};if(t.dryRun||(a.configFileCreated=sre(),console.log("")),!t.dryRun)if(t.skipLicense)a.license="skipped-flag";else{let p=Xs.join(process.cwd(),".env"),f=process.env.CDK_INSIGHTS_LICENSE_KEY,m=!1;if(mt.existsSync(p)&&(m=mt.readFileSync(p,"utf-8").includes("CDK_INSIGHTS_LICENSE_KEY=")),t.licenseKey&&typeof t.licenseKey=="string")t.licenseKey.startsWith("LIC-")?(n5(),s5(t.licenseKey),T.success(" License key saved from --license-key flag."),a.license="saved-from-flag"):(T.warning(' --license-key value does not start with "LIC-". Skipping.'),T.comment(" Real keys look like LIC-XXXXXXXXXXXX\u2026 \u2014 re-run with the correct value."),a.license="invalid-input");else if(!f&&!m)if(console.log(""),T.info("\u{1F511} License Key Setup"),T.comment(" A license key enables AI-powered analysis and recommendations."),T.comment(" Get your license at: https://cdkinsights.dev/start"),console.log(""),process.stdin.isTTY){let g=await nh(" Enter your license key (or press Enter to skip): ");if(g?.startsWith("LIC-"))n5(),s5(g),T.comment(" Your license key will be loaded automatically on future runs."),a.license="saved-interactive";else if(g)T.warning(' Invalid license key format. Keys should start with "LIC-".'),T.comment(" You can add it later to your .env file:"),T.comment(" CDK_INSIGHTS_LICENSE_KEY=your-key-here"),a.license="invalid-input";else{console.log(""),T.info(" You can grab a free key now (500 AI credits/month, no card required).");let h=await nh(" Open https://cdkinsights.dev/start in your browser? (Y/n): ");/^(n|no)$/i.test(h??"")||(nre("https://cdkinsights.dev/start")?T.success(" Opened the signup page in your browser."):(T.warning(" Could not launch the browser automatically. Visit:"),T.comment(" https://cdkinsights.dev/start"))),T.comment(" When you have a key, add it to your .env file:"),T.comment(" CDK_INSIGHTS_LICENSE_KEY=your-key-here"),a.license="skipped-interactive"}}else T.info(" To enable Pro features, add to your .env file:"),T.comment(" CDK_INSIGHTS_LICENSE_KEY=your-key-here"),a.license="non-interactive";else(f||m)&&(T.success("\u{1F511} License key detected"),a.license="pre-existing")}if(t.dryRun)a.telemetry="dry-run";else{let p=ire();if(p!==void 0)p?(T.success("\u{1F4CA} Telemetry preference detected (enabled). Leaving as-is."),a.telemetry="pre-existing-enabled"):(T.info("\u{1F4CA} Telemetry preference detected (disabled). Leaving as-is."),a.telemetry="pre-existing-disabled"),T.comment(" Edit .cdk-insights.json -> telemetry.enabled to change.");else if(process.stdin.isTTY){let f=Xs.join(process.cwd(),".env"),m=!!process.env.CDK_INSIGHTS_LICENSE_KEY||mt.existsSync(f)&&mt.readFileSync(f,"utf-8").includes("CDK_INSIGHTS_LICENSE_KEY=");console.log(""),T.info("\u{1F4CA} Anonymous Telemetry"),T.comment(" Sending aggregate counts (severities, rule histograms, fix activity) helps us"),T.comment(" prioritise rules and improve auto-fix coverage. The license ID is sha256-hashed"),T.comment(" before transmission. No resource names, file paths, or code ever leave the machine."),T.comment(" Requires a license key (free-tier is enough); without one, telemetry is a no-op."),console.log("");let g=await nh(" Enable telemetry? (y/N): "),h=/^(y|yes)$/i.test(g??"");rre(h),a.telemetry=h?"enabled":"disabled",h&&m?T.success(" Telemetry enabled in .cdk-insights.json."):h?(T.success(" Telemetry preference saved. Events will start sending once you add a license key."),T.comment(" Get a free key at https://cdkinsights.dev/start")):T.info(" Telemetry disabled. You can change this any time in .cdk-insights.json.")}else a.telemetry="non-interactive"}let c=!!s.devDependencies?.["cdk-insights"]||!!s.dependencies?.["cdk-insights"];if(t.dryRun){console.log(""),T.info("Dry run complete. No changes made.");return}let u=p=>{switch(p){case"pre-existing":return"detected (existing key)";case"saved-from-flag":return"saved (from --license-key)";case"saved-interactive":return"saved (entered during init)";case"invalid-input":return"not saved (invalid format)";case"skipped-interactive":case"skipped-flag":return"free tier (no key)";case"non-interactive":return"free tier (non-interactive run)"}},l=p=>{switch(p){case"enabled":return"enabled";case"disabled":return"disabled";case"pre-existing-enabled":return"enabled (already set, left as-is)";case"pre-existing-disabled":return"disabled (already set, left as-is)";case"non-interactive":return"disabled (non-interactive run)";case"dry-run":return"unchanged"}},d="\u2550".repeat(56);console.log(""),console.log(d),T.success("CDK Insights is set up."),console.log(""),T.comment(` \u2022 npm scripts added: ${a.scriptsAdded}`),T.comment(` \u2022 .cdk-insights.json: ${a.configFileCreated?"created":"already present"}`),T.comment(` \u2022 Telemetry: ${l(a.telemetry)}`),T.comment(` \u2022 License: ${u(a.license)}`),console.log(""),T.info("Next: scan your stacks"),console.log(" npm run cdk-insights:all"),console.log(""),T.info("Or fine-tune your config interactively"),console.log(" npx cdk-insights config setup"),console.log(d),c||(console.log(""),T.warning("cdk-insights is not installed as a dependency in this project."),T.info("Run: npm install --save-dev cdk-insights"))}};lt();Cl();var c5={command:"reset",describe:"Clear saved prompt answers and CLI preferences",handler:()=>{km(),re.info("\u{1F5D1}\uFE0F Cleared saved CLI preferences.")}};var g5=require("node:child_process"),wi=oe(require("node:fs")),rh=oe(require("node:path"));Kx();Of();p5();lt();var f5="2.251.0",m5=async(t,e,s)=>{if(wi.existsSync(rh.join(t,"node_modules",e)))return;if(!await pc({message:s,default:!0})){re.info(`Skipping ${e} installation.`);return}let i=wi.existsSync(rh.join(t,"yarn.lock")),o=i?"yarn":"npm",a=i?["add","-D",e]:["install","--save-dev",e];re.info(`Installing ${e}...`);try{(0,g5.execFileSync)(o,a,{stdio:"inherit"})}catch{re.error(`Failed to install ${e}. Please install it manually.`)}},cre=(t,e)=>{let s=(r,i)=>e?`const { ${r.join(", ")} } = require('${i}');`:`import { ${r.join(", ")} } from '${i}';`,n={imports:[],body:[]};switch(t){case"aspect-and-plugin":n.imports.push(s(["Aspects","Validations"],"aws-cdk-lib")),n.imports.push(s(["createCdkInsightsAspect","CdkInsightsPolicyValidationPlugin"],"cdk-insights")),n.body.push("Aspects.of(app).add(createCdkInsightsAspect());"),n.body.push("Validations.of(app).addPlugins(new CdkInsightsPolicyValidationPlugin());");break;case"plugin-only":n.imports.push(s(["Validations"],"aws-cdk-lib")),n.imports.push(s(["CdkInsightsPolicyValidationPlugin"],"cdk-insights")),n.body.push("Validations.of(app).addPlugins(new CdkInsightsPolicyValidationPlugin());");break;case"aspect-only":n.imports.push(s(["Aspects"],"aws-cdk-lib")),n.imports.push(s(["createCdkInsightsAspect"],"cdk-insights")),n.body.push("Aspects.of(app).add(createCdkInsightsAspect());");break;case"cdk-nag-only":n.imports.push(s(["Aspects"],"aws-cdk-lib")),n.imports.push(s(["AwsSolutionsChecks"],"cdk-nag")),n.body.push("Aspects.of(app).add(new AwsSolutionsChecks());");break;case"skip":break}return n},ure=(t,e)=>e.body.every(s=>t.includes(s)),lre=(t,e)=>{let s=t,n=e.imports.filter(o=>!t.includes(o));n.length>0&&(s=`${n.join(`
|
|
@@ -573,7 +573,7 @@ ${t.body.join(`
|
|
|
573
573
|
\u2705 Configuration saved successfully!`),console.log(`
|
|
574
574
|
\u{1F4CB} Your current configuration:`),console.log(JSON.stringify(t,null,2))}finally{s.close()}},fre=()=>{let t=qn();console.log("\u{1F4CB} Current Configuration:"),console.log(JSON.stringify(t,null,2))},mre=t=>{let{key:e,value:s}=t;if(t.help){$l(e);return}s||(console.log(`
|
|
575
575
|
\u274C No value provided for ${e}`),$l(e),process.exit(1));let n=qn(),r;try{e==="services"||e==="ruleFilter"?r=s.split(",").map(o=>o.trim()):e==="cache"?r=JSON.parse(s):s.toLowerCase()==="true"||s.toLowerCase()==="false"?r=s.toLowerCase()==="true":Number.isNaN(Number(s))?r=s:r=Number(s)}catch{re.error(`\u274C Invalid value for ${e}: ${s}`),$l(e),process.exit(1)}let i=tC[e];i&&(i.type==="boolean"&&typeof r!="boolean"&&(re.error(`\u274C ${e} must be a boolean (true/false)`),$l(e),process.exit(1)),i.type==="array"&&!Array.isArray(r)&&(re.error(`\u274C ${e} must be a comma-separated list`),$l(e),process.exit(1))),n[e]=r,vl(n),re.info(`\u2714\uFE0F ${e} = ${JSON.stringify(r)}`)},hre=t=>{let{key:e}=t,s=qn();if(s[e]===void 0){re.warn(`\u26A0\uFE0F ${e} not set`);return}delete s[e],vl(s),re.info(`\u2714\uFE0F Removed ${e}`)},w5=new Set(["vi","vim","nvim","nano","emacs","code","subl","atom","gedit","kate","notepad","notepad++","micro","helix","pico"]),gre=t=>{let e=t.split("/").pop()||t;return w5.has(e.toLowerCase())},yre=()=>{let t=kp.get("EDITOR")||"vi";gre(t)||(re.error(`\u274C Unsupported editor: ${t}. Allowed editors: ${Array.from(w5).join(", ")}`),process.exit(1));let e=(0,ih.spawnSync)(t,[dre],{stdio:"inherit"});e.error&&(re.error("\u274C Editor error",{error:e.error.message}),process.exit(1)),re.info("\u2714\uFE0F Config saved")},sC=t=>t.teamId||process.env.CDK_INSIGHTS_TEAM_ID||void 0,nC=()=>{let t=kp.get("CDK_INSIGHTS_LICENSE_KEY");if(!t)throw new Error("CDK_INSIGHTS_LICENSE_KEY environment variable is required for team config operations");return{"Content-Type":"application/json","x-api-key":t}},rC=()=>kp.get("CDK_INSIGHTS_API_URL")||"https://api.cdkinsights.dev",xre=async t=>{let e=sC(t);e||(console.error("\u274C Team ID required. Use --team-id or set CDK_INSIGHTS_TEAM_ID env var."),process.exit(1));try{console.log("\u{1F4E5} Fetching team configurations...");let n=(await Rt.get(`${rC()}/v1/teams/${e}/configs`,{headers:nC()})).data;n.success||(console.error(`\u274C ${n.error||n.message}`),process.exit(1));let i=n.configurations?.find(u=>u.isDefault);if(!i){console.log('\u2139\uFE0F No default team configuration found. Use "config team-configs" to list available configs.');return}let o=Sl(i.configData),c={...qn(),...o};vl(c),console.log(`\u2705 Pulled team config "${i.configName}" (v${i.version}) to .cdk-insights.json`)}catch(s){console.error(`\u274C Failed to pull config: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}},bre=async t=>{let e=sC(t);e||(console.error("\u274C Team ID required. Use --team-id or set CDK_INSIGHTS_TEAM_ID env var."),process.exit(1));try{let s=qn(),n=t.name||"CLI Config",r=t.description||"";console.log(`\u{1F4E4} Pushing local config as "${n}"...`);let o=(await Rt.post(`${rC()}/v1/teams/${e}/configs`,{configName:n,configDescription:r,configData:s},{headers:nC()})).data;o.success||(console.error(`\u274C ${o.error||o.message}`),process.exit(1));let a=o.configuration;console.log(`\u2705 Config pushed as "${a?.configName}" (v${a?.version})`)}catch(s){console.error(`\u274C Failed to push config: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}},Sre=async t=>{let e=sC(t);e||(console.error("\u274C Team ID required. Use --team-id or set CDK_INSIGHTS_TEAM_ID env var."),process.exit(1));try{console.log(`\u{1F4CB} Listing team configurations...
|
|
576
|
-
`);let n=(await Rt.get(`${rC()}/v1/teams/${e}/configs`,{headers:nC()})).data;n.success||(console.error(`\u274C ${n.error||n.message}`),process.exit(1));let r=n.configurations;if(!r||r.length===0){console.log(' No configurations found. Use "config push" to share your config with the team.');return}for(let i of r){let o=i.updatedAt?new Date(i.updatedAt*1e3).toISOString().replace("T"," ").split(".")[0]:"-",a=i.isDefault?" [DEFAULT]":"";console.log(` ${i.configName||"Unnamed"}${a} (v${i.version||1})`),i.configDescription&&console.log(` ${i.configDescription}`),console.log(` Updated: ${o}`),console.log("")}}catch(s){console.error(`\u274C Failed to list configs: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}},vre=async t=>{let{path:e}=t,s=(0,C5.promisify)(ih.exec),n=e||process.cwd();re.info(`\u{1F6E0}\uFE0F Running 'cdk synth' in ${n}...`);try{let{stderr:r}=await s("cdk synth",{cwd:n,env:{...process.env,CDK_DEBUG:"true"}});r&&re.error(r)}catch(r){re.error("\u274C Failed to synthesize stacks",{error:r instanceof Error?r.message:String(r)}),process.exit(1)}},Cre=()=>{re.info("\u{1F5D1}\uFE0F Clearing caches..."),NI(),ZI();let t=G0();re.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),re.info(`\u{1F4CA} Cache status: ${t.cacheFileExists?"Files found":"No persistent cache files"}`)},Dre=()=>{re.info("\u{1F4CA} Cache Status:");let t=G0();if(re.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),re.info(`\u{1F4C2} Directory exists: ${t.cacheDirExists?"Yes":"No"}`),re.info(`\u{1F4C4} Cache file exists: ${t.cacheFileExists?"Yes":"No"}`),t.cacheSize!==void 0){let e=(t.cacheSize/1024).toFixed(2);re.info(`\u{1F4CF} Cache file size: ${e} KB`)}re.info(`\u2699\uFE0F Cache enabled: ${$I()?"Yes":"No"}`),re.info("\u2139\uFE0F Note: Current cache is in-memory and clears on process restart")},wre=()=>{let t=new D5.default({head:["Command/Option","Description"],colWidths:[30,80]});return t.push(["COMMANDS",""],["scan [stackName]","Scan CDK stacks for best practices and security issues"],["fix","Apply mechanical fixes for findings whose remediation is unambiguous (defaults to dry-run; pass --apply)"],["init","Add cdk-insights npm scripts to your package.json"],["config <action>","Manage project-level configuration"],["synth","Run `cdk synth` automatically before analysis"],["hook","Install Git pre-commit hook for CDK Insights"],["reset","Clear saved prompt answers and CLI preferences"],["clear-cache","Clear the analysis cache"],["cache-status","Show cache status and statistics"],["setup","Interactive setup: install the CDK Insights aspect, Validations plugin, or AwsSolutionsChecks"],["",""]),t.push(["SCAN OPTIONS",""],["--output, -o","Output format: json, table, markdown, summary, sarif, github-actions"],["--format","Alias for --output"],["--all, -a","Analyze all available stacks"],["--services","Comma-separated list of AWS services to analyze"],["--with-issue","Create GitHub issues for findings (markdown output only)"],["--github","Alias for --with-issue"],["--redact","Redact sensitive resource names in output"],["--summaryOnly","Only show summary in console"],["--synth","Run `cdk synth` before analysis"],["--ci","Run in CI mode (no prompts)"],["--yes, -y","Skip prompts and use saved/default values"],["--reset","Clear saved config and start fresh"],["--failOnCritical","Exit with code 1 if critical issues found"],["--ruleFilter","Filter findings by rule IDs or categories"],["--noCache","Disable cache and force fresh analysis"],["--allow-overuse","Allow AI analysis even when exceeding paid allowance (extra usage charged)"],["--local","Run static analysis only (skip AI even with valid license)"],["--warn-sensitive","Treat sensitive data as warning (does not fail CI)"],["--prComment","Post analysis summary as a PR comment (GitHub Actions only)"],["--model","AI model alias (e.g. nova-lite, mistral-14b, llama-3-3-70b). Tier-gated."],["--diff","Filter findings to only those new since the saved baseline (.cdk-insights-baseline.json)"],["--writeBaseline","Save current findings as the baseline; suppresses fail-on-critical and skips rendering"],["--baseline","Override path to the baseline file"],["",""]),t.push(["FIX OPTIONS",""],["--rule","Only fix findings for this rule ID (e.g. AwsSolutions-S10). Without this flag, fixes every supported rule."],["--dry-run","Preview changes without writing files. Default behaviour; pass --apply to disable."],["--apply","Write fixes to disk. Implies --dry-run=false."],["",""]),t.push(["CONFIG SUBCOMMANDS",""],["config list","Show current configuration"],["config set <key> <value>","Set a configuration key"],["config unset <key>","Remove a configuration key"],["config edit","Open config file in your editor"],["config setup","Interactive setup to configure CDK Insights"],["",""]),t.push(["GLOBAL OPTIONS",""],["--help, -h","Show help information"],["--version, -v","Show version information"]),t.toString()},Are={command:"config <action> [key] [value]",describe:"Manage project-level configuration",builder:t=>t.command({command:"list",describe:"Show current configuration",handler:fre}).command({command:"set <key> <value>",describe:"Set a configuration key",builder:e=>e.positional("key",{type:"string",choices:["stackName","output","services","redact","withIssue","summaryOnly","synth","ruleFilter","failOnCritical","noCache","allowOveruse","local","cache","sensitiveDataDetection"],describe:"Configuration field to set"}).positional("value",{type:"string",describe:"Value to set (use --help for field-specific help)"}).option("help",{type:"boolean",describe:"Show detailed help for the specified field"}),handler:mre}).command({command:"unset <key>",describe:"Remove a configuration key",builder:e=>e.positional("key",{type:"string",choices:["stackName","output","services","redact","withIssue","summaryOnly","synth","ruleFilter","failOnCritical","noCache","allowOveruse","local","cache","sensitiveDataDetection"],describe:"Configuration field to remove"}),handler:hre}).command({command:"edit",describe:"Open config file in your editor",handler:yre}).command({command:"setup",describe:"Interactive setup to configure CDK Insights",handler:pre}).command({command:"pull",describe:"Pull the team default configuration to local .cdk-insights.json",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}),handler:xre}).command({command:"push",describe:"Push local .cdk-insights.json as a team configuration",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}).option("name",{type:"string",describe:"Configuration name",default:"CLI Config"}).option("description",{type:"string",describe:"Configuration description",default:""}),handler:bre}).command({command:"team-configs",describe:"List available team configurations",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}),handler:Sre}).demandCommand(1).help(),handler:()=>{}},Ere=()=>{DR(Qg(process.argv)).scriptName("cdk-insights").version("1.
|
|
576
|
+
`);let n=(await Rt.get(`${rC()}/v1/teams/${e}/configs`,{headers:nC()})).data;n.success||(console.error(`\u274C ${n.error||n.message}`),process.exit(1));let r=n.configurations;if(!r||r.length===0){console.log(' No configurations found. Use "config push" to share your config with the team.');return}for(let i of r){let o=i.updatedAt?new Date(i.updatedAt*1e3).toISOString().replace("T"," ").split(".")[0]:"-",a=i.isDefault?" [DEFAULT]":"";console.log(` ${i.configName||"Unnamed"}${a} (v${i.version||1})`),i.configDescription&&console.log(` ${i.configDescription}`),console.log(` Updated: ${o}`),console.log("")}}catch(s){console.error(`\u274C Failed to list configs: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}},vre=async t=>{let{path:e}=t,s=(0,C5.promisify)(ih.exec),n=e||process.cwd();re.info(`\u{1F6E0}\uFE0F Running 'cdk synth' in ${n}...`);try{let{stderr:r}=await s("cdk synth",{cwd:n,env:{...process.env,CDK_DEBUG:"true"}});r&&re.error(r)}catch(r){re.error("\u274C Failed to synthesize stacks",{error:r instanceof Error?r.message:String(r)}),process.exit(1)}},Cre=()=>{re.info("\u{1F5D1}\uFE0F Clearing caches..."),NI(),ZI();let t=G0();re.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),re.info(`\u{1F4CA} Cache status: ${t.cacheFileExists?"Files found":"No persistent cache files"}`)},Dre=()=>{re.info("\u{1F4CA} Cache Status:");let t=G0();if(re.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),re.info(`\u{1F4C2} Directory exists: ${t.cacheDirExists?"Yes":"No"}`),re.info(`\u{1F4C4} Cache file exists: ${t.cacheFileExists?"Yes":"No"}`),t.cacheSize!==void 0){let e=(t.cacheSize/1024).toFixed(2);re.info(`\u{1F4CF} Cache file size: ${e} KB`)}re.info(`\u2699\uFE0F Cache enabled: ${$I()?"Yes":"No"}`),re.info("\u2139\uFE0F Note: Current cache is in-memory and clears on process restart")},wre=()=>{let t=new D5.default({head:["Command/Option","Description"],colWidths:[30,80]});return t.push(["COMMANDS",""],["scan [stackName]","Scan CDK stacks for best practices and security issues"],["fix","Apply mechanical fixes for findings whose remediation is unambiguous (defaults to dry-run; pass --apply)"],["init","Add cdk-insights npm scripts to your package.json"],["config <action>","Manage project-level configuration"],["synth","Run `cdk synth` automatically before analysis"],["hook","Install Git pre-commit hook for CDK Insights"],["reset","Clear saved prompt answers and CLI preferences"],["clear-cache","Clear the analysis cache"],["cache-status","Show cache status and statistics"],["setup","Interactive setup: install the CDK Insights aspect, Validations plugin, or AwsSolutionsChecks"],["",""]),t.push(["SCAN OPTIONS",""],["--output, -o","Output format: json, table, markdown, summary, sarif, github-actions"],["--format","Alias for --output"],["--all, -a","Analyze all available stacks"],["--services","Comma-separated list of AWS services to analyze"],["--with-issue","Create GitHub issues for findings (markdown output only)"],["--github","Alias for --with-issue"],["--redact","Redact sensitive resource names in output"],["--summaryOnly","Only show summary in console"],["--synth","Run `cdk synth` before analysis"],["--ci","Run in CI mode (no prompts)"],["--yes, -y","Skip prompts and use saved/default values"],["--reset","Clear saved config and start fresh"],["--failOnCritical","Exit with code 1 if critical issues found"],["--ruleFilter","Filter findings by rule IDs or categories"],["--noCache","Disable cache and force fresh analysis"],["--allow-overuse","Allow AI analysis even when exceeding paid allowance (extra usage charged)"],["--local","Run static analysis only (skip AI even with valid license)"],["--warn-sensitive","Treat sensitive data as warning (does not fail CI)"],["--prComment","Post analysis summary as a PR comment (GitHub Actions only)"],["--model","AI model alias (e.g. nova-lite, mistral-14b, llama-3-3-70b). Tier-gated."],["--diff","Filter findings to only those new since the saved baseline (.cdk-insights-baseline.json)"],["--writeBaseline","Save current findings as the baseline; suppresses fail-on-critical and skips rendering"],["--baseline","Override path to the baseline file"],["",""]),t.push(["FIX OPTIONS",""],["--rule","Only fix findings for this rule ID (e.g. AwsSolutions-S10). Without this flag, fixes every supported rule."],["--dry-run","Preview changes without writing files. Default behaviour; pass --apply to disable."],["--apply","Write fixes to disk. Implies --dry-run=false."],["",""]),t.push(["CONFIG SUBCOMMANDS",""],["config list","Show current configuration"],["config set <key> <value>","Set a configuration key"],["config unset <key>","Remove a configuration key"],["config edit","Open config file in your editor"],["config setup","Interactive setup to configure CDK Insights"],["",""]),t.push(["GLOBAL OPTIONS",""],["--help, -h","Show help information"],["--version, -v","Show version information"]),t.toString()},Are={command:"config <action> [key] [value]",describe:"Manage project-level configuration",builder:t=>t.command({command:"list",describe:"Show current configuration",handler:fre}).command({command:"set <key> <value>",describe:"Set a configuration key",builder:e=>e.positional("key",{type:"string",choices:["stackName","output","services","redact","withIssue","summaryOnly","synth","ruleFilter","failOnCritical","noCache","allowOveruse","local","cache","sensitiveDataDetection"],describe:"Configuration field to set"}).positional("value",{type:"string",describe:"Value to set (use --help for field-specific help)"}).option("help",{type:"boolean",describe:"Show detailed help for the specified field"}),handler:mre}).command({command:"unset <key>",describe:"Remove a configuration key",builder:e=>e.positional("key",{type:"string",choices:["stackName","output","services","redact","withIssue","summaryOnly","synth","ruleFilter","failOnCritical","noCache","allowOveruse","local","cache","sensitiveDataDetection"],describe:"Configuration field to remove"}),handler:hre}).command({command:"edit",describe:"Open config file in your editor",handler:yre}).command({command:"setup",describe:"Interactive setup to configure CDK Insights",handler:pre}).command({command:"pull",describe:"Pull the team default configuration to local .cdk-insights.json",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}),handler:xre}).command({command:"push",describe:"Push local .cdk-insights.json as a team configuration",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}).option("name",{type:"string",describe:"Configuration name",default:"CLI Config"}).option("description",{type:"string",describe:"Configuration description",default:""}),handler:bre}).command({command:"team-configs",describe:"List available team configurations",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}),handler:Sre}).demandCommand(1).help(),handler:()=>{}},Ere=()=>{DR(Qg(process.argv)).scriptName("cdk-insights").version("1.29.0").usage("Usage: $0 <command> [options]").command(QN).command(e5).command(a5).command(c5).command(x5).command(b5).command(Are).command("hook","Install Git pre-commit hook for CDK Insights",()=>{},()=>t5()).command("synth","Run `cdk synth` automatically before analysis",t=>t.option("path",{type:"string",describe:"Path to the CDK project (defaults to current directory)"}),vre).command("clear-cache","Clear the analysis cache",()=>{},Cre).command("cache-status","Show the current cache status",()=>{},Dre).demandCommand(1,"Please specify a command.").strict().help().wrap(null).epilog(wre()).parse()};Ere();
|
|
577
577
|
/*! Bundled license information:
|
|
578
578
|
|
|
579
579
|
mime-db/index.js:
|
package/dist/index.js
CHANGED
|
@@ -77,7 +77,7 @@ ${JSON.stringify(se)}`}).join(`
|
|
|
77
77
|
`)!=-1,n=this._styles,r=n.length;r--;){var i=gn[n[r]];t=i.open+t.replace(i.closeRe,i.open)+i.close,s&&(t=t.replace(wP,function(o){return i.close+o+i.open}))}return t}De.setTheme=function(e){if(typeof e=="string"){console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));");return}for(var t in e)(function(s){De[s]=function(n){if(typeof e[s]=="object"){var r=n;for(var i in e[s])r=De[e[s][i]](r);return r}return De[e[s]](n)}})(t)};function kP(){var e={};return Object.keys(ev).forEach(function(t){e[t]={get:function(){return XD([t])}}}),e}var TP=function(t,s){var n=s.split("");return n=n.map(t),n.join("")};De.trap=UD();De.zalgo=$D();De.maps={};De.maps.america=HD()(De);De.maps.zebra=qD()(De);De.maps.rainbow=KD()(De);De.maps.random=YD()(De);for(JD in De.maps)(function(e){De[e]=function(t){return TP(De.maps[e],t)}})(JD);var JD;QD(De,kP())});var rv=T((zq,nv)=>{var PP=sv();nv.exports=PP});var cv=T((qq,Vo)=>{var{info:LP,debug:av}=zo(),vt=ul(),dl=class e{constructor(t){this.setOptions(t),this.x=null,this.y=null}setOptions(t){["boolean","number","bigint","string"].indexOf(typeof t)!==-1&&(t={content:""+t}),t=t||{},this.options=t;let s=t.content;if(["boolean","number","bigint","string"].indexOf(typeof s)!==-1)this.content=String(s);else if(!s)this.content=this.options.href||"";else throw new Error("Content needs to be a primitive, got: "+typeof s);this.colSpan=t.colSpan||1,this.rowSpan=t.rowSpan||1,this.options.href&&Object.defineProperty(this,"href",{get(){return this.options.href}})}mergeTableOptions(t,s){this.cells=s;let n=this.options.chars||{},r=t.chars,i=this.chars={};OP.forEach(function(u){pl(n,r,u,i)}),this.truncate=this.options.truncate||t.truncate;let o=this.options.style=this.options.style||{},a=t.style;pl(o,a,"padding-left",this),pl(o,a,"padding-right",this),this.head=o.head||a.head,this.border=o.border||a.border,this.fixedWidth=t.colWidths[this.x],this.lines=this.computeLines(t),this.desiredWidth=vt.strlen(this.content)+this.paddingLeft+this.paddingRight,this.desiredHeight=this.lines.length}computeLines(t){let s=t.wordWrap||t.textWrap,{wordWrap:n=s}=this.options;if(this.fixedWidth&&n){if(this.fixedWidth-=this.paddingLeft+this.paddingRight,this.colSpan){let o=1;for(;o<this.colSpan;)this.fixedWidth+=t.colWidths[this.x+o],o++}let{wrapOnWordBoundary:r=!0}=t,{wrapOnWordBoundary:i=r}=this.options;return this.wrapLines(vt.wordWrap(this.fixedWidth,this.content,i))}return this.wrapLines(this.content.split(`
|
|
78
78
|
`))}wrapLines(t){let s=vt.colorizeLines(t);return this.href?s.map(n=>vt.hyperlink(this.href,n)):s}init(t){let s=this.x,n=this.y;this.widths=t.colWidths.slice(s,s+this.colSpan),this.heights=t.rowHeights.slice(n,n+this.rowSpan),this.width=this.widths.reduce(ov,-1),this.height=this.heights.reduce(ov,-1),this.hAlign=this.options.hAlign||t.colAligns[s],this.vAlign=this.options.vAlign||t.rowAligns[n],this.drawRight=s+this.colSpan==t.colWidths.length}draw(t,s){if(t=="top")return this.drawTop(this.drawRight);if(t=="bottom")return this.drawBottom(this.drawRight);let n=vt.truncate(this.content,10,this.truncate);t||LP(`${this.y}-${this.x}: ${this.rowSpan-t}x${this.colSpan} Cell ${n}`);let r=Math.max(this.height-this.lines.length,0),i;switch(this.vAlign){case"center":i=Math.ceil(r/2);break;case"bottom":i=r;break;default:i=0}if(t<i||t>=i+this.lines.length)return this.drawEmpty(this.drawRight,s);let o=this.lines.length>this.height&&t+1>=this.height;return this.drawLine(t-i,this.drawRight,o,s)}drawTop(t){let s=[];return this.cells?this.widths.forEach(function(n,r){s.push(this._topLeftChar(r)),s.push(vt.repeat(this.chars[this.y==0?"top":"mid"],n))},this):(s.push(this._topLeftChar(0)),s.push(vt.repeat(this.chars[this.y==0?"top":"mid"],this.width))),t&&s.push(this.chars[this.y==0?"topRight":"rightMid"]),this.wrapWithStyleColors("border",s.join(""))}_topLeftChar(t){let s=this.x+t,n;if(this.y==0)n=s==0?"topLeft":t==0?"topMid":"top";else if(s==0)n="leftMid";else if(n=t==0?"midMid":"bottomMid",this.cells&&(this.cells[this.y-1][s]instanceof e.ColSpanCell&&(n=t==0?"topMid":"mid"),t==0)){let i=1;for(;this.cells[this.y][s-i]instanceof e.ColSpanCell;)i++;this.cells[this.y][s-i]instanceof e.RowSpanCell&&(n="leftMid")}return this.chars[n]}wrapWithStyleColors(t,s){if(this[t]&&this[t].length)try{let n=rv();for(let r=this[t].length-1;r>=0;r--)n=n[this[t][r]];return n(s)}catch{return s}else return s}drawLine(t,s,n,r){let i=this.chars[this.x==0?"left":"middle"];if(this.x&&r&&this.cells){let d=this.cells[this.y+r][this.x-1];for(;d instanceof ni;)d=this.cells[d.y][d.x-1];d instanceof ri||(i=this.chars.rightMid)}let o=vt.repeat(" ",this.paddingLeft),a=s?this.chars.right:"",u=vt.repeat(" ",this.paddingRight),c=this.lines[t],l=this.width-(this.paddingLeft+this.paddingRight);n&&(c+=this.truncate||"\u2026");let p=vt.truncate(c,l,this.truncate);return p=vt.pad(p,l," ",this.hAlign),p=o+p+u,this.stylizeLine(i,p,a)}stylizeLine(t,s,n){return t=this.wrapWithStyleColors("border",t),n=this.wrapWithStyleColors("border",n),this.y===0&&(s=this.wrapWithStyleColors("head",s)),t+s+n}drawBottom(t){let s=this.chars[this.x==0?"bottomLeft":"bottomMid"],n=vt.repeat(this.chars.bottom,this.width),r=t?this.chars.bottomRight:"";return this.wrapWithStyleColors("border",s+n+r)}drawEmpty(t,s){let n=this.chars[this.x==0?"left":"middle"];if(this.x&&s&&this.cells){let o=this.cells[this.y+s][this.x-1];for(;o instanceof ni;)o=this.cells[o.y][o.x-1];o instanceof ri||(n=this.chars.rightMid)}let r=t?this.chars.right:"",i=vt.repeat(" ",this.width);return this.stylizeLine(n,i,r)}},ni=class{constructor(){}draw(t){return typeof t=="number"&&av(`${this.y}-${this.x}: 1x1 ColSpanCell`),""}init(){}mergeTableOptions(){}},ri=class{constructor(t){this.originalCell=t}init(t){let s=this.y,n=this.originalCell.y;this.cellOffset=s-n,this.offset=_P(t.rowHeights,n,this.cellOffset)}draw(t){return t=="top"?this.originalCell.draw(this.offset,this.cellOffset):t=="bottom"?this.originalCell.draw("bottom"):(av(`${this.y}-${this.x}: 1x${this.colSpan} RowSpanCell for ${this.originalCell.content}`),this.originalCell.draw(this.offset+1+t))}mergeTableOptions(){}};function iv(...e){return e.filter(t=>t!=null).shift()}function pl(e,t,s,n){let r=s.split("-");r.length>1?(r[1]=r[1].charAt(0).toUpperCase()+r[1].substr(1),r=r.join(""),n[r]=iv(e[r],e[s],t[r],t[s])):n[s]=iv(e[s],t[s])}function _P(e,t,s){let n=e[t];for(let r=1;r<s;r++)n+=1+e[t+r];return n}function ov(e,t){return e+t+1}var OP=["top","top-mid","top-left","top-right","bottom","bottom-mid","bottom-left","bottom-right","left","left-mid","mid","mid-mid","right","right-mid","middle"];Vo.exports=dl;Vo.exports.ColSpanCell=ni;Vo.exports.RowSpanCell=ri});var pv=T((Vq,lv)=>{var{warn:BP,debug:MP}=zo(),ml=cv(),{ColSpanCell:WP,RowSpanCell:NP}=ml;(function(){function e(m,f){return m[f]>0?e(m,f+1):f}function t(m){let f={};m.forEach(function(h,g){let b=0;h.forEach(function(S){S.y=g,S.x=g?e(f,b):b;let D=S.rowSpan||1,v=S.colSpan||1;if(D>1)for(let I=0;I<v;I++)f[S.x+I]=D;b=S.x+v}),Object.keys(f).forEach(S=>{f[S]--,f[S]<1&&delete f[S]})})}function s(m){let f=0;return m.forEach(function(h){h.forEach(function(g){f=Math.max(f,g.x+(g.colSpan||1))})}),f}function n(m){return m.length}function r(m,f){let h=m.y,g=m.y-1+(m.rowSpan||1),b=f.y,S=f.y-1+(f.rowSpan||1),D=!(h>S||b>g),v=m.x,I=m.x-1+(m.colSpan||1),O=f.x,L=f.x-1+(f.colSpan||1),E=!(v>L||O>I);return D&&E}function i(m,f,h){let g=Math.min(m.length-1,h),b={x:f,y:h};for(let S=0;S<=g;S++){let D=m[S];for(let v=0;v<D.length;v++)if(r(b,D[v]))return!0}return!1}function o(m,f,h,g){for(let b=h;b<g;b++)if(i(m,b,f))return!1;return!0}function a(m){m.forEach(function(f,h){f.forEach(function(g){for(let b=1;b<g.rowSpan;b++){let S=new NP(g);S.x=g.x,S.y=g.y+b,S.colSpan=g.colSpan,c(S,m[h+b])}})})}function u(m){for(let f=m.length-1;f>=0;f--){let h=m[f];for(let g=0;g<h.length;g++){let b=h[g];for(let S=1;S<b.colSpan;S++){let D=new WP;D.x=b.x+S,D.y=b.y,h.splice(g+1,0,D)}}}}function c(m,f){let h=0;for(;h<f.length&&f[h].x<m.x;)h++;f.splice(h,0,m)}function l(m){let f=n(m),h=s(m);MP(`Max rows: ${f}; Max cols: ${h}`);for(let g=0;g<f;g++)for(let b=0;b<h;b++)if(!i(m,b,g)){let S={x:b,y:g,colSpan:1,rowSpan:1};for(b++;b<h&&!i(m,b,g);)S.colSpan++,b++;let D=g+1;for(;D<f&&o(m,D,S.x,S.x+S.colSpan);)S.rowSpan++,D++;let v=new ml(S);v.x=S.x,v.y=S.y,BP(`Missing cell at ${v.y}-${v.x}.`),c(v,m[g])}}function p(m){return m.map(function(f){if(!Array.isArray(f)){let h=Object.keys(f)[0];f=f[h],Array.isArray(f)?(f=f.slice(),f.unshift(h)):f=[h,f]}return f.map(function(h){return new ml(h)})})}function d(m){let f=p(m);return t(f),l(f),a(f),u(f),f}lv.exports={makeTableLayout:d,layoutTable:t,addRowSpanCells:a,maxWidth:s,fillInTable:l,computeWidths:uv("colSpan","desiredWidth","x",1),computeHeights:uv("rowSpan","desiredHeight","y",1)}})();function uv(e,t,s,n){return function(r,i){let o=[],a=[],u={};i.forEach(function(c){c.forEach(function(l){(l[e]||1)>1?a.push(l):o[l[s]]=Math.max(o[l[s]]||0,l[t]||0,n)})}),r.forEach(function(c,l){typeof c=="number"&&(o[l]=c)});for(let c=a.length-1;c>=0;c--){let l=a[c],p=l[e],d=l[s],m=o[d],f=typeof r[d]=="number"?0:1;if(typeof m=="number")for(let h=1;h<p;h++)m+=1+o[d+h],typeof r[d+h]!="number"&&f++;else m=t==="desiredWidth"?l.desiredWidth-1:1,(!u[d]||u[d]<m)&&(u[d]=m);if(l[t]>m){let h=0;for(;f>0&&l[t]>m;){if(typeof r[d+h]!="number"){let g=Math.round((l[t]-m)/f);m+=g,o[d+h]+=g,f--}h++}}}Object.assign(r,o,u);for(let c=0;c<r.length;c++)r[c]=Math.max(n,r[c]||0)}}});var mv=T((Kq,dv)=>{var ds=zo(),UP=ul(),fl=pv(),Ko=class extends Array{constructor(t){super();let s=UP.mergeOptions(t);if(Object.defineProperty(this,"options",{value:s,enumerable:s.debug}),s.debug){switch(typeof s.debug){case"boolean":ds.setDebugLevel(ds.WARN);break;case"number":ds.setDebugLevel(s.debug);break;case"string":ds.setDebugLevel(parseInt(s.debug,10));break;default:ds.setDebugLevel(ds.WARN),ds.warn(`Debug option is expected to be boolean, number, or string. Received a ${typeof s.debug}`)}Object.defineProperty(this,"messages",{get(){return ds.debugMessages()}})}}toString(){let t=this,s=this.options.head&&this.options.head.length;s?(t=[this.options.head],this.length&&t.push.apply(t,this)):this.options.style.head=[];let n=fl.makeTableLayout(t);n.forEach(function(i){i.forEach(function(o){o.mergeTableOptions(this.options,n)},this)},this),fl.computeWidths(this.options.colWidths,n),fl.computeHeights(this.options.rowHeights,n),n.forEach(function(i){i.forEach(function(o){o.init(this.options)},this)},this);let r=[];for(let i=0;i<n.length;i++){let o=n[i],a=this.options.rowHeights[i];(i===0||!this.options.style.compact||i==1&&s)&&gl(o,"top",r);for(let u=0;u<a;u++)gl(o,u,r);i+1==n.length&&gl(o,"bottom",r)}return r.join(`
|
|
79
79
|
`)}get width(){return this.toString().split(`
|
|
80
|
-
`)[0].length}};Ko.reset=()=>ds.reset();function gl(e,t,s){let n=[];e.forEach(function(i){n.push(i.draw(t))});let r=n.join("");r.length&&s.push(r)}dv.exports=Ko});var gv=T((Zq,fv)=>{fv.exports=mv()});var hl=T((Jq,HP)=>{HP.exports={name:"cdk-insights",version:"1.
|
|
80
|
+
`)[0].length}};Ko.reset=()=>ds.reset();function gl(e,t,s){let n=[];e.forEach(function(i){n.push(i.draw(t))});let r=n.join("");r.length&&s.push(r)}dv.exports=Ko});var gv=T((Zq,fv)=>{fv.exports=mv()});var hl=T((Jq,HP)=>{HP.exports={name:"cdk-insights",version:"1.29.0",description:"AWS CDK security and cost analysis CLI. Free static scans via npm \u2014 no account needed. Sign up free to add AI-powered insights.",main:"dist/index.js",types:"dist/index.d.ts",bin:{"cdk-insights":"dist/entry.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.js"}},files:["dist/**/*","README.md","LICENSE"],scripts:{test:"vitest --run",lint:"biome lint src/",typecheck:"tsc --noEmit",format:"biome format --write src/",check:"biome check src/","check:schema-sync":"ts-node scripts/check-schema-sync.ts",build:"ts-node scripts/build.ts","build:dev":"CDK_INSIGHTS_ENVIRONMENT=dev CDK_INSIGHTS_API_URL=https://s2zhmjbwlj.execute-api.eu-west-2.amazonaws.com/v1 ts-node scripts/build.ts",start:"node dist/index.js",dev:"ts-node src/index.ts",prepare:"husky install && npm run build","start:dev":"CDK_ENV=local ts-node src/index.ts","ai-run":"ts-node src/index.ts",unlink:"npm unlink -g cdk-insights",link:"npm link","prepare:test":"npm run unlink && npm run build && npm run link","prepare:dev":"npm run unlink && npm run build:dev && npm run link","deploy:dev":"STAGE=dev cdk deploy","destroy:dev":"STAGE=dev cdk destroy","release:patch":"bumper release patch","release:minor":"bumper release minor","release:major":"bumper release major","release:dry-run":"bumper release patch --dry-run","changelog:preview":"bumper preview","changelog:generate":"bumper generate","validate:commits":"bumper validate","release:check":"npm run validate:commits && npm run test && npm run build","release:full":"npm run release:check && npm run changelog:generate","setup:bumper":"bumper setup","publish:beta":"npm run build && npm publish --tag beta && npm dist-tag add cdk-insights@$npm_package_version latest","publish:alpha":"npm run build && npm publish --tag alpha","publish:canary":"npm run build && npm publish --tag canary","publish:latest":"npm run build && npm publish --tag latest","version:beta":"npm version prerelease --preid=beta","version:alpha":"npm version prerelease --preid=alpha","version:rc":"npm version prerelease --preid=rc","cdk-insights":"node scripts/cdk-insights-wrapper.js",scan:"node scripts/cdk-insights-wrapper.js scan","scan:all":"node scripts/cdk-insights-wrapper.js scan --all","scan:json":"node scripts/cdk-insights-wrapper.js scan --format json","scan:markdown":"node scripts/cdk-insights-wrapper.js scan --format markdown","scan:summary":"node scripts/cdk-insights-wrapper.js scan --format summary","scan:with-issues":"node scripts/cdk-insights-wrapper.js scan --withIssue","cache:clear":"node scripts/cdk-insights-wrapper.js cache clear","cache:status":"node scripts/cdk-insights-wrapper.js cache status","demo:progress":"ts-node src/examples/progress-demo.ts","demo:single-line":"ts-node src/examples/single-line-progress-demo.ts","test:line-clearing":"ts-node src/examples/line-clearing-test.ts"},publishConfig:{access:"public"},keywords:["aws","cdk","cloudformation","analysis","security","cost-optimization","static-analysis","devops","infrastructure","aws-cdk","cloud-security","compliance"],author:"Lee Priest <lee@cdkinsights.dev>",license:"BUSL-1.1",homepage:"https://github.com/instancelabs/cdk-insights",bugs:"https://github.com/instancelabs/cdk-insights/issues",repository:{type:"git",url:"git+https://github.com/instancelabs/cdk-insights.git"},dependencies:{"@inquirer/prompts":"^7.4.1","@middy/core":"^6.1.6","@types/glob":"^8.1.0",axios:"^1.8.4",chalk:"^5.4.1",chokidar:"^3.6.0","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.5.0",envolution:"^1.4.1",glob:"^11.0.3",ora:"^8.2.0",strogger:"^2.0.3",yargs:"^17.7.2",zod:"^3.23.8"},devDependencies:{"@aws-sdk/client-dynamodb":"^3.788.0","@biomejs/biome":"^2.0.6","@commitlint/cli":"^19.8.1","@commitlint/config-conventional":"^19.8.1","@types/cli-progress":"^3.11.6","@types/jsonwebtoken":"^9.0.9","@types/node":"^22.14.1","@types/yargs":"^17.0.33","aws-cdk":"^2.1010.0","bumper-cli":"^1.6.0",esbuild:"^0.25.2",husky:"^8.0.3","ts-node":"^10.9.2",typescript:"^5.8.3",vitest:"^3.1.1"},peerDependencies:{"aws-cdk-lib":"^2.190.0","cdk-nag":"^2.35.73",constructs:"^10.4.2"},optionalDependencies:{"@aws-solutions-constructs/aws-apigateway-lambda":"^2.0.0","@aws-solutions-constructs/aws-lambda-stepfunctions":"^2.0.0","@aws-solutions-constructs/aws-s3-lambda":"^2.0.0"}}});var Nv={};fi(Nv,{STACK_TRACE_CONTEXT_KEY:()=>ra,ensureStackTraceInCdkJson:()=>AL,isStackTraceContextEnabledInCdkJson:()=>xL,patchCdkJsonForStackTrace:()=>Wv});var Fs,kl,ra,Wv,AL,xL,Uv=Ml(()=>{"use strict";Fs=K(require("node:fs")),kl=K(require("node:path")),ra="@aws-cdk/core:stackTrace",Wv=e=>{let t;try{t=JSON.parse(e)}catch{return{status:"invalid-json"}}if(t===null||typeof t!="object"||Array.isArray(t))return{status:"invalid-json"};let s=t,n=s.context,r=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{};if(r[ra]===!0)return{status:"already-set",updated:e};r[ra]=!0;let i={...s,context:r},o=e.endsWith(`
|
|
81
81
|
`)?`
|
|
82
82
|
`:"";return{status:"added",updated:`${JSON.stringify(i,null,2)}${o}`}},AL=e=>{let t=kl.join(e,"cdk.json");if(!Fs.existsSync(t))return{status:"missing",cdkJsonPath:t};let s=Fs.readFileSync(t,"utf-8"),n=Wv(s);return n.status==="invalid-json"?{status:"invalid-json",cdkJsonPath:t}:n.status==="already-set"?{status:"already-set",cdkJsonPath:t}:(Fs.writeFileSync(t,n.updated,"utf-8"),{status:"added",cdkJsonPath:t})},xL=e=>{try{let t=kl.join(e,"cdk.json");if(!Fs.existsSync(t))return!1;let s=JSON.parse(Fs.readFileSync(t,"utf-8"));if(!s||typeof s!="object"||Array.isArray(s))return!1;let n=s.context;return!n||typeof n!="object"||Array.isArray(n)?!1:n[ra]===!0}catch{return!1}}});var f_={};fi(f_,{CDK_INSIGHTS_ANNOTATION_PREFIX:()=>la,CDK_INSIGHTS_METADATA_VERSION:()=>_l,CDK_INSIGHTS_NAG_FINDING_PREFIX:()=>oa,CdkInsightsAspect:()=>ua,CdkInsightsPolicyValidationPlugin:()=>li,ExtremelyHelpfulConsoleLogger:()=>ui,SCAN_REPORT_SCHEMA_VERSION:()=>Jv,clearCaches:()=>Zv,createCdkInsightsAspect:()=>Kv,createCdkInsightsLogger:()=>qv,createCdkInsightsPolicyValidationPlugin:()=>cC,createExtremelyHelpfulConsoleLogger:()=>Vv,getCacheStats:()=>Yv,isCdkDebugEnabled:()=>Ol,runAnalysis:()=>m_});module.exports=Sa(f_);var dC=K(require("node:fs"));function pr(e,t){return function(){return e.apply(t,arguments)}}var{toString:SC}=Object.prototype,{getPrototypeOf:Da}=Object,{iterator:hi,toStringTag:Ul}=Symbol,yi=(e=>t=>{let s=SC.call(t);return e[s]||(e[s]=s.slice(8,-1).toLowerCase())})(Object.create(null)),Lt=e=>(e=e.toLowerCase(),t=>yi(t)===e),Si=e=>t=>typeof t===e,{isArray:bn}=Array,Sn=Si("undefined");function dr(e){return e!==null&&!Sn(e)&&e.constructor!==null&&!Sn(e.constructor)&&ot(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var jl=Lt("ArrayBuffer");function bC(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&jl(e.buffer),t}var DC=Si("string"),ot=Si("function"),$l=Si("number"),mr=e=>e!==null&&typeof e=="object",vC=e=>e===!0||e===!1,gi=e=>{if(yi(e)!=="object")return!1;let t=Da(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Ul in e)&&!(hi in e)},CC=e=>{if(!mr(e)||dr(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},AC=Lt("Date"),xC=Lt("File"),wC=Lt("Blob"),EC=Lt("FileList"),FC=e=>mr(e)&&ot(e.pipe),RC=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||ot(e.append)&&((t=yi(e))==="formdata"||t==="object"&&ot(e.toString)&&e.toString()==="[object FormData]"))},IC=Lt("URLSearchParams"),[kC,TC,PC,LC]=["ReadableStream","Request","Response","Headers"].map(Lt),_C=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function fr(e,t,{allOwnKeys:s=!1}={}){if(e===null||typeof e>"u")return;let n,r;if(typeof e!="object"&&(e=[e]),bn(e))for(n=0,r=e.length;n<r;n++)t.call(null,e[n],n,e);else{if(dr(e))return;let i=s?Object.getOwnPropertyNames(e):Object.keys(e),o=i.length,a;for(n=0;n<o;n++)a=i[n],t.call(null,e[a],a,e)}}function Gl(e,t){if(dr(e))return null;t=t.toLowerCase();let s=Object.keys(e),n=s.length,r;for(;n-- >0;)if(r=s[n],t===r.toLowerCase())return r;return null}var Ts=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Hl=e=>!Sn(e)&&e!==Ts;function ba(){let{caseless:e,skipUndefined:t}=Hl(this)&&this||{},s={},n=(r,i)=>{let o=e&&Gl(s,i)||i;gi(s[o])&&gi(r)?s[o]=ba(s[o],r):gi(r)?s[o]=ba({},r):bn(r)?s[o]=r.slice():(!t||!Sn(r))&&(s[o]=r)};for(let r=0,i=arguments.length;r<i;r++)arguments[r]&&fr(arguments[r],n);return s}var OC=(e,t,s,{allOwnKeys:n}={})=>(fr(t,(r,i)=>{s&&ot(r)?e[i]=pr(r,s):e[i]=r},{allOwnKeys:n}),e),BC=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),MC=(e,t,s,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),s&&Object.assign(e.prototype,s)},WC=(e,t,s,n)=>{let r,i,o,a={};if(t=t||{},e==null)return t;do{for(r=Object.getOwnPropertyNames(e),i=r.length;i-- >0;)o=r[i],(!n||n(o,e,t))&&!a[o]&&(t[o]=e[o],a[o]=!0);e=s!==!1&&Da(e)}while(e&&(!s||s(e,t))&&e!==Object.prototype);return t},NC=(e,t,s)=>{e=String(e),(s===void 0||s>e.length)&&(s=e.length),s-=t.length;let n=e.indexOf(t,s);return n!==-1&&n===s},UC=e=>{if(!e)return null;if(bn(e))return e;let t=e.length;if(!$l(t))return null;let s=new Array(t);for(;t-- >0;)s[t]=e[t];return s},jC=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Da(Uint8Array)),$C=(e,t)=>{let n=(e&&e[hi]).call(e),r;for(;(r=n.next())&&!r.done;){let i=r.value;t.call(e,i[0],i[1])}},GC=(e,t)=>{let s,n=[];for(;(s=e.exec(t))!==null;)n.push(s);return n},HC=Lt("HTMLFormElement"),zC=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(s,n,r){return n.toUpperCase()+r}),Nl=(({hasOwnProperty:e})=>(t,s)=>e.call(t,s))(Object.prototype),qC=Lt("RegExp"),zl=(e,t)=>{let s=Object.getOwnPropertyDescriptors(e),n={};fr(s,(r,i)=>{let o;(o=t(r,i,e))!==!1&&(n[i]=o||r)}),Object.defineProperties(e,n)},VC=e=>{zl(e,(t,s)=>{if(ot(e)&&["arguments","caller","callee"].indexOf(s)!==-1)return!1;let n=e[s];if(ot(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+s+"'")})}})},KC=(e,t)=>{let s={},n=r=>{r.forEach(i=>{s[i]=!0})};return bn(e)?n(e):n(String(e).split(t)),s},ZC=()=>{},YC=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function JC(e){return!!(e&&ot(e.append)&&e[Ul]==="FormData"&&e[hi])}var QC=e=>{let t=new Array(10),s=(n,r)=>{if(mr(n)){if(t.indexOf(n)>=0)return;if(dr(n))return n;if(!("toJSON"in n)){t[r]=n;let i=bn(n)?[]:{};return fr(n,(o,a)=>{let u=s(o,r+1);!Sn(u)&&(i[a]=u)}),t[r]=void 0,i}}return n};return s(e,0)},XC=Lt("AsyncFunction"),eA=e=>e&&(mr(e)||ot(e))&&ot(e.then)&&ot(e.catch),ql=((e,t)=>e?setImmediate:t?((s,n)=>(Ts.addEventListener("message",({source:r,data:i})=>{r===Ts&&i===s&&n.length&&n.shift()()},!1),r=>{n.push(r),Ts.postMessage(s,"*")}))(`axios@${Math.random()}`,[]):s=>setTimeout(s))(typeof setImmediate=="function",ot(Ts.postMessage)),tA=typeof queueMicrotask<"u"?queueMicrotask.bind(Ts):typeof process<"u"&&process.nextTick||ql,sA=e=>e!=null&&ot(e[hi]),C={isArray:bn,isArrayBuffer:jl,isBuffer:dr,isFormData:RC,isArrayBufferView:bC,isString:DC,isNumber:$l,isBoolean:vC,isObject:mr,isPlainObject:gi,isEmptyObject:CC,isReadableStream:kC,isRequest:TC,isResponse:PC,isHeaders:LC,isUndefined:Sn,isDate:AC,isFile:xC,isBlob:wC,isRegExp:qC,isFunction:ot,isStream:FC,isURLSearchParams:IC,isTypedArray:jC,isFileList:EC,forEach:fr,merge:ba,extend:OC,trim:_C,stripBOM:BC,inherits:MC,toFlatObject:WC,kindOf:yi,kindOfTest:Lt,endsWith:NC,toArray:UC,forEachEntry:$C,matchAll:GC,isHTMLForm:HC,hasOwnProperty:Nl,hasOwnProp:Nl,reduceDescriptors:zl,freezeMethods:VC,toObjectSet:KC,toCamelCase:zC,noop:ZC,toFiniteNumber:YC,findKey:Gl,global:Ts,isContextDefined:Hl,isSpecCompliantForm:JC,toJSONObject:QC,isAsyncFn:XC,isThenable:eA,setImmediate:ql,asap:tA,isIterable:sA};function Dn(e,t,s,n,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),s&&(this.config=s),n&&(this.request=n),r&&(this.response=r,this.status=r.status?r.status:null)}C.inherits(Dn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:C.toJSONObject(this.config),code:this.code,status:this.status}}});var Vl=Dn.prototype,Kl={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{Kl[e]={value:e}});Object.defineProperties(Dn,Kl);Object.defineProperty(Vl,"isAxiosError",{value:!0});Dn.from=(e,t,s,n,r,i)=>{let o=Object.create(Vl);C.toFlatObject(e,o,function(l){return l!==Error.prototype},c=>c!=="isAxiosError");let a=e&&e.message?e.message:"Error",u=t==null&&e?e.code:t;return Dn.call(o,a,u,s,n,r),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",i&&Object.assign(o,i),o};var G=Dn;var Qd=K(Jd(),1),Ii=Qd.default;function Ua(e){return C.isPlainObject(e)||C.isArray(e)}function em(e){return C.endsWith(e,"[]")?e.slice(0,-2):e}function Xd(e,t,s){return e?e.concat(t).map(function(r,i){return r=em(r),!s&&i?"["+r+"]":r}).join(s?".":""):t}function jx(e){return C.isArray(e)&&!e.some(Ua)}var $x=C.toFlatObject(C,{},null,function(t){return/^is[A-Z]/.test(t)});function Gx(e,t,s){if(!C.isObject(e))throw new TypeError("target must be an object");t=t||new(Ii||FormData),s=C.toFlatObject(s,{metaTokens:!0,dots:!1,indexes:!1},!1,function(h,g){return!C.isUndefined(g[h])});let n=s.metaTokens,r=s.visitor||l,i=s.dots,o=s.indexes,u=(s.Blob||typeof Blob<"u"&&Blob)&&C.isSpecCompliantForm(t);if(!C.isFunction(r))throw new TypeError("visitor must be a function");function c(f){if(f===null)return"";if(C.isDate(f))return f.toISOString();if(C.isBoolean(f))return f.toString();if(!u&&C.isBlob(f))throw new G("Blob is not supported. Use a Buffer instead.");return C.isArrayBuffer(f)||C.isTypedArray(f)?u&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function l(f,h,g){let b=f;if(f&&!g&&typeof f=="object"){if(C.endsWith(h,"{}"))h=n?h:h.slice(0,-2),f=JSON.stringify(f);else if(C.isArray(f)&&jx(f)||(C.isFileList(f)||C.endsWith(h,"[]"))&&(b=C.toArray(f)))return h=em(h),b.forEach(function(D,v){!(C.isUndefined(D)||D===null)&&t.append(o===!0?Xd([h],v,i):o===null?h:h+"[]",c(D))}),!1}return Ua(f)?!0:(t.append(Xd(g,h,i),c(f)),!1)}let p=[],d=Object.assign($x,{defaultVisitor:l,convertValue:c,isVisitable:Ua});function m(f,h){if(!C.isUndefined(f)){if(p.indexOf(f)!==-1)throw Error("Circular reference detected in "+h.join("."));p.push(f),C.forEach(f,function(b,S){(!(C.isUndefined(b)||b===null)&&r.call(t,b,C.isString(S)?S.trim():S,h,d))===!0&&m(b,h?h.concat(S):[S])}),p.pop()}}if(!C.isObject(e))throw new TypeError("data must be an object");return m(e),t}var fs=Gx;function tm(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function sm(e,t){this._pairs=[],e&&fs(e,this,t)}var nm=sm.prototype;nm.append=function(t,s){this._pairs.push([t,s])};nm.toString=function(t){let s=t?function(n){return t.call(this,n,tm)}:tm;return this._pairs.map(function(r){return s(r[0])+"="+s(r[1])},"").join("&")};var rm=sm;function Hx(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ls(e,t,s){if(!t)return e;let n=s&&s.encode||Hx;C.isFunction(s)&&(s={serialize:s});let r=s&&s.serialize,i;if(r?i=r(t,s):i=C.isURLSearchParams(t)?t.toString():new rm(t,s).toString(n),i){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}var ja=class{constructor(){this.handlers=[]}use(t,s,n){return this.handlers.push({fulfilled:t,rejected:s,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){C.forEach(this.handlers,function(n){n!==null&&t(n)})}},$a=ja;var wn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var cm=K(require("crypto"),1);var im=K(require("url"),1),om=im.default.URLSearchParams;var Ga="abcdefghijklmnopqrstuvwxyz",am="0123456789",um={DIGIT:am,ALPHA:Ga,ALPHA_DIGIT:Ga+Ga.toUpperCase()+am},zx=(e=16,t=um.ALPHA_DIGIT)=>{let s="",{length:n}=t,r=new Uint32Array(e);cm.default.randomFillSync(r);for(let i=0;i<e;i++)s+=t[r[i]%n];return s},lm={isNode:!0,classes:{URLSearchParams:om,FormData:Ii,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:um,generateString:zx,protocols:["http","https","file","data"]};var qa={};fi(qa,{hasBrowserEnv:()=>za,hasStandardBrowserEnv:()=>qx,hasStandardBrowserWebWorkerEnv:()=>Vx,navigator:()=>Ha,origin:()=>Kx});var za=typeof window<"u"&&typeof document<"u",Ha=typeof navigator=="object"&&navigator||void 0,qx=za&&(!Ha||["ReactNative","NativeScript","NS"].indexOf(Ha.product)<0),Vx=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Kx=za&&window.location.href||"http://localhost";var xe={...qa,...lm};function Va(e,t){return fs(e,new xe.classes.URLSearchParams,{visitor:function(s,n,r,i){return xe.isNode&&C.isBuffer(s)?(this.append(n,s.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}function Zx(e){return C.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function Yx(e){let t={},s=Object.keys(e),n,r=s.length,i;for(n=0;n<r;n++)i=s[n],t[i]=e[i];return t}function Jx(e){function t(s,n,r,i){let o=s[i++];if(o==="__proto__")return!0;let a=Number.isFinite(+o),u=i>=s.length;return o=!o&&C.isArray(r)?r.length:o,u?(C.hasOwnProp(r,o)?r[o]=[r[o],n]:r[o]=n,!a):((!r[o]||!C.isObject(r[o]))&&(r[o]=[]),t(s,n,r[o],i)&&C.isArray(r[o])&&(r[o]=Yx(r[o])),!a)}if(C.isFormData(e)&&C.isFunction(e.entries)){let s={};return C.forEachEntry(e,(n,r)=>{t(Zx(n),r,s,0)}),s}return null}var ki=Jx;function Qx(e,t,s){if(C.isString(e))try{return(t||JSON.parse)(e),C.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(s||JSON.stringify)(e)}var Ka={transitional:wn,adapter:["xhr","http","fetch"],transformRequest:[function(t,s){let n=s.getContentType()||"",r=n.indexOf("application/json")>-1,i=C.isObject(t);if(i&&C.isHTMLForm(t)&&(t=new FormData(t)),C.isFormData(t))return r?JSON.stringify(ki(t)):t;if(C.isArrayBuffer(t)||C.isBuffer(t)||C.isStream(t)||C.isFile(t)||C.isBlob(t)||C.isReadableStream(t))return t;if(C.isArrayBufferView(t))return t.buffer;if(C.isURLSearchParams(t))return s.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let a;if(i){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Va(t,this.formSerializer).toString();if((a=C.isFileList(t))||n.indexOf("multipart/form-data")>-1){let u=this.env&&this.env.FormData;return fs(a?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||r?(s.setContentType("application/json",!1),Qx(t)):t}],transformResponse:[function(t){let s=this.transitional||Ka.transitional,n=s&&s.forcedJSONParsing,r=this.responseType==="json";if(C.isResponse(t)||C.isReadableStream(t))return t;if(t&&C.isString(t)&&(n&&!this.responseType||r)){let o=!(s&&s.silentJSONParsing)&&r;try{return JSON.parse(t,this.parseReviver)}catch(a){if(o)throw a.name==="SyntaxError"?G.from(a,G.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:xe.classes.FormData,Blob:xe.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};C.forEach(["delete","get","head","post","put","patch"],e=>{Ka.headers[e]={}});var En=Ka;var Xx=C.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),pm=e=>{let t={},s,n,r;return e&&e.split(`
|
|
83
83
|
`).forEach(function(o){r=o.indexOf(":"),s=o.substring(0,r).trim().toLowerCase(),n=o.substring(r+1).trim(),!(!s||t[s]&&Xx[s])&&(s==="set-cookie"?t[s]?t[s].push(n):t[s]=[n]:t[s]=t[s]?t[s]+", "+n:n)}),t};var dm=Symbol("internals");function br(e){return e&&String(e).trim().toLowerCase()}function Ti(e){return e===!1||e==null?e:C.isArray(e)?e.map(Ti):String(e)}function ew(e){let t=Object.create(null),s=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=s.exec(e);)t[n[1]]=n[2];return t}var tw=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Za(e,t,s,n,r){if(C.isFunction(n))return n.call(this,t,s);if(r&&(t=s),!!C.isString(t)){if(C.isString(n))return t.indexOf(n)!==-1;if(C.isRegExp(n))return n.test(t)}}function sw(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,s,n)=>s.toUpperCase()+n)}function nw(e,t){let s=C.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+s,{value:function(r,i,o){return this[n].call(this,t,r,i,o)},configurable:!0})})}var Fn=class{constructor(t){t&&this.set(t)}set(t,s,n){let r=this;function i(a,u,c){let l=br(u);if(!l)throw new Error("header name must be a non-empty string");let p=C.findKey(r,l);(!p||r[p]===void 0||c===!0||c===void 0&&r[p]!==!1)&&(r[p||u]=Ti(a))}let o=(a,u)=>C.forEach(a,(c,l)=>i(c,l,u));if(C.isPlainObject(t)||t instanceof this.constructor)o(t,s);else if(C.isString(t)&&(t=t.trim())&&!tw(t))o(pm(t),s);else if(C.isObject(t)&&C.isIterable(t)){let a={},u,c;for(let l of t){if(!C.isArray(l))throw TypeError("Object iterator must return a key-value pair");a[c=l[0]]=(u=a[c])?C.isArray(u)?[...u,l[1]]:[u,l[1]]:l[1]}o(a,s)}else t!=null&&i(s,t,n);return this}get(t,s){if(t=br(t),t){let n=C.findKey(this,t);if(n){let r=this[n];if(!s)return r;if(s===!0)return ew(r);if(C.isFunction(s))return s.call(this,r,n);if(C.isRegExp(s))return s.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,s){if(t=br(t),t){let n=C.findKey(this,t);return!!(n&&this[n]!==void 0&&(!s||Za(this,this[n],n,s)))}return!1}delete(t,s){let n=this,r=!1;function i(o){if(o=br(o),o){let a=C.findKey(n,o);a&&(!s||Za(n,n[a],a,s))&&(delete n[a],r=!0)}}return C.isArray(t)?t.forEach(i):i(t),r}clear(t){let s=Object.keys(this),n=s.length,r=!1;for(;n--;){let i=s[n];(!t||Za(this,this[i],i,t,!0))&&(delete this[i],r=!0)}return r}normalize(t){let s=this,n={};return C.forEach(this,(r,i)=>{let o=C.findKey(n,i);if(o){s[o]=Ti(r),delete s[i];return}let a=t?sw(i):String(i).trim();a!==i&&delete s[i],s[a]=Ti(r),n[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let s=Object.create(null);return C.forEach(this,(n,r)=>{n!=null&&n!==!1&&(s[r]=t&&C.isArray(n)?n.join(", "):n)}),s}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,s])=>t+": "+s).join(`
|
|
@@ -120,7 +120,7 @@ ${z.comment("\u{1F4A1} Next Steps:")}`),$?(e.log(z.error(" \u274C Trial expire
|
|
|
120
120
|
`)},displayQuotaWarning:_=>{let{currentResourcesAnalyzed:B,maxResources:q,requestedResources:Z,isTrial:$}=_;if(!$)return;B+Z>q&&(e.log(`
|
|
121
121
|
${z.warning.bold("\u26A0\uFE0F AI credit allowance exceeded")}`),e.log(z.comment("\u2500".repeat(40))),e.log(z.warning(` You've used ${B}/${q} AI credits`)),e.log(z.warning(` This analysis would add ${Z} more`)),e.log(z.warning(` Total would be ${B+Z}/${q}`)),e.log(`
|
|
122
122
|
${z.info("\u{1F4CB} Falling back to static analysis only")}`),e.log(z.comment("\u{1F4A1} Upgrade to Pro for unlimited AI analysis: https://cdkinsights.dev/pricing")),e.log(`${z.comment("\u2500".repeat(40))}
|
|
123
|
-
`))}}},V=kT();var Vb=e=>e&&(e.Name||e.ResourceName||e.FunctionName)||"Unnamed";var Yu=null,Kb=e=>{Yu=e};var Ju=()=>{if(Yu&&!process.env.CI)try{Yu.saveToDisk(),Ye.info("\u{1F4BE} Cache saved to disk on exit")}catch(e){Ye.warn("\u26A0\uFE0F Could not save cache on exit",{error:e instanceof Error?e.message:String(e)})}};process.on("exit",Ju);process.on("SIGINT",()=>{Ju(),process.exit(0)});process.on("SIGTERM",()=>{Ju(),process.exit(0)});var TT={maxConcurrent:Gr.DEFAULT_MAX_CONCURRENT,retryAttempts:Gr.DEFAULT_RETRY_ATTEMPTS,retryDelay:Gr.DEFAULT_RETRY_DELAY_MS,timeoutMs:Gr.DEFAULT_TIMEOUT_MS},PT=e=>{if(!(e instanceof Error))return!1;let t=e.message??"";return t.startsWith("Polling timed out")||t==="Analysis timeout"||t.toLowerCase().includes("timeout")},No=(e,t)=>{let s=e.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return e;let[,n,r=""]=s;return`${tr(t,n)}${r}`},LT=e=>{let t=Pr({ttl:6e4,maxSize:1e3});return({analysisError:s,redactedId:n})=>{let r=s instanceof Error?s.message:"unknown",i=`${n}:${r}`,o=t.get(i)||0;return PT(s)?{status:"timeout",redactedId:n}:(t.set(i,o+1),o>e.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},_T=({analyzeResource:e,redactionMapping:t,aggregatedResult:s,errorHandler:n,config:r,authToken:i,fingerprint:o,stackName:a,analysisCache:u,originalResources:c,relationships:l,aiModelId:p})=>async({redactedId:d,redactedResources:m,findingsByResource:f,progressTracker:h})=>{let g=f.get(d)||[],b=m[d];if(!b)return{status:"skipped",redactedId:d};let D=lu(d,b,i,o,[]),v=pu(D),I=t[d];if(!I)return{status:"skipped",redactedId:d};let O=I,L=()=>(s[O]||(s[O]={issues:[]}),s[O]),E=u.get(v);if(E){let ce=(E.issues||[]).map(_=>({..._,resource:O,resourceId:O})),le=L();return le.issues.push(...dn({existing:le.issues,incoming:ce})),le.resourceName=E.resourceName,{status:"success",redactedId:d,resourceKey:O,remappedIssues:ce,resourceName:E.resourceName}}let H=tr(a,I),Y=tr("cdk-insights-stack",a),se=$i(I,l,c),ue={dependencies:se.dependencies.map(ce=>No(ce,a)),dependents:se.dependents.map(ce=>No(ce,a)),usageDescription:se.usageDescription};for(let ce=1;ce<=r.retryAttempts;ce++)try{let le=await Promise.race([e(Y,H,b,b.Type,i,o,g,h,ue,p),new Promise((q,Z)=>setTimeout(()=>Z(new Error("Analysis timeout")),r.timeoutMs))]);le.resourceId=O;let _=(le.issues||[]).map(q=>({...q,resource:O,resourceId:O})),B=L();return B.issues.push(...dn({existing:B.issues,incoming:_})),B.resourceName=le.resourceName,u.set(v,le,D),{status:"success",redactedId:d,resourceKey:O,remappedIssues:_,resourceName:le.resourceName}}catch(le){if(ce===r.retryAttempts)return n({analysisError:le,redactedId:d});await new Promise(_=>setTimeout(_,r.retryDelay*2**(ce-1)))}return{status:"fail",redactedId:d,error:new Error("Max retries exceeded")}},OT=async(e,t,s)=>{let n=Math.max(1,Math.floor(t)),r=0,i=Array.from({length:Math.min(n,e.length)}).map(async()=>{for(;r<e.length;){let o=r;r+=1;let a=e[o];await s(a)}});await Promise.allSettled(i)},BT=10,Zb=({analyzeResource:e,analyzeResourcesBatch:t,redactResources:s,config:n=TT})=>async({stackName:r,resources:i,authToken:o,existingFindingsMap:a,pathToLogicalId:u,fingerprint:c,noCache:l=!1,cacheConfig:p,aiModelId:d,aiBatchSize:m})=>{let f={},h=[],g={startTime:Date.now(),processedCount:0,successCount:0,failureCount:0,timeoutCount:0},{redactedResources:b,mapping:S}=s(i),D=BS(a,S,u),v=new Map;for(let $ of D){let N=v.get($.resourceId);N?N.push($):v.set($.resourceId,[$])}let I=Object.keys(b),O=I.length,L=Us(i),E=new xo({ttl:p?.ttl||6*60*60*1e3,maxSize:p?.maxSize||5e3,disabled:l||!p?.enabled});Kb(E);let H=LT(n),Y=_T({analyzeResource:e,redactionMapping:S,aggregatedResult:f,errorHandler:H,config:n,authToken:o,fingerprint:c,stackName:r,analysisCache:E,originalResources:i,relationships:L,aiModelId:d}),se=Mo.createSingleLineProgressTracker(O,"Analyzing resources with AI"),ue=Math.min(Math.max(1,Math.floor(m??1)),BT);if(ue>1&&!!t&&t){Ye.debug("Batched analysis enabled",{batchSize:ue,totalResources:O});let $=tr("cdk-insights-stack",r),N=M=>{let Q=$i(M,L,i);return{dependencies:Q.dependencies.map(ie=>No(ie,r)),dependents:Q.dependents.map(ie=>No(ie,r)),usageDescription:Q.usageDescription}};for(let M=0;M<I.length;M+=ue){let Q=I.slice(M,M+ue),ie=async()=>{for(let re of Q){let fe=await Y({redactedId:re,redactedResources:b,findingsByResource:v,progressTracker:se});switch(g.processedCount++,fe.status){case"success":g.successCount++;break;case"timeout":g.timeoutCount++,h.push({redactedId:re,resourceData:b[re],resourceType:b[re].Type,existingFindings:v.get(re)||[]});break;case"fail":case"skipped":g.failureCount++;break}}},ee=new Map,oe=[];for(let re of Q){let fe=b[re],X=S[re];if(!fe||!X){g.processedCount++,g.failureCount++;continue}let _e=lu(re,fe,o,c,[]),Re=pu(_e),it=E.get(Re);if(it){let hn=(it.issues||[]).map(ks=>({...ks,resource:X,resourceId:X}));f[X]||(f[X]={issues:[]});let qt=f[X];qt.issues.push(...dn({existing:qt.issues,incoming:hn})),qt.resourceName=it.resourceName,g.processedCount++,g.successCount++;continue}let es=tr(r,X);ee.set(es,{redactedId:re,originalResourceId:X,cacheKey:Re,cacheComponents:_e}),oe.push({stableResourceId:es,resourceData:fe,resourceType:fe.Type,context:N(X),existingFindings:v.get(re)||[]})}if(oe.length!==0)try{let re=await Promise.race([t($,oe,o,c,d),new Promise((fe,X)=>setTimeout(()=>X(new Error("Analysis timeout")),n.timeoutMs))]);for(let[fe,X]of ee){let _e=re.get(fe);if(g.processedCount++,!_e){Ye.warn(`Batched response missing entry for resource ${X.originalResourceId}`,{stableResourceId:fe,redactedId:X.redactedId}),g.failureCount++;continue}let Re=(_e.issues||[]).map(es=>({...es,resource:X.originalResourceId,resourceId:X.originalResourceId}));f[X.originalResourceId]||(f[X.originalResourceId]={issues:[]});let it=f[X.originalResourceId];it.issues.push(...dn({existing:it.issues,incoming:Re})),it.resourceName=_e.resourceName,E.set(X.cacheKey,{resourceId:X.originalResourceId,issues:_e.issues||[],resourceName:_e.resourceName},X.cacheComponents),g.successCount++}}catch(re){Ye.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:re instanceof Error?re.message:String(re),chunkSize:Q.length}),await ie()}}}else await OT(I,n.maxConcurrent,async $=>{Ye.debug(`Starting analysis for resource ${$}`,{redactedId:$,maxConcurrent:n.maxConcurrent});let N=await Y({redactedId:$,redactedResources:b,findingsByResource:v,progressTracker:se});switch(g.processedCount++,Ye.debug(`Resource ${$} analysis result: ${N.status}`,{redactedId:$,status:N.status,hasProgressTracker:!!se}),N.status){case"success":g.successCount++,Ye.debug(`Resource ${$} completed successfully`,{redactedId:$,resourceKey:N.resourceKey});break;case"timeout":g.timeoutCount++,Ye.warn(`Resource ${$} timed out`,{redactedId:$}),h.push({redactedId:$,resourceData:b[$],resourceType:b[$].Type,existingFindings:v.get($)||[]});break;case"fail":case"skipped":g.failureCount++,Ye.warn(`Resource ${$} failed or was skipped`,{redactedId:$,status:N.status});break}});let le=Date.now()-g.startTime,_=se.getStats();if(Ye.debug("Analysis completed with progress tracker stats",{progressTrackerStats:_,performanceMetrics:g,totalTime:le,totalResources:O,maxConcurrent:n.maxConcurrent}),V.analysisComplete(le,g.successCount,g.failureCount,g.timeoutCount),g.failureCount>0||g.timeoutCount>0){V.newline(),V.info("\u{1F4CA} Performance Analysis:");let $=g.successCount>0?Math.round(le/1e3/g.successCount):0;V.comment(` \u23F1\uFE0F Average completion time: ${$}s`),V.comment(` \u{1F4CA} Success rate: ${(g.successCount/O*100).toFixed(1)}%`)}if(h.length>0){V.newline(),V.warning("\u23F0 Timed Out Resources:"),V.comment(` \u{1F4CB} Total timed out: ${h.length}`);for(let $ of h){if(V.comment(` \u274C ${$.resourceType}: ${$.redactedId}`),$.resourceData?.Properties){let M=$.resourceData.Properties,Q=Vb(M);V.comment(` \u{1F4DD} Name: ${Q}`)}$.existingFindings.length>0&&V.comment(` \u{1F50D} Existing findings: ${$.existingFindings.length}`),$.resourceData?.Metadata&&V.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes($.resourceType)&&V.comment(" \u26A0\uFE0F Complex resource type - may require extended analysis time")}V.newline(),V.info("\u{1F4A1} Tip: Some resources are taking longer to analyze than expected."),V.comment(" This is normal for complex resources. The analysis will continue with the remaining resources."),V.warning(`Retrying ${h.length} resource${h.length===1?"":"s"} that need a little more time...`)}let B=new Set(Object.keys(f)),q=new Set(Object.values(S)),Z=Array.from(q).filter($=>!B.has($)||!f[$]?.issues?.length);if(Z.length>0){let $=E.getCachedResultsForResources(Z),N=0;for(let[M,Q]of Array.from($.entries())){if(f[M]?.issues?.length>0)continue;let ie=(Q.issues||[]).map(ee=>({...ee,resource:M,resourceId:M}));ie.length>0&&(f[M]||(f[M]={issues:[]}),f[M].issues.push(...ie),f[M].resourceName=Q.resourceName,N+=ie.length)}N>0}return f};var Qu=require("node:child_process"),Je=K(require("node:fs")),Xu=K(require("node:os")),Xr=K(require("node:path"));var Qb="1.28.0",MT={Security:"https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/",Reliability:"https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/","Performance Efficiency":"https://docs.aws.amazon.com/wellarchitected/latest/performance-efficiency-pillar/","Cost Optimization":"https://docs.aws.amazon.com/wellarchitected/latest/cost-optimization-pillar/","Operational Excellence":"https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/",Sustainability:"https://docs.aws.amazon.com/wellarchitected/latest/sustainability-pillar/"},Yb=e=>e.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),WT=(e,t)=>{let s=0;if(s+=2e3,t){let n=Object.values(e).filter(r=>{let i=r.sources.cdkInsights?.issues??[],o=r.sources.cdkNag?.issues??[];return i.length>0||o.length>0});s+=n.length*100}for(let[,n]of Object.entries(e)){let r=n.sources.cdkInsights?.issues??[],i=n.sources.cdkNag?.issues??[];for(let o of[...r,...i])s+=o.issue.length,s+=o.recommendation?.length||0,s+=o.codeSnippet?.length||0,s+=500}return s},NT=e=>e?e.split(`
|
|
123
|
+
`))}}},V=kT();var Vb=e=>e&&(e.Name||e.ResourceName||e.FunctionName)||"Unnamed";var Yu=null,Kb=e=>{Yu=e};var Ju=()=>{if(Yu&&!process.env.CI)try{Yu.saveToDisk(),Ye.info("\u{1F4BE} Cache saved to disk on exit")}catch(e){Ye.warn("\u26A0\uFE0F Could not save cache on exit",{error:e instanceof Error?e.message:String(e)})}};process.on("exit",Ju);process.on("SIGINT",()=>{Ju(),process.exit(0)});process.on("SIGTERM",()=>{Ju(),process.exit(0)});var TT={maxConcurrent:Gr.DEFAULT_MAX_CONCURRENT,retryAttempts:Gr.DEFAULT_RETRY_ATTEMPTS,retryDelay:Gr.DEFAULT_RETRY_DELAY_MS,timeoutMs:Gr.DEFAULT_TIMEOUT_MS},PT=e=>{if(!(e instanceof Error))return!1;let t=e.message??"";return t.startsWith("Polling timed out")||t==="Analysis timeout"||t.toLowerCase().includes("timeout")},No=(e,t)=>{let s=e.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return e;let[,n,r=""]=s;return`${tr(t,n)}${r}`},LT=e=>{let t=Pr({ttl:6e4,maxSize:1e3});return({analysisError:s,redactedId:n})=>{let r=s instanceof Error?s.message:"unknown",i=`${n}:${r}`,o=t.get(i)||0;return PT(s)?{status:"timeout",redactedId:n}:(t.set(i,o+1),o>e.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},_T=({analyzeResource:e,redactionMapping:t,aggregatedResult:s,errorHandler:n,config:r,authToken:i,fingerprint:o,stackName:a,analysisCache:u,originalResources:c,relationships:l,aiModelId:p})=>async({redactedId:d,redactedResources:m,findingsByResource:f,progressTracker:h})=>{let g=f.get(d)||[],b=m[d];if(!b)return{status:"skipped",redactedId:d};let D=lu(d,b,i,o,[]),v=pu(D),I=t[d];if(!I)return{status:"skipped",redactedId:d};let O=I,L=()=>(s[O]||(s[O]={issues:[]}),s[O]),E=u.get(v);if(E){let ce=(E.issues||[]).map(_=>({..._,resource:O,resourceId:O})),le=L();return le.issues.push(...dn({existing:le.issues,incoming:ce})),le.resourceName=E.resourceName,{status:"success",redactedId:d,resourceKey:O,remappedIssues:ce,resourceName:E.resourceName}}let H=tr(a,I),Y=tr("cdk-insights-stack",a),se=$i(I,l,c),ue={dependencies:se.dependencies.map(ce=>No(ce,a)),dependents:se.dependents.map(ce=>No(ce,a)),usageDescription:se.usageDescription};for(let ce=1;ce<=r.retryAttempts;ce++)try{let le=await Promise.race([e(Y,H,b,b.Type,i,o,g,h,ue,p),new Promise((q,Z)=>setTimeout(()=>Z(new Error("Analysis timeout")),r.timeoutMs))]);le.resourceId=O;let _=(le.issues||[]).map(q=>({...q,resource:O,resourceId:O})),B=L();return B.issues.push(...dn({existing:B.issues,incoming:_})),B.resourceName=le.resourceName,u.set(v,le,D),{status:"success",redactedId:d,resourceKey:O,remappedIssues:_,resourceName:le.resourceName}}catch(le){if(ce===r.retryAttempts)return n({analysisError:le,redactedId:d});await new Promise(_=>setTimeout(_,r.retryDelay*2**(ce-1)))}return{status:"fail",redactedId:d,error:new Error("Max retries exceeded")}},OT=async(e,t,s)=>{let n=Math.max(1,Math.floor(t)),r=0,i=Array.from({length:Math.min(n,e.length)}).map(async()=>{for(;r<e.length;){let o=r;r+=1;let a=e[o];await s(a)}});await Promise.allSettled(i)},BT=10,Zb=({analyzeResource:e,analyzeResourcesBatch:t,redactResources:s,config:n=TT})=>async({stackName:r,resources:i,authToken:o,existingFindingsMap:a,pathToLogicalId:u,fingerprint:c,noCache:l=!1,cacheConfig:p,aiModelId:d,aiBatchSize:m})=>{let f={},h=[],g={startTime:Date.now(),processedCount:0,successCount:0,failureCount:0,timeoutCount:0},{redactedResources:b,mapping:S}=s(i),D=BS(a,S,u),v=new Map;for(let $ of D){let N=v.get($.resourceId);N?N.push($):v.set($.resourceId,[$])}let I=Object.keys(b),O=I.length,L=Us(i),E=new xo({ttl:p?.ttl||6*60*60*1e3,maxSize:p?.maxSize||5e3,disabled:l||!p?.enabled});Kb(E);let H=LT(n),Y=_T({analyzeResource:e,redactionMapping:S,aggregatedResult:f,errorHandler:H,config:n,authToken:o,fingerprint:c,stackName:r,analysisCache:E,originalResources:i,relationships:L,aiModelId:d}),se=Mo.createSingleLineProgressTracker(O,"Analyzing resources with AI"),ue=Math.min(Math.max(1,Math.floor(m??1)),BT);if(ue>1&&!!t&&t){Ye.debug("Batched analysis enabled",{batchSize:ue,totalResources:O});let $=tr("cdk-insights-stack",r),N=M=>{let Q=$i(M,L,i);return{dependencies:Q.dependencies.map(ie=>No(ie,r)),dependents:Q.dependents.map(ie=>No(ie,r)),usageDescription:Q.usageDescription}};for(let M=0;M<I.length;M+=ue){let Q=I.slice(M,M+ue),ie=async()=>{for(let re of Q){let fe=await Y({redactedId:re,redactedResources:b,findingsByResource:v,progressTracker:se});switch(g.processedCount++,fe.status){case"success":g.successCount++;break;case"timeout":g.timeoutCount++,h.push({redactedId:re,resourceData:b[re],resourceType:b[re].Type,existingFindings:v.get(re)||[]});break;case"fail":case"skipped":g.failureCount++;break}}},ee=new Map,oe=[];for(let re of Q){let fe=b[re],X=S[re];if(!fe||!X){g.processedCount++,g.failureCount++;continue}let _e=lu(re,fe,o,c,[]),Re=pu(_e),it=E.get(Re);if(it){let hn=(it.issues||[]).map(ks=>({...ks,resource:X,resourceId:X}));f[X]||(f[X]={issues:[]});let qt=f[X];qt.issues.push(...dn({existing:qt.issues,incoming:hn})),qt.resourceName=it.resourceName,g.processedCount++,g.successCount++;continue}let es=tr(r,X);ee.set(es,{redactedId:re,originalResourceId:X,cacheKey:Re,cacheComponents:_e}),oe.push({stableResourceId:es,resourceData:fe,resourceType:fe.Type,context:N(X),existingFindings:v.get(re)||[]})}if(oe.length!==0)try{let re=await Promise.race([t($,oe,o,c,d),new Promise((fe,X)=>setTimeout(()=>X(new Error("Analysis timeout")),n.timeoutMs))]);for(let[fe,X]of ee){let _e=re.get(fe);if(g.processedCount++,!_e){Ye.warn(`Batched response missing entry for resource ${X.originalResourceId}`,{stableResourceId:fe,redactedId:X.redactedId}),g.failureCount++;continue}let Re=(_e.issues||[]).map(es=>({...es,resource:X.originalResourceId,resourceId:X.originalResourceId}));f[X.originalResourceId]||(f[X.originalResourceId]={issues:[]});let it=f[X.originalResourceId];it.issues.push(...dn({existing:it.issues,incoming:Re})),it.resourceName=_e.resourceName,E.set(X.cacheKey,{resourceId:X.originalResourceId,issues:_e.issues||[],resourceName:_e.resourceName},X.cacheComponents),g.successCount++}}catch(re){Ye.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:re instanceof Error?re.message:String(re),chunkSize:Q.length}),await ie()}}}else await OT(I,n.maxConcurrent,async $=>{Ye.debug(`Starting analysis for resource ${$}`,{redactedId:$,maxConcurrent:n.maxConcurrent});let N=await Y({redactedId:$,redactedResources:b,findingsByResource:v,progressTracker:se});switch(g.processedCount++,Ye.debug(`Resource ${$} analysis result: ${N.status}`,{redactedId:$,status:N.status,hasProgressTracker:!!se}),N.status){case"success":g.successCount++,Ye.debug(`Resource ${$} completed successfully`,{redactedId:$,resourceKey:N.resourceKey});break;case"timeout":g.timeoutCount++,Ye.warn(`Resource ${$} timed out`,{redactedId:$}),h.push({redactedId:$,resourceData:b[$],resourceType:b[$].Type,existingFindings:v.get($)||[]});break;case"fail":case"skipped":g.failureCount++,Ye.warn(`Resource ${$} failed or was skipped`,{redactedId:$,status:N.status});break}});let le=Date.now()-g.startTime,_=se.getStats();if(Ye.debug("Analysis completed with progress tracker stats",{progressTrackerStats:_,performanceMetrics:g,totalTime:le,totalResources:O,maxConcurrent:n.maxConcurrent}),V.analysisComplete(le,g.successCount,g.failureCount,g.timeoutCount),g.failureCount>0||g.timeoutCount>0){V.newline(),V.info("\u{1F4CA} Performance Analysis:");let $=g.successCount>0?Math.round(le/1e3/g.successCount):0;V.comment(` \u23F1\uFE0F Average completion time: ${$}s`),V.comment(` \u{1F4CA} Success rate: ${(g.successCount/O*100).toFixed(1)}%`)}if(h.length>0){V.newline(),V.warning("\u23F0 Timed Out Resources:"),V.comment(` \u{1F4CB} Total timed out: ${h.length}`);for(let $ of h){if(V.comment(` \u274C ${$.resourceType}: ${$.redactedId}`),$.resourceData?.Properties){let M=$.resourceData.Properties,Q=Vb(M);V.comment(` \u{1F4DD} Name: ${Q}`)}$.existingFindings.length>0&&V.comment(` \u{1F50D} Existing findings: ${$.existingFindings.length}`),$.resourceData?.Metadata&&V.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes($.resourceType)&&V.comment(" \u26A0\uFE0F Complex resource type - may require extended analysis time")}V.newline(),V.info("\u{1F4A1} Tip: Some resources are taking longer to analyze than expected."),V.comment(" This is normal for complex resources. The analysis will continue with the remaining resources."),V.warning(`Retrying ${h.length} resource${h.length===1?"":"s"} that need a little more time...`)}let B=new Set(Object.keys(f)),q=new Set(Object.values(S)),Z=Array.from(q).filter($=>!B.has($)||!f[$]?.issues?.length);if(Z.length>0){let $=E.getCachedResultsForResources(Z),N=0;for(let[M,Q]of Array.from($.entries())){if(f[M]?.issues?.length>0)continue;let ie=(Q.issues||[]).map(ee=>({...ee,resource:M,resourceId:M}));ie.length>0&&(f[M]||(f[M]={issues:[]}),f[M].issues.push(...ie),f[M].resourceName=Q.resourceName,N+=ie.length)}N>0}return f};var Qu=require("node:child_process"),Je=K(require("node:fs")),Xu=K(require("node:os")),Xr=K(require("node:path"));var Qb="1.29.0",MT={Security:"https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/",Reliability:"https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/","Performance Efficiency":"https://docs.aws.amazon.com/wellarchitected/latest/performance-efficiency-pillar/","Cost Optimization":"https://docs.aws.amazon.com/wellarchitected/latest/cost-optimization-pillar/","Operational Excellence":"https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/",Sustainability:"https://docs.aws.amazon.com/wellarchitected/latest/sustainability-pillar/"},Yb=e=>e.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),WT=(e,t)=>{let s=0;if(s+=2e3,t){let n=Object.values(e).filter(r=>{let i=r.sources.cdkInsights?.issues??[],o=r.sources.cdkNag?.issues??[];return i.length>0||o.length>0});s+=n.length*100}for(let[,n]of Object.entries(e)){let r=n.sources.cdkInsights?.issues??[],i=n.sources.cdkNag?.issues??[];for(let o of[...r,...i])s+=o.issue.length,s+=o.recommendation?.length||0,s+=o.codeSnippet?.length||0,s+=500}return s},NT=e=>e?e.split(`
|
|
124
124
|
`).map(t=>t.trim()).filter(Boolean).join(`
|
|
125
125
|
`):"",Jb=e=>{let t=`- **Issue:** ${e.issue}`;return e.recommendation&&(t+=`
|
|
126
126
|
- **Recommendation:** ${NT(e.recommendation)}`),e.context&&(e.context.property&&(t+=`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cdk-insights",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.29.0",
|
|
4
4
|
"description": "AWS CDK security and cost analysis CLI. Free static scans via npm — no account needed. Sign up free to add AI-powered insights.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|