cdk-insights 1.37.5 → 1.37.6
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 +4 -4
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/entry.js
CHANGED
|
@@ -174,7 +174,7 @@ ${yt.primary.bold(`${Xt.rocket} ${s}`)}`),console.log(`${yt.comment("\u2500".rep
|
|
|
174
174
|
${yt.primary.bold(`${Xt.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: ${x}s`))}}}createSpinner(e){let s=ym({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(`
|
|
175
175
|
${yt.primary.bold(`${Xt.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(`
|
|
176
176
|
${yt.primary.bold(`${Xt.rocket} ${e}`)}`),console.log(`${yt.comment("\u2500".repeat(60))}
|
|
177
|
-
`)}section(e,s=Xt.info){console.log(yt.primary.bold(`${s} ${e}`))}success(e,s=Xt.success){console.log(yt.success(`${s} ${e}`))}info(e,s=Xt.info){console.log(yt.info(`${s} ${e}`))}warning(e,s=Xt.warning){console.log(yt.warning(`${s} ${e}`))}error(e,s=Xt.error){console.log(yt.error(`${s} ${e}`))}comment(e,s=""){console.log(yt.comment(`${s} ${e}`))}phase1(e){console.log(yt.info(`${Xt.phase1} Phase 1: ${e}`))}phase2(e){console.log(yt.primary(`${Xt.phase2} Phase 2: ${e}`))}phase3(e){console.log(yt.secondary(`${Xt.phase3} Phase 3: ${e}`))}severityBadge(e){switch(e.toUpperCase()){case"CRITICAL":return yt.severity.critical.bold(`${Xt.critical} CRITICAL`);case"HIGH":return yt.severity.high.bold(`${Xt.high} HIGH`);case"MEDIUM":return yt.severity.medium.bold(`${Xt.medium} MEDIUM`);case"LOW":return yt.severity.low.bold(`${Xt.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`)}},xm=ES.getInstance()});var yM,xM=D(()=>{"use strict";yM=t=>t&&(t.Name||t.ResourceName||t.FunctionName)||"Unnamed"});var IS,bM,_S,SM=D(()=>{"use strict";pt();IS=null,bM=t=>{IS=t},_S=()=>{if(IS&&!process.env.CI)try{IS.saveToDisk(),ae.info("\u{1F4BE} Cache saved to disk on exit")}catch(t){ae.warn("\u26A0\uFE0F Could not save cache on exit",{error:t instanceof Error?t.message:String(t)})}};process.on("exit",_S);process.on("SIGINT",()=>{_S(),process.exit(0)});process.on("SIGTERM",()=>{_S(),process.exit(0)})});var IQ,_Q,bm,kQ,FQ,TQ,PQ,vM,CM=D(()=>{"use strict";oS();O8();Xb();pl();em();W8();dS();RS();pt();Jn();xM();SM();IQ={maxConcurrent:ll.DEFAULT_MAX_CONCURRENT,retryAttempts:ll.DEFAULT_RETRY_ATTEMPTS,retryDelay:ll.DEFAULT_RETRY_DELAY_MS,timeoutMs:ll.DEFAULT_TIMEOUT_MS},_Q=t=>{if(!(t instanceof Error))return!1;let e=t.message??"";return e.startsWith("Polling timed out")||e==="Analysis timeout"||e.toLowerCase().includes("timeout")},bm=(t,e)=>{let s=t.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return t;let[,n,r=""]=s;return`${kc(e,n)}${r}`},kQ=t=>{let e=ol({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 _Q(s)?{status:"timeout",redactedId:n}:(e.set(i,o+1),o>t.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},FQ=({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)||[],x=f[p];if(!x)return{status:"skipped",redactedId:p};let S=aS(p,x,i,o,[]),w=cS(S),A=e[p];if(!A)return{status:"skipped",redactedId:p};let N=A,L=()=>(s[N]||(s[N]={issues:[]}),s[N]),E=c.get(w);if(E){let k=(E.issues||[]).map(y=>({...y,resource:N,resourceId:N})),V=L();return V.issues.push(...ta({existing:V.issues,incoming:k})),V.resourceName=E.resourceName,{status:"success",redactedId:p,resourceKey:N,remappedIssues:k,resourceName:E.resourceName}}let B=kc(a,A),H=kc("cdk-insights-stack",a),C=Qf(A,l,u),W={dependencies:C.dependencies.map(k=>bm(k,a)),dependents:C.dependents.map(k=>bm(k,a)),usageDescription:C.usageDescription};for(let k=1;k<=r.retryAttempts;k++)try{let V=await Promise.race([t(H,B,x,x.Type,i,o,h,g,W,d),new Promise((Q,K)=>setTimeout(()=>K(new Error("Analysis timeout")),r.timeoutMs))]);V.resourceId=N;let y=(V.issues||[]).map(Q=>({...Q,resource:N,resourceId:N})),v=L();return v.issues.push(...ta({existing:v.issues,incoming:y})),v.resourceName=V.resourceName,c.set(w,V,S),{status:"success",redactedId:p,resourceKey:N,remappedIssues:y,resourceName:V.resourceName}}catch(V){if(k===r.retryAttempts)return n({analysisError:V,redactedId:p});await new Promise(y=>setTimeout(y,r.retryDelay*2**(k-1)))}return{status:"fail",redactedId:p,error:new Error("Max retries exceeded")}},TQ=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)},PQ=10,vM=({analyzeResource:t,analyzeResourcesBatch:e,redactResources:s,config:n=IQ})=>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:x,mapping:b}=s(i),S=U8(a,b,c),w=new Map;for(let ee of S){let ue=w.get(ee.resourceId);ue?ue.push(ee):w.set(ee.resourceId,[ee])}let A=Object.keys(x),N=A.length,L=Qo(i),E=new dm({ttl:d?.ttl||6*60*60*1e3,maxSize:d?.maxSize||5e3,disabled:l||!d?.enabled});bM(E);let B=kQ(n),H=FQ({analyzeResource:t,redactionMapping:b,aggregatedResult:m,errorHandler:B,config:n,authToken:o,fingerprint:u,stackName:r,analysisCache:E,originalResources:i,relationships:L,aiModelId:p}),C=xm.createSingleLineProgressTracker(N,"Analyzing resources with AI"),W=Math.min(Math.max(1,Math.floor(f??1)),PQ);if(W>1&&!!e&&e){ae.debug("Batched analysis enabled",{batchSize:W,totalResources:N});let ee=kc("cdk-insights-stack",r),ue=pe=>{let Ce=Qf(pe,L,i);return{dependencies:Ce.dependencies.map(Re=>bm(Re,r)),dependents:Ce.dependents.map(Re=>bm(Re,r)),usageDescription:Ce.usageDescription}};for(let pe=0;pe<A.length;pe+=W){let Ce=A.slice(pe,pe+W),Re=async()=>{for(let q of Ce){let te=await H({redactedId:q,redactedResources:x,findingsByResource:w,progressTracker:C});switch(h.processedCount++,te.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:q,resourceData:x[q],resourceType:x[q].Type,existingFindings:w.get(q)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},re=new Map,we=[];for(let q of Ce){let te=x[q],Y=b[q];if(!te||!Y){h.processedCount++,h.failureCount++;continue}let _=aS(q,te,o,u,[]),se=cS(_),F=E.get(se);if(F){let xe=(F.issues||[]).map(I=>({...I,resource:Y,resourceId:Y}));m[Y]||(m[Y]={issues:[]});let Se=m[Y];Se.issues.push(...ta({existing:Se.issues,incoming:xe})),Se.resourceName=F.resourceName,h.processedCount++,h.successCount++;continue}let oe=kc(r,Y);re.set(oe,{redactedId:q,originalResourceId:Y,cacheKey:se,cacheComponents:_}),we.push({stableResourceId:oe,resourceData:te,resourceType:te.Type,context:ue(Y),existingFindings:w.get(q)||[]})}if(we.length!==0)try{let q=await Promise.race([e(ee,we,o,u,p),new Promise((te,Y)=>setTimeout(()=>Y(new Error("Analysis timeout")),n.timeoutMs))]);for(let[te,Y]of re){let _=q.get(te);if(h.processedCount++,!_){ae.warn(`Batched response missing entry for resource ${Y.originalResourceId}`,{stableResourceId:te,redactedId:Y.redactedId}),h.failureCount++;continue}let se=(_.issues||[]).map(oe=>({...oe,resource:Y.originalResourceId,resourceId:Y.originalResourceId}));m[Y.originalResourceId]||(m[Y.originalResourceId]={issues:[]});let F=m[Y.originalResourceId];F.issues.push(...ta({existing:F.issues,incoming:se})),F.resourceName=_.resourceName,E.set(Y.cacheKey,{resourceId:Y.originalResourceId,issues:_.issues||[],resourceName:_.resourceName},Y.cacheComponents),h.successCount++}}catch(q){ae.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:q instanceof Error?q.message:String(q),chunkSize:Ce.length}),await Re()}}}else await TQ(A,n.maxConcurrent,async ee=>{ae.debug(`Starting analysis for resource ${ee}`,{redactedId:ee,maxConcurrent:n.maxConcurrent});let ue=await H({redactedId:ee,redactedResources:x,findingsByResource:w,progressTracker:C});switch(h.processedCount++,ae.debug(`Resource ${ee} analysis result: ${ue.status}`,{redactedId:ee,status:ue.status,hasProgressTracker:!!C}),ue.status){case"success":h.successCount++,ae.debug(`Resource ${ee} completed successfully`,{redactedId:ee,resourceKey:ue.resourceKey});break;case"timeout":h.timeoutCount++,ae.warn(`Resource ${ee} timed out`,{redactedId:ee}),g.push({redactedId:ee,resourceData:x[ee],resourceType:x[ee].Type,existingFindings:w.get(ee)||[]});break;case"fail":case"skipped":h.failureCount++,ae.warn(`Resource ${ee} failed or was skipped`,{redactedId:ee,status:ue.status});break}});let V=Date.now()-h.startTime,y=C.getStats();if(ae.debug("Analysis completed with progress tracker stats",{progressTrackerStats:y,performanceMetrics:h,totalTime:V,totalResources:N,maxConcurrent:n.maxConcurrent}),P.analysisComplete(V,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){P.newline(),P.info("\u{1F4CA} Performance Analysis:");let ee=h.successCount>0?Math.round(V/1e3/h.successCount):0;P.comment(` \u23F1\uFE0F Average completion time: ${ee}s`),P.comment(` \u{1F4CA} Success rate: ${(h.successCount/N*100).toFixed(1)}%`)}if(g.length>0){P.newline(),P.warning("\u23F0 Timed Out Resources:"),P.comment(` \u{1F4CB} Total timed out: ${g.length}`);for(let ee of g){if(P.comment(` \u274C ${ee.resourceType}: ${ee.redactedId}`),ee.resourceData?.Properties){let pe=ee.resourceData.Properties,Ce=yM(pe);P.comment(` \u{1F4DD} Name: ${Ce}`)}ee.existingFindings.length>0&&P.comment(` \u{1F50D} Existing findings: ${ee.existingFindings.length}`),ee.resourceData?.Metadata&&P.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(ee.resourceType)&&P.comment(" \u26A0\uFE0F Complex resource type - may require extended analysis time")}P.newline(),P.info("\u{1F4A1} Tip: Some resources are taking longer to analyze than expected."),P.comment(" This is normal for complex resources. The analysis will continue with the remaining resources."),P.warning(`Retrying ${g.length} resource${g.length===1?"":"s"} that need a little more time...`)}let v=new Set(Object.keys(m)),Q=new Set(Object.values(b)),K=Array.from(Q).filter(ee=>!v.has(ee)||!m[ee]?.issues?.length);if(K.length>0){let ee=E.getCachedResultsForResources(K),ue=0;for(let[pe,Ce]of Array.from(ee.entries())){if(m[pe]?.issues?.length>0)continue;let Re=(Ce.issues||[]).map(re=>({...re,resource:pe,resourceId:pe}));Re.length>0&&(m[pe]||(m[pe]={issues:[]}),m[pe].issues.push(...Re),m[pe].resourceName=Ce.resourceName,ue+=Re.length)}ue>0}return m}});var AM,LQ,DM,OQ,MQ,wM,Sm,vm,EM,RM,BQ,NQ,$Q,Tc,Cm=D(()=>{"use strict";AM="1.37.5",LQ={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/"},DM=t=>t.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),OQ=(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},MQ=t=>t?t.split(`
|
|
177
|
+
`)}section(e,s=Xt.info){console.log(yt.primary.bold(`${s} ${e}`))}success(e,s=Xt.success){console.log(yt.success(`${s} ${e}`))}info(e,s=Xt.info){console.log(yt.info(`${s} ${e}`))}warning(e,s=Xt.warning){console.log(yt.warning(`${s} ${e}`))}error(e,s=Xt.error){console.log(yt.error(`${s} ${e}`))}comment(e,s=""){console.log(yt.comment(`${s} ${e}`))}phase1(e){console.log(yt.info(`${Xt.phase1} Phase 1: ${e}`))}phase2(e){console.log(yt.primary(`${Xt.phase2} Phase 2: ${e}`))}phase3(e){console.log(yt.secondary(`${Xt.phase3} Phase 3: ${e}`))}severityBadge(e){switch(e.toUpperCase()){case"CRITICAL":return yt.severity.critical.bold(`${Xt.critical} CRITICAL`);case"HIGH":return yt.severity.high.bold(`${Xt.high} HIGH`);case"MEDIUM":return yt.severity.medium.bold(`${Xt.medium} MEDIUM`);case"LOW":return yt.severity.low.bold(`${Xt.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`)}},xm=ES.getInstance()});var yM,xM=D(()=>{"use strict";yM=t=>t&&(t.Name||t.ResourceName||t.FunctionName)||"Unnamed"});var IS,bM,_S,SM=D(()=>{"use strict";pt();IS=null,bM=t=>{IS=t},_S=()=>{if(IS&&!process.env.CI)try{IS.saveToDisk(),ae.info("\u{1F4BE} Cache saved to disk on exit")}catch(t){ae.warn("\u26A0\uFE0F Could not save cache on exit",{error:t instanceof Error?t.message:String(t)})}};process.on("exit",_S);process.on("SIGINT",()=>{_S(),process.exit(0)});process.on("SIGTERM",()=>{_S(),process.exit(0)})});var IQ,_Q,bm,kQ,FQ,TQ,PQ,vM,CM=D(()=>{"use strict";oS();O8();Xb();pl();em();W8();dS();RS();pt();Jn();xM();SM();IQ={maxConcurrent:ll.DEFAULT_MAX_CONCURRENT,retryAttempts:ll.DEFAULT_RETRY_ATTEMPTS,retryDelay:ll.DEFAULT_RETRY_DELAY_MS,timeoutMs:ll.DEFAULT_TIMEOUT_MS},_Q=t=>{if(!(t instanceof Error))return!1;let e=t.message??"";return e.startsWith("Polling timed out")||e==="Analysis timeout"||e.toLowerCase().includes("timeout")},bm=(t,e)=>{let s=t.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return t;let[,n,r=""]=s;return`${kc(e,n)}${r}`},kQ=t=>{let e=ol({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 _Q(s)?{status:"timeout",redactedId:n}:(e.set(i,o+1),o>t.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},FQ=({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)||[],x=f[p];if(!x)return{status:"skipped",redactedId:p};let S=aS(p,x,i,o,[]),w=cS(S),A=e[p];if(!A)return{status:"skipped",redactedId:p};let N=A,L=()=>(s[N]||(s[N]={issues:[]}),s[N]),E=c.get(w);if(E){let k=(E.issues||[]).map(y=>({...y,resource:N,resourceId:N})),V=L();return V.issues.push(...ta({existing:V.issues,incoming:k})),V.resourceName=E.resourceName,{status:"success",redactedId:p,resourceKey:N,remappedIssues:k,resourceName:E.resourceName}}let B=kc(a,A),H=kc("cdk-insights-stack",a),C=Qf(A,l,u),W={dependencies:C.dependencies.map(k=>bm(k,a)),dependents:C.dependents.map(k=>bm(k,a)),usageDescription:C.usageDescription};for(let k=1;k<=r.retryAttempts;k++)try{let V=await Promise.race([t(H,B,x,x.Type,i,o,h,g,W,d),new Promise((Q,K)=>setTimeout(()=>K(new Error("Analysis timeout")),r.timeoutMs))]);V.resourceId=N;let y=(V.issues||[]).map(Q=>({...Q,resource:N,resourceId:N})),v=L();return v.issues.push(...ta({existing:v.issues,incoming:y})),v.resourceName=V.resourceName,c.set(w,V,S),{status:"success",redactedId:p,resourceKey:N,remappedIssues:y,resourceName:V.resourceName}}catch(V){if(k===r.retryAttempts)return n({analysisError:V,redactedId:p});await new Promise(y=>setTimeout(y,r.retryDelay*2**(k-1)))}return{status:"fail",redactedId:p,error:new Error("Max retries exceeded")}},TQ=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)},PQ=10,vM=({analyzeResource:t,analyzeResourcesBatch:e,redactResources:s,config:n=IQ})=>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:x,mapping:b}=s(i),S=U8(a,b,c),w=new Map;for(let ee of S){let ue=w.get(ee.resourceId);ue?ue.push(ee):w.set(ee.resourceId,[ee])}let A=Object.keys(x),N=A.length,L=Qo(i),E=new dm({ttl:d?.ttl||6*60*60*1e3,maxSize:d?.maxSize||5e3,disabled:l||!d?.enabled});bM(E);let B=kQ(n),H=FQ({analyzeResource:t,redactionMapping:b,aggregatedResult:m,errorHandler:B,config:n,authToken:o,fingerprint:u,stackName:r,analysisCache:E,originalResources:i,relationships:L,aiModelId:p}),C=xm.createSingleLineProgressTracker(N,"Analyzing resources with AI"),W=Math.min(Math.max(1,Math.floor(f??1)),PQ);if(W>1&&!!e&&e){ae.debug("Batched analysis enabled",{batchSize:W,totalResources:N});let ee=kc("cdk-insights-stack",r),ue=pe=>{let Ce=Qf(pe,L,i);return{dependencies:Ce.dependencies.map(Re=>bm(Re,r)),dependents:Ce.dependents.map(Re=>bm(Re,r)),usageDescription:Ce.usageDescription}};for(let pe=0;pe<A.length;pe+=W){let Ce=A.slice(pe,pe+W),Re=async()=>{for(let q of Ce){let te=await H({redactedId:q,redactedResources:x,findingsByResource:w,progressTracker:C});switch(h.processedCount++,te.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:q,resourceData:x[q],resourceType:x[q].Type,existingFindings:w.get(q)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},re=new Map,we=[];for(let q of Ce){let te=x[q],Y=b[q];if(!te||!Y){h.processedCount++,h.failureCount++;continue}let _=aS(q,te,o,u,[]),se=cS(_),F=E.get(se);if(F){let xe=(F.issues||[]).map(I=>({...I,resource:Y,resourceId:Y}));m[Y]||(m[Y]={issues:[]});let Se=m[Y];Se.issues.push(...ta({existing:Se.issues,incoming:xe})),Se.resourceName=F.resourceName,h.processedCount++,h.successCount++;continue}let oe=kc(r,Y);re.set(oe,{redactedId:q,originalResourceId:Y,cacheKey:se,cacheComponents:_}),we.push({stableResourceId:oe,resourceData:te,resourceType:te.Type,context:ue(Y),existingFindings:w.get(q)||[]})}if(we.length!==0)try{let q=await Promise.race([e(ee,we,o,u,p),new Promise((te,Y)=>setTimeout(()=>Y(new Error("Analysis timeout")),n.timeoutMs))]);for(let[te,Y]of re){let _=q.get(te);if(h.processedCount++,!_){ae.warn(`Batched response missing entry for resource ${Y.originalResourceId}`,{stableResourceId:te,redactedId:Y.redactedId}),h.failureCount++;continue}let se=(_.issues||[]).map(oe=>({...oe,resource:Y.originalResourceId,resourceId:Y.originalResourceId}));m[Y.originalResourceId]||(m[Y.originalResourceId]={issues:[]});let F=m[Y.originalResourceId];F.issues.push(...ta({existing:F.issues,incoming:se})),F.resourceName=_.resourceName,E.set(Y.cacheKey,{resourceId:Y.originalResourceId,issues:_.issues||[],resourceName:_.resourceName},Y.cacheComponents),h.successCount++}}catch(q){ae.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:q instanceof Error?q.message:String(q),chunkSize:Ce.length}),await Re()}}}else await TQ(A,n.maxConcurrent,async ee=>{ae.debug(`Starting analysis for resource ${ee}`,{redactedId:ee,maxConcurrent:n.maxConcurrent});let ue=await H({redactedId:ee,redactedResources:x,findingsByResource:w,progressTracker:C});switch(h.processedCount++,ae.debug(`Resource ${ee} analysis result: ${ue.status}`,{redactedId:ee,status:ue.status,hasProgressTracker:!!C}),ue.status){case"success":h.successCount++,ae.debug(`Resource ${ee} completed successfully`,{redactedId:ee,resourceKey:ue.resourceKey});break;case"timeout":h.timeoutCount++,ae.warn(`Resource ${ee} timed out`,{redactedId:ee}),g.push({redactedId:ee,resourceData:x[ee],resourceType:x[ee].Type,existingFindings:w.get(ee)||[]});break;case"fail":case"skipped":h.failureCount++,ae.warn(`Resource ${ee} failed or was skipped`,{redactedId:ee,status:ue.status});break}});let V=Date.now()-h.startTime,y=C.getStats();if(ae.debug("Analysis completed with progress tracker stats",{progressTrackerStats:y,performanceMetrics:h,totalTime:V,totalResources:N,maxConcurrent:n.maxConcurrent}),P.analysisComplete(V,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){P.newline(),P.info("\u{1F4CA} Performance Analysis:");let ee=h.successCount>0?Math.round(V/1e3/h.successCount):0;P.comment(` \u23F1\uFE0F Average completion time: ${ee}s`),P.comment(` \u{1F4CA} Success rate: ${(h.successCount/N*100).toFixed(1)}%`)}if(g.length>0){P.newline(),P.warning("\u23F0 Timed Out Resources:"),P.comment(` \u{1F4CB} Total timed out: ${g.length}`);for(let ee of g){if(P.comment(` \u274C ${ee.resourceType}: ${ee.redactedId}`),ee.resourceData?.Properties){let pe=ee.resourceData.Properties,Ce=yM(pe);P.comment(` \u{1F4DD} Name: ${Ce}`)}ee.existingFindings.length>0&&P.comment(` \u{1F50D} Existing findings: ${ee.existingFindings.length}`),ee.resourceData?.Metadata&&P.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(ee.resourceType)&&P.comment(" \u26A0\uFE0F Complex resource type - may require extended analysis time")}P.newline(),P.info("\u{1F4A1} Tip: Some resources are taking longer to analyze than expected."),P.comment(" This is normal for complex resources. The analysis will continue with the remaining resources."),P.warning(`Retrying ${g.length} resource${g.length===1?"":"s"} that need a little more time...`)}let v=new Set(Object.keys(m)),Q=new Set(Object.values(b)),K=Array.from(Q).filter(ee=>!v.has(ee)||!m[ee]?.issues?.length);if(K.length>0){let ee=E.getCachedResultsForResources(K),ue=0;for(let[pe,Ce]of Array.from(ee.entries())){if(m[pe]?.issues?.length>0)continue;let Re=(Ce.issues||[]).map(re=>({...re,resource:pe,resourceId:pe}));Re.length>0&&(m[pe]||(m[pe]={issues:[]}),m[pe].issues.push(...Re),m[pe].resourceName=Ce.resourceName,ue+=Re.length)}ue>0}return m}});var AM,LQ,DM,OQ,MQ,wM,Sm,vm,EM,RM,BQ,NQ,$Q,Tc,Cm=D(()=>{"use strict";AM="1.37.6",LQ={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/"},DM=t=>t.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),OQ=(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},MQ=t=>t?t.split(`
|
|
178
178
|
`).map(e=>e.trim()).filter(Boolean).join(`
|
|
179
179
|
`):"",wM=t=>{let e=`- **Issue:** ${t.issue}`;return t.recommendation&&(e+=`
|
|
180
180
|
- **Recommendation:** ${MQ(t.recommendation)}`),t.context&&(t.context.property&&(e+=`
|
|
@@ -293,7 +293,7 @@ ${o}`)}});var LM,OM,MM=D(()=>{"use strict";LM=require("node:child_process"),OM=(
|
|
|
293
293
|
`)}catch(a){console.error("Failed to write GitHub outputs:",a)}}});var Am,YM,JM=D(()=>{"use strict";pt();Am=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"}},YM=(t,e)=>{Me.info(`
|
|
294
294
|
\u{1F4DD} Analysis Summary for stack: ${t}`),Me.info(`Total Resources Scanned: ${e.totalResources}`),Me.info(`Resources with Issues: ${e.resourcesWithIssues} (${e.percentWithIssues}%)`),Me.info(`Total Issues Found: ${e.totalIssues}
|
|
295
295
|
`),Me.info("Severity Breakdown:"),Me.info(` ${Am("CRITICAL")} Critical: ${e.severityCounts.CRITICAL}`),Me.info(` ${Am("HIGH")} High: ${e.severityCounts.HIGH}`),Me.info(` ${Am("MEDIUM")} Medium: ${e.severityCounts.MEDIUM}`),Me.info(` ${Am("LOW")} Low: ${e.severityCounts.LOW}
|
|
296
|
-
`),Me.info("WAF Pillar Impact:");for(let[s,n]of Object.entries(e.wafIssues))Me.info(` ${s}: ${n}`);Me.info(""),Me.info("Top Priorities:"),e.severityCounts.CRITICAL>0&&Me.info(" \u{1F534} Address Critical issues immediately (highest risk)"),e.severityCounts.HIGH>0&&Me.info(" \u{1F7E0} Then handle High-severity issues"),e.severityCounts.MEDIUM>0&&Me.info(" \u{1F7E1} Schedule Medium-severity tasks soon"),e.severityCounts.LOW>0&&Me.info(" \u{1F7E2} Plan Low-severity enhancements at your convenience"),Me.info("")}});var eee,tee,see,XM,vl,BS=D(()=>{"use strict";eee=i0(),tee=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"}},see=(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}`:""},XM={CRITICAL:4,HIGH:3,MEDIUM:2,LOW:1},vl=t=>{let e=new eee({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=see(i,n);s.push({issue:i,group:n,service:o,sourceLocation:a})}}s.sort((n,r)=>{let i=XM[n.issue.severity]||0;return(XM[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",`${tee(n.severity)} ${n.severity}`,i,n.issue,o||n.locationHint||""]);console.log(e.toString())}});var Cl=M((D_e,nee)=>{nee.exports={name:"cdk-insights",version:"1.37.5",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 e4,ree,QM,iee,t4,s4=D(()=>{"use strict";e4=ce(require("node:fs"));pt();pl();({version:ree}=Cl()),QM={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3},iee=(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)=>QM[c.severity]-QM[u.severity]),a=fm(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:ree,summary:e,recommendations:n}},t4=(t,e,s)=>{let n=iee(t,e,s),r=`${t}_analysis_report.json`;try{e4.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),Me.info(`\u{1F4C4} JSON report written to ${r}`)}catch(i){let o=i instanceof Error?i.message:String(i);throw Me.error(`\u274C Failed to write JSON report to ${r}: ${o}`),new Error(`Failed to write analysis report: ${o}`)}return n}});var oee,aee,n4,Em,cee,NS=D(()=>{"use strict";({version:oee}=Cl()),aee=t=>{switch(t){case"CRITICAL":case"HIGH":return"error";case"MEDIUM":return"warning";default:return"note"}},n4=t=>{switch(t){case"CRITICAL":return 9;case"HIGH":return 7;case"MEDIUM":return 4;case"LOW":return 2;default:return 1}},Em=(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=cee(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":n4(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:aee(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":n4(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:oee,informationUri:"https://cdkinsights.dev",rules:s}},results:n}]}},cee=t=>{let e=t.issue.toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,50);return`CDK-${t.severity}-${e}`}});var $S,r4,i4=D(()=>{"use strict";$S=ce(require("node:fs"));pt();Cm();JM();BS();s4();NS();MS();r4=(t,e,s,n,r)=>{switch(Me.info(`Generating output in format: ${t}`),t){case"markdown":{let i=Tc(e,s,r,n),o=`${e}_analysis_report.md`;try{$S.writeFileSync(o,i),Me.info(`\u{1F4C4} Saved Markdown report to ${o}`)}catch(a){let c=a instanceof Error?a.message:String(a);throw Me.error(`\u274C Failed to write Markdown report to ${o}: ${c}`),new Error(`Failed to write Markdown report: ${c}`)}break}case"table":{vl(s);break}case"json":{let i=t4(e,r,s);process.stdout.write(`${JSON.stringify(i,null,2)}
|
|
296
|
+
`),Me.info("WAF Pillar Impact:");for(let[s,n]of Object.entries(e.wafIssues))Me.info(` ${s}: ${n}`);Me.info(""),Me.info("Top Priorities:"),e.severityCounts.CRITICAL>0&&Me.info(" \u{1F534} Address Critical issues immediately (highest risk)"),e.severityCounts.HIGH>0&&Me.info(" \u{1F7E0} Then handle High-severity issues"),e.severityCounts.MEDIUM>0&&Me.info(" \u{1F7E1} Schedule Medium-severity tasks soon"),e.severityCounts.LOW>0&&Me.info(" \u{1F7E2} Plan Low-severity enhancements at your convenience"),Me.info("")}});var eee,tee,see,XM,vl,BS=D(()=>{"use strict";eee=i0(),tee=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"}},see=(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}`:""},XM={CRITICAL:4,HIGH:3,MEDIUM:2,LOW:1},vl=t=>{let e=new eee({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=see(i,n);s.push({issue:i,group:n,service:o,sourceLocation:a})}}s.sort((n,r)=>{let i=XM[n.issue.severity]||0;return(XM[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",`${tee(n.severity)} ${n.severity}`,i,n.issue,o||n.locationHint||""]);console.log(e.toString())}});var Cl=M((D_e,nee)=>{nee.exports={name:"cdk-insights",version:"1.37.6",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 e4,ree,QM,iee,t4,s4=D(()=>{"use strict";e4=ce(require("node:fs"));pt();pl();({version:ree}=Cl()),QM={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3},iee=(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)=>QM[c.severity]-QM[u.severity]),a=fm(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:ree,summary:e,recommendations:n}},t4=(t,e,s)=>{let n=iee(t,e,s),r=`${t}_analysis_report.json`;try{e4.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),Me.info(`\u{1F4C4} JSON report written to ${r}`)}catch(i){let o=i instanceof Error?i.message:String(i);throw Me.error(`\u274C Failed to write JSON report to ${r}: ${o}`),new Error(`Failed to write analysis report: ${o}`)}return n}});var oee,aee,n4,Em,cee,NS=D(()=>{"use strict";({version:oee}=Cl()),aee=t=>{switch(t){case"CRITICAL":case"HIGH":return"error";case"MEDIUM":return"warning";default:return"note"}},n4=t=>{switch(t){case"CRITICAL":return 9;case"HIGH":return 7;case"MEDIUM":return 4;case"LOW":return 2;default:return 1}},Em=(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=cee(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":n4(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:aee(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":n4(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:oee,informationUri:"https://cdkinsights.dev",rules:s}},results:n}]}},cee=t=>{let e=t.issue.toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,50);return`CDK-${t.severity}-${e}`}});var $S,r4,i4=D(()=>{"use strict";$S=ce(require("node:fs"));pt();Cm();JM();BS();s4();NS();MS();r4=(t,e,s,n,r)=>{switch(Me.info(`Generating output in format: ${t}`),t){case"markdown":{let i=Tc(e,s,r,n),o=`${e}_analysis_report.md`;try{$S.writeFileSync(o,i),Me.info(`\u{1F4C4} Saved Markdown report to ${o}`)}catch(a){let c=a instanceof Error?a.message:String(a);throw Me.error(`\u274C Failed to write Markdown report to ${o}: ${c}`),new Error(`Failed to write Markdown report: ${c}`)}break}case"table":{vl(s);break}case"json":{let i=t4(e,r,s);process.stdout.write(`${JSON.stringify(i,null,2)}
|
|
297
297
|
`);break}case"sarif":{let i=Em(e,s),o=`${e}_analysis_report.sarif`;try{$S.writeFileSync(o,JSON.stringify(i,null,2)),Me.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 Me.error(`\u274C Failed to write SARIF report to ${o}: ${c}`),new Error(`Failed to write SARIF report: ${c}`)}break}case"github-actions":{wm(e,s,r.severityCounts,r.totalResources);break}default:YM(e,r);break}}});var Rm,o4=D(()=>{"use strict";Rm=(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 a4,c4,u4=D(()=>{"use strict";a4=ce(require("node:crypto")),c4=t=>a4.createHash("sha256").update(JSON.stringify(t)).digest("hex")});var Im,uee,lee,WS,jS=D(()=>{"use strict";Im=(t,e)=>e.endsWith("*")?t.startsWith(e.slice(0,-1)):t===e,uee=(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},lee=(t,e,s)=>!t.ruleId||s.length===0||e.length===0?!1:s.some(n=>n.ruleId===t.ruleId&&e.some(r=>uee(r,n.constructPath))),WS=(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=>Im(c,a)))||t.ruleId&&n.some(c=>Im(t.ruleId,c))?!0:lee(t,e,i)}});var dee,pee,fee,mee,l4,d4=D(()=>{"use strict";dee=[/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],pee=[/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],fee=t=>dee.some(e=>e.test(t)),mee=t=>pee.some(e=>e.test(t)),l4=(t,e=!1)=>t.filter(s=>{let n=s.issue||"";return!(fee(n)||e&&mee(n))})});var p4,f4=D(()=>{"use strict";pt();pl();d4();p4=({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)){Me.warn(`\u26A0\uFE0F No AI issues for resource '${d}', skipping.`);continue}let f=d;if(!o[f]){Me.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,x=l4(g,m.isGenerated).map(S=>{switch(S.severity||(Me.debug(`AI recommendation missing severity for resource '${f}', defaulting to MEDIUM`),S.severity="MEDIUM"),S.severity.toUpperCase()==="CRITICAL"&&(Me.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:Me.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"}}),b=fm(x,m.cdkPath);m.sources||(m.sources={cdkInsights:{issues:[]},cdkNag:{issues:[]}}),m.sources.cdkInsights||(m.sources.cdkInsights={issues:[]}),m.sources.cdkInsights.issues.push(...b)}return{updatedMap:o,criticalCount:a,highCount:c,mediumCount:u,lowCount:l}}});var _m,US,hee,gee,HS=D(()=>{"use strict";_m=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},US=(t,e=!1)=>{if(t.length<16||hee(t)||_m(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},hee=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!!gee(t)},gee=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 GS,zS,yee,xee,bee,See,m4,h4,qS,VS,KS,ZS,km,YS,JS=D(()=>{"use strict";GS=[/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],zS=[/^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_-]+$/],yee=[/\{\{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*:/],xee=[/^<[^>]+>$/,/^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],bee=[/^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],See=[/(?:^|\.)Targets\[\d+\]\.Input$/,/(?:^|\.)Create$/,/(?:^|\.)Update$/,/(?:^|\.)Delete$/,/(?:^|\.)DefinitionString$/,/(?:^|\.)Code\.ZipFile$/,/(?:^|\.)Statement\[\d+\]\.Resource$/,/(?:^|\.)Statement\[\d+\]\.Resource\[\d+\]$/,/(?:^|\.)Statement\[\d+\]\.Sid$/],m4=t=>bee.some(e=>e.test(t)),h4=t=>See.some(e=>e.test(t)),qS=t=>GS.some(e=>e.test(t)),VS=t=>zS.some(e=>e.test(t)),KS=t=>yee.some(e=>e.test(t)),ZS=t=>xee.some(e=>e.test(t)),km=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])},YS=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,wl,XS=D(()=>{"use strict";Dl=t=>{let e={api_key:`Use AWS Secrets Manager to store API keys securely:
|
|
298
298
|
|
|
299
299
|
// CDK TypeScript example:
|
|
@@ -455,7 +455,7 @@ See: https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html`},wl
|
|
|
455
455
|
`,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 qN=M((yFe,zN)=>{"use strict";var Rne=th(),{MAX_LENGTH:UN,CHAR_BACKSLASH:Uv,CHAR_BACKTICK:Ine,CHAR_COMMA:_ne,CHAR_DOT:kne,CHAR_LEFT_PARENTHESES:Fne,CHAR_RIGHT_PARENTHESES:Tne,CHAR_LEFT_CURLY_BRACE:Pne,CHAR_RIGHT_CURLY_BRACE:Lne,CHAR_LEFT_SQUARE_BRACKET:HN,CHAR_RIGHT_SQUARE_BRACKET:GN,CHAR_DOUBLE_QUOTE:One,CHAR_SINGLE_QUOTE:Mne,CHAR_NO_BREAK_SPACE:Bne,CHAR_ZERO_WIDTH_NOBREAK_SPACE:Nne}=jN(),$ne=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let s=e||{},n=typeof s.maxLength=="number"?Math.min(UN,s.maxLength):UN;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===Nne||p===Bne)){if(p===Uv){m({type:"text",value:(e.keepEscaping?p:"")+f()});continue}if(p===GN){m({type:"text",value:"\\"+p});continue}if(p===HN){c++;let g;for(;l<u&&(g=f());){if(p+=g,g===HN){c++;continue}if(g===Uv){p+=f();continue}if(g===GN&&(c--,c===0))break}m({type:"text",value:p});continue}if(p===Fne){o=m({type:"paren",nodes:[]}),i.push(o),m({type:"text",value:p});continue}if(p===Tne){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===One||p===Mne||p===Ine){let g=p,h;for(e.keepQuotes!==!0&&(p="");l<u&&(h=f());){if(h===Uv){p+=h+f();continue}if(h===g){e.keepQuotes===!0&&(p+=h);break}p+=h}m({type:"text",value:p});continue}if(p===Pne){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===Lne){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===_ne&&d>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:Rne(o)}]}m({type:"comma",value:p}),o.commas++;continue}if(p===kne&&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(x=>{x.nodes||(x.type==="open"&&(x.isOpen=!0),x.type==="close"&&(x.isClose=!0),x.nodes||(x.type="text"),x.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};zN.exports=$ne});var ZN=M((xFe,KN)=>{"use strict";var VN=th(),Wne=MN(),jne=$N(),Une=qN(),en=(t,e={})=>{let s=[];if(Array.isArray(t))for(let n of t){let r=en.create(n,e);Array.isArray(r)?s.push(...r):s.push(r)}else s=[].concat(en.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(s=[...new Set(s)]),s};en.parse=(t,e={})=>Une(t,e);en.stringify=(t,e={})=>VN(typeof t=="string"?en.parse(t,e):t,e);en.compile=(t,e={})=>(typeof t=="string"&&(t=en.parse(t,e)),Wne(t,e));en.expand=(t,e={})=>{typeof t=="string"&&(t=en.parse(t,e));let s=jne(t,e);return e.noempty===!0&&(s=s.filter(Boolean)),e.nodupes===!0&&(s=[...new Set(s)]),s};en.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?en.compile(t,e):en.expand(t,e);KN.exports=en});var YN=M((bFe,Hne)=>{Hne.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 XN=M((SFe,JN)=>{JN.exports=YN()});var e5=M((vFe,QN)=>{"use strict";var Gne=require("path"),zne=XN(),qne=new Set(zne);QN.exports=t=>qne.has(Gne.extname(t).slice(1).toLowerCase())});var rh=M(Be=>{"use strict";var{sep:Vne}=require("path"),{platform:Hv}=process,Kne=require("os");Be.EV_ALL="all";Be.EV_READY="ready";Be.EV_ADD="add";Be.EV_CHANGE="change";Be.EV_ADD_DIR="addDir";Be.EV_UNLINK="unlink";Be.EV_UNLINK_DIR="unlinkDir";Be.EV_RAW="raw";Be.EV_ERROR="error";Be.STR_DATA="data";Be.STR_END="end";Be.STR_CLOSE="close";Be.FSEVENT_CREATED="created";Be.FSEVENT_MODIFIED="modified";Be.FSEVENT_DELETED="deleted";Be.FSEVENT_MOVED="moved";Be.FSEVENT_CLONED="cloned";Be.FSEVENT_UNKNOWN="unknown";Be.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;Be.FSEVENT_TYPE_FILE="file";Be.FSEVENT_TYPE_DIRECTORY="directory";Be.FSEVENT_TYPE_SYMLINK="symlink";Be.KEY_LISTENERS="listeners";Be.KEY_ERR="errHandlers";Be.KEY_RAW="rawEmitters";Be.HANDLER_KEYS=[Be.KEY_LISTENERS,Be.KEY_ERR,Be.KEY_RAW];Be.DOT_SLASH=`.${Vne}`;Be.BACK_SLASH_RE=/\\/g;Be.DOUBLE_SLASH_RE=/\/\//;Be.SLASH_OR_BACK_SLASH_RE=/[/\\]/;Be.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;Be.REPLACER_RE=/^\.[/\\]/;Be.SLASH="/";Be.SLASH_SLASH="//";Be.BRACE_START="{";Be.BANG="!";Be.ONE_DOT=".";Be.TWO_DOTS="..";Be.STAR="*";Be.GLOBSTAR="**";Be.ROOT_GLOBSTAR="/**/*";Be.SLASH_GLOBSTAR="/**";Be.DIR_SUFFIX="Dir";Be.ANYMATCH_OPTS={dot:!0};Be.STRING_TYPE="string";Be.FUNCTION_TYPE="function";Be.EMPTY_STR="";Be.EMPTY_FN=()=>{};Be.IDENTITY_FN=t=>t;Be.isWindows=Hv==="win32";Be.isMacos=Hv==="darwin";Be.isLinux=Hv==="linux";Be.isIBMi=Kne.type()==="OS400"});var o5=M((DFe,i5)=>{"use strict";var Yr=require("fs"),us=require("path"),{promisify:Vl}=require("util"),Zne=e5(),{isWindows:Yne,isLinux:Jne,EMPTY_FN:Xne,EMPTY_STR:Qne,KEY_LISTENERS:Bc,KEY_ERR:Gv,KEY_RAW:Gl,HANDLER_KEYS:ere,EV_CHANGE:oh,EV_ADD:ih,EV_ADD_DIR:tre,EV_ERROR:s5,STR_DATA:sre,STR_END:nre,BRACE_START:rre,STAR:ire}=rh(),ore="watch",are=Vl(Yr.open),n5=Vl(Yr.stat),cre=Vl(Yr.lstat),ure=Vl(Yr.close),zv=Vl(Yr.realpath),lre={lstat:cre,stat:n5},Vv=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},zl=(t,e,s)=>{let n=t[e];n instanceof Set||(t[e]=n=new Set([n])),n.add(s)},dre=t=>e=>{let s=t[e];s instanceof Set?s.clear():delete t[e]},ql=(t,e,s)=>{let n=t[e];n instanceof Set?n.delete(s):n===s&&delete t[e]},r5=t=>t instanceof Set?t.size===0:!t,ah=new Map;function t5(t,e,s,n,r){let i=(o,a)=>{s(t),r(o,a,{watchedPath:t}),a&&t!==a&&ch(us.resolve(t,a),Bc,us.join(t,a))};try{return Yr.watch(t,e,i)}catch(o){n(o)}}var ch=(t,e,s,n,r)=>{let i=ah.get(t);i&&Vv(i[e],o=>{o(s,n,r)})},pre=(t,e,s,n)=>{let{listener:r,errHandler:i,rawEmitter:o}=n,a=ah.get(e),c;if(!s.persistent)return c=t5(t,s,r,i,o),c.close.bind(c);if(a)zl(a,Bc,r),zl(a,Gv,i),zl(a,Gl,o);else{if(c=t5(t,s,ch.bind(null,e,Bc),i,ch.bind(null,e,Gl)),!c)return;c.on(s5,async u=>{let l=ch.bind(null,e,Gv);if(a.watcherUnusable=!0,Yne&&u.code==="EPERM")try{let d=await are(t,"r");await ure(d),l(u)}catch{}else l(u)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:c},ah.set(e,a)}return()=>{ql(a,Bc,r),ql(a,Gv,i),ql(a,Gl,o),r5(a.listeners)&&(a.watcher.close(),ah.delete(e),ere.forEach(dre(a)),a.watcher=void 0,Object.freeze(a))}},qv=new Map,fre=(t,e,s,n)=>{let{listener:r,rawEmitter:i}=n,o=qv.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,Yr.unwatchFile(e),o=void 0),o?(zl(o,Bc,r),zl(o,Gl,i)):(o={listeners:r,rawEmitters:i,options:s,watcher:Yr.watchFile(e,s,(l,d)=>{Vv(o.rawEmitters,f=>{f(oh,e,{curr:l,prev:d})});let p=l.mtimeMs;(l.size!==d.size||p>d.mtimeMs||p===0)&&Vv(o.listeners,f=>f(t,l))})},qv.set(e,o)),()=>{ql(o,Bc,r),ql(o,Gl,i),r5(o.listeners)&&(qv.delete(e),Yr.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},Kv=class{constructor(e){this.fsw=e,this._boundHandleError=s=>e._handleError(s)}_watchWithNodeFs(e,s){let n=this.fsw.options,r=us.dirname(e),i=us.basename(e);this.fsw._getWatchedDir(r).add(i);let a=us.resolve(e),c={persistent:n.persistent};s||(s=Xne);let u;return n.usePolling?(c.interval=n.enableBinaryInterval&&Zne(i)?n.binaryInterval:n.interval,u=fre(e,a,c,{listener:s,rawEmitter:this.fsw._emitRaw})):u=pre(e,a,c,{listener:s,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),u}_handleFile(e,s,n){if(this.fsw.closed)return;let r=us.dirname(e),i=us.basename(e),o=this.fsw._getWatchedDir(r),a=s;if(o.has(i))return;let c=async(l,d)=>{if(this.fsw._throttle(ore,e,5)){if(!d||d.mtimeMs===0)try{let p=await n5(e);if(this.fsw.closed)return;let f=p.atimeMs,m=p.mtimeMs;(!f||f<=m||m!==a.mtimeMs)&&this.fsw._emit(oh,e,p),Jne&&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(oh,e,d),a=d}}},u=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(ih,e,0))return;this.fsw._emit(ih,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 zv(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(oh,n,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(ih,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=us.join(e,Qne),!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(sre,async d=>{if(this.fsw.closed){l=void 0;return}let p=d.path,f=us.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=us.join(i,us.relative(i,f)),this._addToNodeFs(f,s,n,o+1))}}).on(s5,this._boundHandleError);return new Promise(d=>l.once(nre,()=>{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:us.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(us.dirname(e)),u=c.has(us.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!u&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(tre,e,s),c.add(us.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 lre[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(ire)&&!e.includes(rre),l;if(c.isDirectory()){let d=us.resolve(e),p=u?await zv(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 zv(e):e;if(this.fsw.closed)return;let p=us.dirname(a.watchPath);if(this.fsw._getWatchedDir(p).add(a.watchPath),this.fsw._emit(ih,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(us.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}}};i5.exports=Kv});var f5=M((wFe,sC)=>{"use strict";var eC=require("fs"),ls=require("path"),{promisify:tC}=require("util"),Nc;try{Nc=require("fsevents")}catch(t){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(t)}if(Nc){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&&(Nc=void 0)}}var{EV_ADD:Zv,EV_CHANGE:mre,EV_ADD_DIR:a5,EV_UNLINK:uh,EV_ERROR:hre,STR_DATA:gre,STR_END:yre,FSEVENT_CREATED:xre,FSEVENT_MODIFIED:bre,FSEVENT_DELETED:Sre,FSEVENT_MOVED:vre,FSEVENT_UNKNOWN:Cre,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:Dre,FSEVENT_TYPE_FILE:wre,FSEVENT_TYPE_DIRECTORY:Kl,FSEVENT_TYPE_SYMLINK:p5,ROOT_GLOBSTAR:c5,DIR_SUFFIX:Are,DOT_SLASH:u5,FUNCTION_TYPE:Yv,EMPTY_FN:Ere,IDENTITY_FN:Rre}=rh(),Ire=t=>isNaN(t)?{}:{depth:t},Xv=tC(eC.stat),_re=tC(eC.lstat),l5=tC(eC.realpath),kre={stat:Xv,lstat:_re},ia=new Map,Fre=10,Tre=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),Pre=(t,e)=>({stop:Nc.watch(t,e)});function Lre(t,e,s,n){let r=ls.extname(e)?ls.dirname(e):e,i=ls.dirname(r),o=ia.get(r);Ore(i)&&(r=i);let a=ls.resolve(t),c=a!==e,u=(d,p,f)=>{c&&(d=d.replace(e,a)),(d===a||!d.indexOf(a+ls.sep))&&s(d,p,f)},l=!1;for(let d of ia.keys())if(e.indexOf(ls.resolve(d)+ls.sep)===0){r=d,o=ia.get(r),l=!0;break}return o||l?o.listeners.add(u):(o={listeners:new Set([u]),rawEmitter:n,watcher:Pre(r,(d,p)=>{if(!o.listeners.size||p&Dre)return;let f=Nc.getInfo(d,p);o.listeners.forEach(m=>{m(d,p,f)}),o.rawEmitter(f.event,d,f)})},ia.set(r,o)),()=>{let d=o.listeners;if(d.delete(u),!d.size&&(ia.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var Ore=t=>{let e=0;for(let s of ia.keys())if(s.indexOf(t)===0&&(e++,e>=Fre))return!0;return!1},Mre=()=>Nc&&ia.size<128,Jv=(t,e)=>{let s=0;for(;!t.indexOf(e)&&(t=ls.dirname(t))!==e;)s++;return s},d5=(t,e)=>t.type===Kl&&e.isDirectory()||t.type===p5&&e.isSymbolicLink()||t.type===wre&&e.isFile(),Qv=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+c5),!0;n.delete(e),n.delete(e+c5)}addOrChange(e,s,n,r,i,o,a,c){let u=i.has(o)?mre:Zv;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 Xv(e);if(this.fsw.closed)return;d5(a,u)?this.addOrChange(e,s,n,r,i,o,a,c):this.handleEvent(uh,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(uh,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===uh){let l=c.type===Kl;(l||o.has(a))&&this.fsw._remove(i,a,l)}else{if(e===Zv){if(c.type===Kl&&this.fsw._getWatchedDir(s),c.type===p5&&u.followSymlinks){let d=u.depth===void 0?void 0:Jv(n,r)+1;return this._addToFsEvents(s,!1,!0,d)}this.fsw._getWatchedDir(i).add(a)}let l=c.type===Kl?e+Are:e;this.fsw._emit(l,s),l===a5&&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=Lre(e,s,async(c,u,l)=>{if(this.fsw.closed||i.depth!==void 0&&Jv(c,s)>i.depth)return;let d=n(ls.join(e,ls.relative(e,c)));if(r&&!r(d))return;let p=ls.dirname(d),f=ls.basename(d),m=this.fsw._getWatchedDir(l.type===Kl?d:p);if(Tre.has(u)||l.event===Cre)if(typeof i.ignored===Yv){let g;try{g=await Xv(d)}catch{}if(this.fsw.closed||this.checkIgnored(d,g))return;d5(l,g)?this.addOrChange(d,c,s,p,m,f,l,i):this.handleEvent(uh,d,c,s,p,m,f,l,i)}else this.checkExists(d,c,s,p,m,f,l,i);else switch(l.event){case xre:case bre:return this.addOrChange(d,c,s,p,m,f,l,i);case Sre:case vre: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 l5(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!==u5?a=o.replace(i,e):o!==u5&&(a=ls.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(ls.dirname(o)),u=ls.basename(o);a&&this.fsw._getWatchedDir(o),!c.has(u)&&(c.add(u),(!r.ignoreInitial||i===!0)&&this.fsw._emit(a?a5:Zv,o,s))}initWatch(e,s,n,r){if(this.fsw.closed)return;let i=this._watchWithFsEvents(n.watchPath,ls.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===Yv?s:Rre,a=this.fsw._getWatchHelpers(e);try{let c=await kre[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),...Ire(i.depth-(r||0))}).on(gre,u=>{if(this.fsw.closed||u.stats.isDirectory()&&!a.filterPath(u))return;let l=ls.join(a.watchPath,u.path),{fullPath:d}=u;if(a.followSymlinks&&u.stats.isSymbolicLink()){let p=i.depth===void 0?void 0:Jv(l,ls.resolve(a.watchPath))+1;this._handleFsEventsSymlink(l,d,o,p)}else this.emitAdd(l,u.stats,o,i,n)}).on(hre,Ere).on(yre,()=>{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===Yv)this.initWatch(void 0,e,a,o);else{let c;try{c=await l5(a.watchPath)}catch{}this.initWatch(c,e,a,o)}}};sC.exports=Qv;sC.exports.canUse=Mre});var w5=M(yC=>{"use strict";var{EventEmitter:Bre}=require("events"),hC=require("fs"),St=require("path"),{promisify:S5}=require("util"),Nre=TB(),cC=aN().default,$re=fN(),nC=Mv(),Wre=ZN(),jre=Lv(),Ure=o5(),m5=f5(),{EV_ALL:rC,EV_READY:Hre,EV_ADD:lh,EV_CHANGE:Zl,EV_UNLINK:h5,EV_ADD_DIR:Gre,EV_UNLINK_DIR:zre,EV_RAW:qre,EV_ERROR:iC,STR_CLOSE:Vre,STR_END:Kre,BACK_SLASH_RE:Zre,DOUBLE_SLASH_RE:g5,SLASH_OR_BACK_SLASH_RE:Yre,DOT_RE:Jre,REPLACER_RE:Xre,SLASH:oC,SLASH_SLASH:Qre,BRACE_START:eie,BANG:uC,ONE_DOT:v5,TWO_DOTS:tie,GLOBSTAR:sie,SLASH_GLOBSTAR:aC,ANYMATCH_OPTS:lC,STRING_TYPE:gC,FUNCTION_TYPE:nie,EMPTY_STR:dC,EMPTY_FN:rie,isWindows:iie,isMacos:oie,isIBMi:aie}=rh(),cie=S5(hC.stat),uie=S5(hC.readdir),pC=(t=[])=>Array.isArray(t)?t:[t],C5=(t,e=[])=>(t.forEach(s=>{Array.isArray(s)?C5(s,e):e.push(s)}),e),y5=t=>{let e=C5(pC(t));if(!e.every(s=>typeof s===gC))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(D5)},x5=t=>{let e=t.replace(Zre,oC),s=!1;for(e.startsWith(Qre)&&(s=!0);e.match(g5);)e=e.replace(g5,oC);return s&&(e=oC+e),e},D5=t=>x5(St.normalize(x5(t))),b5=(t=dC)=>e=>typeof e!==gC?e:D5(St.isAbsolute(e)?e:St.join(t,e)),lie=(t,e)=>St.isAbsolute(t)?t:t.startsWith(uC)?uC+St.join(e,t.slice(1)):St.join(e,t),tr=(t,e)=>t[e]===void 0,fC=class{constructor(e,s){this.path=e,this._removeWatcher=s,this.items=new Set}add(e){let{items:s}=this;s&&e!==v5&&e!==tie&&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 uie(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)}},die="stat",pie="lstat",mC=class{constructor(e,s,n,r){this.fsw=r,this.path=e=e.replace(Xre,dC),this.watchPath=s,this.fullWatchPath=St.resolve(s),this.hasGlob=s!==e,e===dC&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&n?void 0:!1,this.globFilter=this.hasGlob?cC(e,void 0,lC):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=n,this.statMethod=n?die:pie}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===nie?this.globFilter(n):!0)&&this.fsw._isntIgnored(n,s)&&this.fsw._hasReadPermissions(s)}getDirParts(e){if(!this.hasGlob)return[];let s=[];return(e.includes(eie)?Wre.expand(e):[e]).forEach(r=>{s.push(St.relative(this.watchPath,r).split(Yre))}),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===sie&&(n=!0),n||!s[0][o]||cC(i,s[0][o],lC))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},dh=class extends Bre{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,tr(s,"persistent")&&(s.persistent=!0),tr(s,"ignoreInitial")&&(s.ignoreInitial=!1),tr(s,"ignorePermissionErrors")&&(s.ignorePermissionErrors=!1),tr(s,"interval")&&(s.interval=100),tr(s,"binaryInterval")&&(s.binaryInterval=300),tr(s,"disableGlobbing")&&(s.disableGlobbing=!1),s.enableBinaryInterval=s.binaryInterval!==s.interval,tr(s,"useFsEvents")&&(s.useFsEvents=!s.usePolling),m5.canUse()||(s.useFsEvents=!1),tr(s,"usePolling")&&!s.useFsEvents&&(s.usePolling=oie),aie&&(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)),tr(s,"atomic")&&(s.atomic=!s.usePolling&&!s.useFsEvents),s.atomic&&(this._pendingUnlinks=new Map),tr(s,"followSymlinks")&&(s.followSymlinks=!0),tr(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=pC(s.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=rie,this._readyEmitted=!0,process.nextTick(()=>this.emit(Hre)))},this._emitRaw=(...c)=>this.emit(qre,...c),this._readyEmitted=!1,this.options=s,s.useFsEvents?this._fsEventsHandler=new m5(this):this._nodeFsHandler=new Ure(this),Object.freeze(s)}add(e,s,n){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=y5(e);return r&&(o=o.map(a=>{let c=lie(a,r);return i||!nC(a)?c:jre(c)})),o=o.filter(a=>a.startsWith(uC)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+aC),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=y5(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+aC),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||v5]=s.getChildren().sort()}),e}emitWithAll(e,s){this.emit(...s),e!==iC&&this.emit(rC,...s)}async _emit(e,s,n,r,i){if(this.closed)return;let o=this.options;iie&&(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===h5)return this._pendingUnlinks.set(s,a),setTimeout(()=>{this._pendingUnlinks.forEach((l,d)=>{this.emit(...l),this.emit(rC,...l),this._pendingUnlinks.delete(d)})},typeof o.atomic=="number"?o.atomic:100),this;e===lh&&this._pendingUnlinks.has(s)&&(e=a[0]=Zl,this._pendingUnlinks.delete(s))}if(c&&(e===lh||e===Zl)&&this._readyEmitted){let l=(d,p)=>{d?(e=a[0]=iC,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===Zl&&!this._throttle(Zl,s,50))return this;if(o.alwaysStat&&n===void 0&&(e===lh||e===Gre||e===Zl)){let l=o.cwd?St.join(o.cwd,s):s,d;try{d=await cie(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(iC,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=>{hC.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&&Jre.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,r=this.options.ignored,i=r&&r.map(b5(n)),o=pC(i).filter(c=>typeof c===gC&&!nC(c)).map(c=>c+aC),a=this._getGlobIgnored().map(b5(n)).concat(i,o);this._userIgnored=cC(a,void 0,lC)}return this._userIgnored([e,s])}_isntIgnored(e,s){return!this._isIgnored(e,s)}_getWatchHelpers(e,s){let n=s||this.options.disableGlobbing||!nC(e)?e:$re(e),r=this.options.followSymlinks;return new mC(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 fC(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()===lh)return;this._watched.delete(r),this._watched.delete(i);let d=n?zre:h5;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:rC,alwaysStat:!0,lstat:!0,...s},r=Nre(e,n);return this._streams.add(r),r.once(Vre,()=>{r=void 0}),r.once(Kre,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};yC.FSWatcher=dh;var fie=(t,e)=>{let s=new dh(e);return s.add(t),s};yC.watch=fie});var E5,br,mie,hie,A5,gie,R5,I5=D(()=>{"use strict";E5=ce(require("node:fs")),br=ce(require("node:path")),mie=["**/.*","**/.*/**","**/node_modules/**"],hie="cdk.out",A5=t=>t===void 0?[]:Array.isArray(t)?t:[t],gie=t=>{try{let e=E5.readFileSync(t,"utf-8");return JSON.parse(e)??{}}catch{return{}}},R5=(t=process.cwd())=>{let e=t,s=gie(br.join(e,"cdk.json")),n=A5(s.watch?.include),r=A5(s.watch?.exclude),i=s.output??hie,o=n.length>0?n:[e],a=[...r,...mie],c=br.relative(e,br.resolve(e,i));return c.length>0&&!c.startsWith(`..${br.sep}`)&&!br.isAbsolute(c)&&a.push(`${c}/**`),{include:o,exclude:a,rootDir:e}}});var F5,T5,yie,P5,L5,xie,bie,Sie,_5,k5,vie,Cie,O5,M5=D(()=>{"use strict";PS();Jn();F5={critical:0,high:0,medium:0,low:0,total:0},T5={counts:{...F5},byFingerprint:new Map},yie={CRITICAL:"critical",HIGH:"high",MEDIUM:"medium",LOW:"low"},P5=t=>{let e={counts:{...F5},byFingerprint:new Map};if(!t)return e;for(let s of Object.values(t)){let n=[...s.sources?.cdkInsights?.issues??[],...s.sources?.cdkNag?.issues??[]];for(let r of n){let i=r.stackName??"_",o=Sl(i,s,r);if(e.byFingerprint.has(o))continue;e.byFingerprint.set(o,{issue:r,group:s,stackName:i}),e.counts.total+=1;let a=yie[r.severity];a&&(e.counts[a]+=1)}}return e},L5=(t,e)=>{let s=[],n=[];for(let[o,a]of e.byFingerprint)t.byFingerprint.has(o)||s.push({fingerprint:o,...a});for(let[o,a]of t.byFingerprint)e.byFingerprint.has(o)||n.push({fingerprint:o,...a});let r={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3},i=(o,a)=>{let c=r[o.issue.severity]-r[a.issue.severity];return c!==0?c:o.fingerprint.localeCompare(a.fingerprint)};return s.sort(i),n.sort(i),{added:s,removed:n}},xie=t=>t==="CRITICAL"?de.severity.critical:t==="HIGH"?de.severity.high:t==="MEDIUM"?de.severity.medium:de.severity.low,bie=(t,e=70)=>{let s=t.replace(/\s+/g," ").trim();return s.length>e?`${s.slice(0,e-1)}\u2026`:s},Sie=t=>{let e=t.stackName!=="_"?t.stackName:"",s=t.group.cdkPath||t.group.friendlyName||t.group.resourceId||"?";return e&&!s.startsWith(`${e}/`)&&!s.includes("/")?`${e}/${s}`:s},_5=(t,e)=>{let n=xie(e.issue.severity)(e.issue.severity.padEnd(8)),r=de.text(Sie(e)),i=de.comment(bie(e.issue.issue));return` ${t==="+"?de.error("+"):de.success("-")} ${n} ${r} ${i}`},k5=8,vie=t=>t.toTimeString().slice(0,8),Cie=t=>t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`,O5=({state:t,diff:e,trigger:s,elapsedMs:n,timestamp:r,isFirstRun:i,watchPathCount:o})=>{let a=[],c=de.comment("\u2500".repeat(72));a.push(c);let u=[de.primary("\u{1F440} CDK Insights \xB7 watch"),de.comment(vie(r)),de.comment(Cie(n)),de.text(`triggered: ${de.accent(s)}`)].join(de.comment(" \xB7 "));a.push(` ${u}`),a.push("");let{counts:l}=t,d=[`${de.severity.critical(`${Ft.critical} CRITICAL`)} ${de.text(String(l.critical).padStart(3))}`,`${de.severity.high(`${Ft.high} HIGH`)} ${de.text(String(l.high).padStart(3))}`,`${de.severity.medium(`${Ft.medium} MEDIUM`)} ${de.text(String(l.medium).padStart(3))}`,`${de.severity.low(`${Ft.low} LOW`)} ${de.text(String(l.low).padStart(3))}`].join(de.comment(" "));if(a.push(` ${d} ${de.comment("\xB7")} ${de.text(`total ${l.total}`)}`),a.push(""),i)a.push(de.comment(" Initial scan complete."));else if(e&&(e.added.length>0||e.removed.length>0)){a.push(de.text(` ${de.error(`+${e.added.length}`)} new \xB7 ${de.success(`-${e.removed.length}`)} resolved since last save:`));let f=e.added.slice(0,k5);for(let g of f)a.push(_5("+",g));e.added.length>f.length&&a.push(de.comment(` \u2026and ${e.added.length-f.length} more added`));let m=e.removed.slice(0,k5);for(let g of m)a.push(_5("-",g));e.removed.length>m.length&&a.push(de.comment(` \u2026and ${e.removed.length-m.length} more resolved`))}else a.push(de.comment(" No changes since last save."));a.push("");let p=[de.comment(`Watching ${o} pattern(s) \xB7 Ctrl+C to exit \xB7 --output table for full report`)].join("");return a.push(` ${p}`),a.push(c),a.join(`
|
|
456
456
|
`)}});var W5={};xh(W5,{runWatchLoop:()=>Aie});var B5,N5,Die,$5,wie,Aie,j5=D(()=>{"use strict";B5=ce(require("node:path")),N5=ce(w5());I5();Jn();M5();bC();Die=300,$5=t=>t.output!=="table"&&t.format!=="table",wie=t=>{let e=$5(t);return{...t,local:!0,github:!1,withIssue:!1,prComment:!1,writeBaseline:!1,diff:!1,failOnCritical:!1,output:e?"summary":"table",format:e?"summary":"table"}},Aie=async t=>{let e=wie(t.config),s=$5(t.config),{include:n,exclude:r,rootDir:i}=R5(),o=null,a=!1,c=!1,u=T5,l=!0,d=async f=>{if(a){c=!0;return}a=!0;let m=Date.now();P.info(`\u{1F504} ${f}`);try{let g=await xC(e,t.fingerprint,t.authToken,t.licenseInfo,t.usageData,t.project,t.licenseKey,!0,void 0,void 0,void 0,s);if(s){let h=P5(g?.recommendationMaps),x=l?void 0:L5(u,h),b=O5({state:h,diff:x,trigger:f,elapsedMs:Date.now()-m,timestamp:new Date,isFirstRun:l,watchPathCount:n.length});console.clear(),console.log(b),u=h,l=!1}else P.success(`\u2713 Done at ${new Date().toLocaleTimeString()}`)}catch(g){let h=g instanceof Error?g.message:String(g);P.error(`Run failed \u2014 keeping last good results. ${h.split(`
|
|
457
457
|
`)[0]}`)}finally{a=!1,c&&(c=!1,d("queued change(s)"))}};P.info(`\u{1F440} Watch mode \u2014 watching ${n.length} include pattern(s) under ${i}`),P.comment(" AI analysis disabled in watch mode. Press Ctrl+C to exit.");let p=N5.default.watch(n,{cwd:i,ignored:r,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});await d("initial scan"),p.on("all",(f,m)=>{o&&clearTimeout(o),o=setTimeout(()=>{let g=B5.relative(i,m)||m;d(`${f} ${g}`)},Die)}),p.on("error",f=>{P.error(`Watcher error: ${f instanceof Error?f.message:String(f)}`)}),await new Promise(f=>{let m=()=>{P.info(`
|
|
458
|
-
\u{1F44B} Stopping watcher.`),p.close().then(()=>f())};process.once("SIGINT",m),process.once("SIGTERM",m)})}});async function Rie(t,e){let s=t.all?"All stacks":t.stackName||"All stacks",n=await Ei({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 Ei({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 Uy({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 xC(t,e,s,n,r,i,o,a,c,u,l,d){let{stackName:p,output:f,services:m,withIssue:g,ruleFilter:h,failOnCritical:x}=t,b=p==="All stacks"?void 0:p,{stacks:S,inlineFindings:w,pathToLogicalId:A,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:E,cdkVersion:B,supportsBoxTraces:H,cdkContext:C,resourceIdMetadata:W}=Xf(b),k=Object.keys(S).length;P.success(`Synthesis complete. Found ${k} stack${k===1?"":"s"} to analyze.`),B&&!H&&P.info(`Detected aws-cdk-lib ${B}. Upgrade to >= 2.252.0 for per-property source locations on deferred values.`);let V=Object.values(S).reduce((te,Y)=>{let _=Object.entries(Y.Resources||{}).filter(([,se])=>!se.Type.startsWith("AWS::CDK::"));return te+_.length},0);V>0?P.info(`\u{1F50D} Preparing to analyze ${V} total resources across ${k} stacks...`):P.warning("No user resources found in stacks. Make sure your CDK app is properly configured.");let y=null,v=!!s;if(a&&(v=!1,P.info("\u{1F3E0} Running in local mode - static analysis only")),o&&!a){P.info("\u{1F50D} Checking license quota...");let te=n.licenseType==="FREE"||n.status==="TRIAL",Y=n.totalResourcesAnalyzed||0,_=n.trialUsageLimit||n.maxUsage||200,se=Number.isNaN(Y)?0:Y,F=Number.isNaN(_)?200:_;if(te&&se>=F)v=!1,y={canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,quota:{currentResourcesAnalyzed:se,maxResources:F,remainingResources:Math.max(0,F-se),isTrial:!0,trialExpired:!1},reason:`Trial AI credit allowance exceeded (${se}/${F} used)`,upgradePath:"https://cdkinsights.dev/pricing"},P.warning("\u26A0\uFE0F Trial AI credit allowance exceeded \u2014 falling back to static scans only"),P.comment(" Upgrade to Pro for 5,000 AI credits per month");else if(y=await N4({licenseKey:o,requestedResources:V,allowOveruse:t.allowOveruse,usageData:r,licenseInfo:n}),v=!!s&&(y?.canRunAIAnalysis??!0),y?.quota?.isTrial){let oe=y.quota.currentResourcesAnalyzed,xe=y.quota.maxResources;oe>=xe&&(y={...y,canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,reason:`Trial AI credit allowance exceeded (${oe}/${xe} used) \u2014 falling back to static scans only`},v=!1)}y?.quota?.isTrial&&P.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}),!v&&y?.quota?P.displayQuotaWarning({currentResourcesAnalyzed:y.quota.currentResourcesAnalyzed,maxResources:y.quota.maxResources,requestedResources:V,remainingResources:y.quota.remainingResources,isTrial:y.quota.isTrial}):v&&o&&P.success("AI analysis enabled - you'll receive comprehensive recommendations")}let Q=Np(t.services),K=Q.services;Q.removedAllServices?ae.debug(`Services normalization: removed "All services", using: ${K.join(", ")}`):Q.defaultedToAll&&ae.debug('Services normalization: defaulting to "All services"');let ee=c||{},ue=t.warnSensitive||ee.warnOnly||!1,pe=(()=>{let te=C?.["cdkInsights:aiModel"];return typeof te=="string"?te:void 0})(),Ce=Z4({flag:t.model,cdkContext:pe,userConfig:typeof t.ai?.model=="string"?t.ai?.model:void 0,tier:n?.tier});Ce.downgradedFromTierGate?P.warning(`\u26A0\uFE0F Requested AI model "${Ce.requestedAlias}" is not available on your tier \u2014 using "${Ce.alias}" instead.`):Ce.source!=="tierDefault"&&P.comment(`\u{1F916} AI model: ${Ce.alias} (from ${Ce.source})`);let Re=t.ai?.batchSize,re=typeof Re=="number"&&Number.isFinite(Re)?Math.max(1,Math.floor(Re)):void 0;re&&re>1&&P.comment(`\u{1F9FA} AI batching: ${re} resources per call`);let we={stacks:S,inlineFindings:w,pathToLogicalId:A,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:E,output:G5(t),services:K,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:ue,sensitiveDataDetection:{disabled:ee.enabled===!1,ignoreProperties:ee.ignoreProperties||[],allowPatterns:ee.allowPatterns||[],strictMode:ee.strictMode||!1},cdkContext:C,resourceIdMetadata:W,aiModelId:Ce.bedrockModelId,aiBatchSize:re,forceLocal:a,baselineExclude:u,collectFingerprints:l,skipRendering:d};return{...await Nm(we),totalResources:V}}var U5,H5,Eie,G5,z5,bC=D(()=>{"use strict";U5=ce(require("node:fs")),H5=ce(require("node:path"));lb();nr();ap();rF();mb();aF();gF();Ob();Ya();gT();Kb();rv();B4();Ja();py();up();$4();yb();pt();U4();z4();uv();Jn();Y4();Q4();Ll();Eie=()=>{let t=H5.resolve(process.cwd(),"cdk.out");return U5.existsSync(t)},G5=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";z5={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 (nova-lite, mistral-14b, haiku-4-5, sonnet-4-6). 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){Hm(),ae.info("\u{1F5D1}\uFE0F Cleared saved CLI preferences.");return}let s=Ku(),n=s.fingerprint,r=s.project;(!n||n.length===0)&&(P.error("Failed to generate system fingerprint for authentication."),P.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 k=await h_(i,n,r);k?(o=k.token,a=k.usageData,c=k.licenseInfo||await Wm(i,o),k.fingerprint?n=k.fingerprint:n=Ku(o).fingerprint):(P.warning("\u26A0\uFE0F License validation failed. Running in free tier mode."),P.comment(" Check your license key and internet connection."),c=await Wm(i,void 0))}else c=await Wm(void 0,void 0);let u=`${c?.tier??"free"} tier`;P.info(`\u{1F50D} CDK Insights (${u})`),c.tier==="free"&&!i&&(P.comment("\u{1F4A1} Upgrade to Pro for AI-powered recommendations and GitHub integration"),P.comment(" Visit: https://cdkinsights.dev"));let l=er(),d=X4(l,t),p=d.ci||cp();if(p&&!d.ci){let k=zR();P.info(`Detected CI environment${k?`: ${k}`:""}`)}let f=!p&&qR();if(p&&!d.stackName&&!d.all&&(d.all=!0),p&&!d.output&&(d.output="json"),d.watch){(d.writeBaseline||d.diff)&&(P.error("--watch cannot be combined with --writeBaseline or --diff."),P.comment(" Run those modes one-shot, then start `cdk-insights scan --watch` for the live loop."),process.exit(2));let k=["json","sarif","github-actions","markdown"],V=typeof t.output=="string"?t.output:void 0,y=typeof t.format=="string"?t.format:void 0,v=V??y;v&&k.includes(v)?(P.warning(`--watch ignores --output ${v}; using compact summary output.`),d.output="summary",d.format="summary"):v==="table"?(d.output="table",d.format="table"):(d.output="summary",d.format="summary"),d.local=!0,d.failOnCritical=!1,!d.stackName&&!d.all&&(d.stackName="All stacks");let{runWatchLoop:Q}=await Promise.resolve().then(()=>(j5(),W5));await Q({config:d,fingerprint:n,authToken:o,licenseInfo:c,usageData:a,project:r,licenseKey:i});return}Eie()||(P.info("\u26A1 No cdk.out directory found. Running cdk synth..."),fT()||(P.error("Failed to synthesize CDK stacks."),P.comment(" Make sure your CDK app compiles correctly."),process.exit(1)));let m=oF();m.length===0&&(P.error("No CDK stacks found in cdk.out directory."),P.comment(' Make sure you have run "cdk synth" and that your CDK app defines at least one stack.'),P.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)&&(Rr.isFeatureEnabled("githubIntegration",c.tier)?P.success("\u{1F517} GitHub integration enabled"):(P.error("GitHub integration is not available for your current tier"),P.comment(op("githubIntegration",c.tier,"GitHub integration")),process.exit(1))),f&&!d.yes){let k=await Rie(d,g);h={...d,...k}}h.all&&(h.stackName="All stacks"),h.stackName||(h.stackName="All stacks"),f&&h.output||(h.output=G5(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 yc({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 x,b=0;if(h.diff)try{let k=pb(h.baseline);k?(x=new Set(k.fingerprints),b=k.fingerprints.length,P.info(`\u{1F4D0} Diff against baseline (${k.fingerprints.length} known findings; ${k.generatedAt}).`)):P.warning("No baseline file found. Run `cdk-insights scan --writeBaseline` to create one. Showing all findings.")}catch(k){P.error(k instanceof Error?k.message:"Failed to load baseline file."),process.exit(2)}let S=h.writeBaseline?new Set:void 0,w=h.writeBaseline===!0,A=G4(),N=new Date,L=await xC(h,n,o,c,a,r,i,h.local,l.sensitiveDataDetection,x,S,w),E=l.telemetry?.enabled===!0&&!!i;if(h.diff&&x){let k=0,V=[];for(let y of Object.values(L.recommendationMaps||{})){if(!y?.sources)continue;let v=[...y.sources.cdkInsights?.issues??[],...y.sources.cdkNag?.issues??[]];k+=v.length,V.push(...v)}if(P.info(`\u{1F4D0} Diff result: ${k} new finding${k===1?"":"s"} (${b} existing, suppressed).`),E){let y=(()=>{try{return pb(h.baseline)}catch{return null}})();Il({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"diff_run",newFindings:k,existingSuppressed:b,newSeverities:cv(V),baselineGeneratedAt:y?.generatedAt,failedOnCritical:!!L.hasCriticalIssues}})}}if(h.writeBaseline&&S){let k="1.37.5",{path:V,count:y}=nF([...S],{cliVersion:k,overridePath:h.baseline});if(P.success(`\u{1F4CC} Wrote baseline of ${y} finding${y===1?"":"s"} to ${V}.`),P.comment(" On the next run, pass --diff to see only new findings since this point."),E){let v=[],Q={},K=new Set;for(let ee of Object.values(L.recommendationMaps||{})){if(!ee?.sources)continue;let ue=[...ee.sources.cdkInsights?.issues??[],...ee.sources.cdkNag?.issues??[]];v.push(...ue);for(let Ce of ue){let Re=Ce.ruleId,re=/^([A-Za-z][A-Za-z0-9-]+):\s/.exec(Ce.issue??""),we=Re||re?.[1]||"unknown";Q[we]=(Q[we]??0)+1}let pe=ee.type;pe?.startsWith("AWS::")&&K.add(pe.split("::")[1])}Il({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"baseline_written",totalFindings:y,severityCounts:cv(v),ruleHistogram:Q,uniqueServices:K.size}})}return}let B=[],H=L.recommendationMaps||{},C=new Set;for(let[k,V]of Object.entries(H)){let y=V,v=k.includes(":")?k.substring(k.indexOf(":")+1):k,Q=k.includes(":")?k.substring(0,k.indexOf(":")):"";Q&&C.add(Q);let K=[...y.sources.cdkInsights?.issues??[],...y.sources.cdkNag?.issues??[]];for(let ee of K)B.push({resourceId:v,issue:ee.issue,recommendation:ee.recommendation,severity:ee.severity,wafPillar:ee.wafPillar||"Security",foundBy:ee.foundBy||"cdkInsights",constructPath:ee.constructPath,codeSnippet:ee.codeSnippet,sourceLocation:ee.sourceLocation,ruleId:ee.ruleId,context:ee.context,constructType:ee.constructType||y.constructType})}if(h.prComment)if($f()){P.info("Posting analysis summary to PR...");let k=[...C],V={stackNames:k.length>0?k:[h.stackName||"Unknown"],resourceCount:L.totalResources,issues:B,reportUrl:void 0,aiEnabled:!h.local&&!!i,tier:c?.tier||"free"},y=await xb({data:V,updateExisting:!0});y.success?P.success("PR comment posted successfully"):P.warning(`Failed to post PR comment: ${y.error}`)}else P.warning("PR comment requested but not in GitHub Actions PR context. Skipping."),P.comment(" PR comments require: GitHub Actions + pull_request event + GITHUB_TOKEN permissions");if(P.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 k="1.37.5",V=new Date,y=!h.local&&!!i,v=j4({scanId:A,cliVersion:k,recommendationMaps:L.recommendationMaps||{},scannedResourceIds:L.scannedResourceIds??new Set,scanStartedAt:N,scanCompletedAt:V,aiAnalysis:{ran:y}});P.info("\u{1F4E4} Uploading scan to CDK Insights...");let Q=await H4({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,report:v});if(!Q.skipped)if(Q.success)P.success(`Uploaded as scan ${Q.scanId}`),Q.viewUrl&&P.comment(` View: ${Q.viewUrl}`),Q.retentionDays&&P.comment(` Retained for ${Q.retentionDays} day${Q.retentionDays===1?"":"s"} \u2014 adjust in scanHistory settings.`),P.comment(" You opted in via .cdk-insights.json. To opt out, set scanHistory.enabled = false.");else{let K=Q.serverMessage??Q.reason??"unknown";P.warning(`Could not upload scan to CDK Insights (${K}). Run continues normally.`)}}if(l.feedback!==!1&&f&&o&&B.length>0)try{let k=await Ei({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(k!=="skip"){let V=qn(),v=hT({apiClient:{post:async(K,ee)=>{let{data:ue}=await It.post(`${V}${K}`,ee,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-cdk-insights-fingerprint":n,"x-cdk-insights-client":"cli"},timeout:1e4});return ue}}}),Q={};for(let[K,ee]of Object.entries(L.recommendationMaps||{})){let ue=ee,pe=K.includes(":")?K.substring(K.indexOf(":")+1):K;ue.type&&(Q[pe]=ue.type)}if(k==="helpful")v.markReportAsHelpful(B,Q).catch(()=>{}),P.comment(" Thanks for your feedback!");else{let K=B.map(ee=>({issue:ee,rating:k,resourceType:Q[ee.resourceId]}));v.submitBatchFeedback(K).catch(()=>{}),P.comment(" Thanks for your feedback!")}}}catch{}else f||P.comment(" Have feedback? Let us know: https://cdkinsights.dev/feedback?source=cli");L.hasCriticalIssues&&(L.hasSensitiveData&&!h.warnSensitive?(P.error("Sensitive data detected. Exiting with code 1."),P.comment(" Use --warn-sensitive to continue without failing, or fix the issues.")):P.error("Critical issues found. Exiting with code 1."),await new Promise(k=>{process.stdout.write("")?k():process.stdout.once("drain",k)}),process.exit(1))}catch(e){let{message:s}=e;P.error(`An error occurred during analysis: ${s||e}`),process.exit(1)}}}});var $c,n$,s$,zie,r$,i$=D(()=>{"use strict";$c=ce(require("node:fs")),n$=ce(require("node:path")),s$="@aws-cdk/core:stackTrace",zie=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[s$]===!0)return{status:"already-set",updated:t};r[s$]=!0;let i={...s,context:r},o=t.endsWith(`
|
|
458
|
+
\u{1F44B} Stopping watcher.`),p.close().then(()=>f())};process.once("SIGINT",m),process.once("SIGTERM",m)})}});async function Rie(t,e){let s=t.all?"All stacks":t.stackName||"All stacks",n=await Ei({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 Ei({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 Uy({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 xC(t,e,s,n,r,i,o,a,c,u,l,d){let{stackName:p,output:f,services:m,withIssue:g,ruleFilter:h,failOnCritical:x}=t,b=p==="All stacks"?void 0:p,{stacks:S,inlineFindings:w,pathToLogicalId:A,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:E,cdkVersion:B,supportsBoxTraces:H,cdkContext:C,resourceIdMetadata:W}=Xf(b),k=Object.keys(S).length;P.success(`Synthesis complete. Found ${k} stack${k===1?"":"s"} to analyze.`),B&&!H&&P.info(`Detected aws-cdk-lib ${B}. Upgrade to >= 2.252.0 for per-property source locations on deferred values.`);let V=Object.values(S).reduce((te,Y)=>{let _=Object.entries(Y.Resources||{}).filter(([,se])=>!se.Type.startsWith("AWS::CDK::"));return te+_.length},0);V>0?P.info(`\u{1F50D} Preparing to analyze ${V} total resources across ${k} stacks...`):P.warning("No user resources found in stacks. Make sure your CDK app is properly configured.");let y=null,v=!!s;if(a&&(v=!1,P.info("\u{1F3E0} Running in local mode - static analysis only")),o&&!a){P.info("\u{1F50D} Checking license quota...");let te=n.licenseType==="FREE"||n.status==="TRIAL",Y=n.totalResourcesAnalyzed||0,_=n.trialUsageLimit||n.maxUsage||200,se=Number.isNaN(Y)?0:Y,F=Number.isNaN(_)?200:_;if(te&&se>=F)v=!1,y={canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,quota:{currentResourcesAnalyzed:se,maxResources:F,remainingResources:Math.max(0,F-se),isTrial:!0,trialExpired:!1},reason:`Trial AI credit allowance exceeded (${se}/${F} used)`,upgradePath:"https://cdkinsights.dev/pricing"},P.warning("\u26A0\uFE0F Trial AI credit allowance exceeded \u2014 falling back to static scans only"),P.comment(" Upgrade to Pro for 5,000 AI credits per month");else if(y=await N4({licenseKey:o,requestedResources:V,allowOveruse:t.allowOveruse,usageData:r,licenseInfo:n}),v=!!s&&(y?.canRunAIAnalysis??!0),y?.quota?.isTrial){let oe=y.quota.currentResourcesAnalyzed,xe=y.quota.maxResources;oe>=xe&&(y={...y,canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,reason:`Trial AI credit allowance exceeded (${oe}/${xe} used) \u2014 falling back to static scans only`},v=!1)}y?.quota?.isTrial&&P.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}),!v&&y?.quota?P.displayQuotaWarning({currentResourcesAnalyzed:y.quota.currentResourcesAnalyzed,maxResources:y.quota.maxResources,requestedResources:V,remainingResources:y.quota.remainingResources,isTrial:y.quota.isTrial}):v&&o&&P.success("AI analysis enabled - you'll receive comprehensive recommendations")}let Q=Np(t.services),K=Q.services;Q.removedAllServices?ae.debug(`Services normalization: removed "All services", using: ${K.join(", ")}`):Q.defaultedToAll&&ae.debug('Services normalization: defaulting to "All services"');let ee=c||{},ue=t.warnSensitive||ee.warnOnly||!1,pe=(()=>{let te=C?.["cdkInsights:aiModel"];return typeof te=="string"?te:void 0})(),Ce=Z4({flag:t.model,cdkContext:pe,userConfig:typeof t.ai?.model=="string"?t.ai?.model:void 0,tier:n?.tier});Ce.downgradedFromTierGate?P.warning(`\u26A0\uFE0F Requested AI model "${Ce.requestedAlias}" is not available on your tier \u2014 using "${Ce.alias}" instead.`):Ce.source!=="tierDefault"&&P.comment(`\u{1F916} AI model: ${Ce.alias} (from ${Ce.source})`);let Re=t.ai?.batchSize,re=typeof Re=="number"&&Number.isFinite(Re)?Math.max(1,Math.floor(Re)):void 0;re&&re>1&&P.comment(`\u{1F9FA} AI batching: ${re} resources per call`);let we={stacks:S,inlineFindings:w,pathToLogicalId:A,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:E,output:G5(t),services:K,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:ue,sensitiveDataDetection:{disabled:ee.enabled===!1,ignoreProperties:ee.ignoreProperties||[],allowPatterns:ee.allowPatterns||[],strictMode:ee.strictMode||!1},cdkContext:C,resourceIdMetadata:W,aiModelId:Ce.bedrockModelId,aiBatchSize:re,forceLocal:a,baselineExclude:u,collectFingerprints:l,skipRendering:d};return{...await Nm(we),totalResources:V}}var U5,H5,Eie,G5,z5,bC=D(()=>{"use strict";U5=ce(require("node:fs")),H5=ce(require("node:path"));lb();nr();ap();rF();mb();aF();gF();Ob();Ya();gT();Kb();rv();B4();Ja();py();up();$4();yb();pt();U4();z4();uv();Jn();Y4();Q4();Ll();Eie=()=>{let t=H5.resolve(process.cwd(),"cdk.out");return U5.existsSync(t)},G5=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";z5={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 (nova-lite, mistral-14b, haiku-4-5, sonnet-4-6). 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){Hm(),ae.info("\u{1F5D1}\uFE0F Cleared saved CLI preferences.");return}let s=Ku(),n=s.fingerprint,r=s.project;(!n||n.length===0)&&(P.error("Failed to generate system fingerprint for authentication."),P.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 k=await h_(i,n,r);k?(o=k.token,a=k.usageData,c=k.licenseInfo||await Wm(i,o),k.fingerprint?n=k.fingerprint:n=Ku(o).fingerprint):(P.warning("\u26A0\uFE0F License validation failed. Running in free tier mode."),P.comment(" Check your license key and internet connection."),c=await Wm(i,void 0))}else c=await Wm(void 0,void 0);let u=`${c?.tier??"free"} tier`;P.info(`\u{1F50D} CDK Insights (${u})`),c.tier==="free"&&!i&&(P.comment("\u{1F4A1} Upgrade to Pro for AI-powered recommendations and GitHub integration"),P.comment(" Visit: https://cdkinsights.dev"));let l=er(),d=X4(l,t),p=d.ci||cp();if(p&&!d.ci){let k=zR();P.info(`Detected CI environment${k?`: ${k}`:""}`)}let f=!p&&qR();if(p&&!d.stackName&&!d.all&&(d.all=!0),p&&!d.output&&(d.output="json"),d.watch){(d.writeBaseline||d.diff)&&(P.error("--watch cannot be combined with --writeBaseline or --diff."),P.comment(" Run those modes one-shot, then start `cdk-insights scan --watch` for the live loop."),process.exit(2));let k=["json","sarif","github-actions","markdown"],V=typeof t.output=="string"?t.output:void 0,y=typeof t.format=="string"?t.format:void 0,v=V??y;v&&k.includes(v)?(P.warning(`--watch ignores --output ${v}; using compact summary output.`),d.output="summary",d.format="summary"):v==="table"?(d.output="table",d.format="table"):(d.output="summary",d.format="summary"),d.local=!0,d.failOnCritical=!1,!d.stackName&&!d.all&&(d.stackName="All stacks");let{runWatchLoop:Q}=await Promise.resolve().then(()=>(j5(),W5));await Q({config:d,fingerprint:n,authToken:o,licenseInfo:c,usageData:a,project:r,licenseKey:i});return}Eie()||(P.info("\u26A1 No cdk.out directory found. Running cdk synth..."),fT()||(P.error("Failed to synthesize CDK stacks."),P.comment(" Make sure your CDK app compiles correctly."),process.exit(1)));let m=oF();m.length===0&&(P.error("No CDK stacks found in cdk.out directory."),P.comment(' Make sure you have run "cdk synth" and that your CDK app defines at least one stack.'),P.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)&&(Rr.isFeatureEnabled("githubIntegration",c.tier)?P.success("\u{1F517} GitHub integration enabled"):(P.error("GitHub integration is not available for your current tier"),P.comment(op("githubIntegration",c.tier,"GitHub integration")),process.exit(1))),f&&!d.yes){let k=await Rie(d,g);h={...d,...k}}h.all&&(h.stackName="All stacks"),h.stackName||(h.stackName="All stacks"),f&&h.output||(h.output=G5(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 yc({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 x,b=0;if(h.diff)try{let k=pb(h.baseline);k?(x=new Set(k.fingerprints),b=k.fingerprints.length,P.info(`\u{1F4D0} Diff against baseline (${k.fingerprints.length} known findings; ${k.generatedAt}).`)):P.warning("No baseline file found. Run `cdk-insights scan --writeBaseline` to create one. Showing all findings.")}catch(k){P.error(k instanceof Error?k.message:"Failed to load baseline file."),process.exit(2)}let S=h.writeBaseline?new Set:void 0,w=h.writeBaseline===!0,A=G4(),N=new Date,L=await xC(h,n,o,c,a,r,i,h.local,l.sensitiveDataDetection,x,S,w),E=l.telemetry?.enabled===!0&&!!i;if(h.diff&&x){let k=0,V=[];for(let y of Object.values(L.recommendationMaps||{})){if(!y?.sources)continue;let v=[...y.sources.cdkInsights?.issues??[],...y.sources.cdkNag?.issues??[]];k+=v.length,V.push(...v)}if(P.info(`\u{1F4D0} Diff result: ${k} new finding${k===1?"":"s"} (${b} existing, suppressed).`),E){let y=(()=>{try{return pb(h.baseline)}catch{return null}})();Il({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"diff_run",newFindings:k,existingSuppressed:b,newSeverities:cv(V),baselineGeneratedAt:y?.generatedAt,failedOnCritical:!!L.hasCriticalIssues}})}}if(h.writeBaseline&&S){let k="1.37.6",{path:V,count:y}=nF([...S],{cliVersion:k,overridePath:h.baseline});if(P.success(`\u{1F4CC} Wrote baseline of ${y} finding${y===1?"":"s"} to ${V}.`),P.comment(" On the next run, pass --diff to see only new findings since this point."),E){let v=[],Q={},K=new Set;for(let ee of Object.values(L.recommendationMaps||{})){if(!ee?.sources)continue;let ue=[...ee.sources.cdkInsights?.issues??[],...ee.sources.cdkNag?.issues??[]];v.push(...ue);for(let Ce of ue){let Re=Ce.ruleId,re=/^([A-Za-z][A-Za-z0-9-]+):\s/.exec(Ce.issue??""),we=Re||re?.[1]||"unknown";Q[we]=(Q[we]??0)+1}let pe=ee.type;pe?.startsWith("AWS::")&&K.add(pe.split("::")[1])}Il({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"baseline_written",totalFindings:y,severityCounts:cv(v),ruleHistogram:Q,uniqueServices:K.size}})}return}let B=[],H=L.recommendationMaps||{},C=new Set;for(let[k,V]of Object.entries(H)){let y=V,v=k.includes(":")?k.substring(k.indexOf(":")+1):k,Q=k.includes(":")?k.substring(0,k.indexOf(":")):"";Q&&C.add(Q);let K=[...y.sources.cdkInsights?.issues??[],...y.sources.cdkNag?.issues??[]];for(let ee of K)B.push({resourceId:v,issue:ee.issue,recommendation:ee.recommendation,severity:ee.severity,wafPillar:ee.wafPillar||"Security",foundBy:ee.foundBy||"cdkInsights",constructPath:ee.constructPath,codeSnippet:ee.codeSnippet,sourceLocation:ee.sourceLocation,ruleId:ee.ruleId,context:ee.context,constructType:ee.constructType||y.constructType})}if(h.prComment)if($f()){P.info("Posting analysis summary to PR...");let k=[...C],V={stackNames:k.length>0?k:[h.stackName||"Unknown"],resourceCount:L.totalResources,issues:B,reportUrl:void 0,aiEnabled:!h.local&&!!i,tier:c?.tier||"free"},y=await xb({data:V,updateExisting:!0});y.success?P.success("PR comment posted successfully"):P.warning(`Failed to post PR comment: ${y.error}`)}else P.warning("PR comment requested but not in GitHub Actions PR context. Skipping."),P.comment(" PR comments require: GitHub Actions + pull_request event + GITHUB_TOKEN permissions");if(P.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 k="1.37.6",V=new Date,y=!h.local&&!!i,v=j4({scanId:A,cliVersion:k,recommendationMaps:L.recommendationMaps||{},scannedResourceIds:L.scannedResourceIds??new Set,scanStartedAt:N,scanCompletedAt:V,aiAnalysis:{ran:y}});P.info("\u{1F4E4} Uploading scan to CDK Insights...");let Q=await H4({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,report:v});if(!Q.skipped)if(Q.success)P.success(`Uploaded as scan ${Q.scanId}`),Q.viewUrl&&P.comment(` View: ${Q.viewUrl}`),Q.retentionDays&&P.comment(` Retained for ${Q.retentionDays} day${Q.retentionDays===1?"":"s"} \u2014 adjust in scanHistory settings.`),P.comment(" You opted in via .cdk-insights.json. To opt out, set scanHistory.enabled = false.");else{let K=Q.serverMessage??Q.reason??"unknown";P.warning(`Could not upload scan to CDK Insights (${K}). Run continues normally.`)}}if(l.feedback!==!1&&f&&o&&B.length>0)try{let k=await Ei({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(k!=="skip"){let V=qn(),v=hT({apiClient:{post:async(K,ee)=>{let{data:ue}=await It.post(`${V}${K}`,ee,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-cdk-insights-fingerprint":n,"x-cdk-insights-client":"cli"},timeout:1e4});return ue}}}),Q={};for(let[K,ee]of Object.entries(L.recommendationMaps||{})){let ue=ee,pe=K.includes(":")?K.substring(K.indexOf(":")+1):K;ue.type&&(Q[pe]=ue.type)}if(k==="helpful")v.markReportAsHelpful(B,Q).catch(()=>{}),P.comment(" Thanks for your feedback!");else{let K=B.map(ee=>({issue:ee,rating:k,resourceType:Q[ee.resourceId]}));v.submitBatchFeedback(K).catch(()=>{}),P.comment(" Thanks for your feedback!")}}}catch{}else f||P.comment(" Have feedback? Let us know: https://cdkinsights.dev/feedback?source=cli");L.hasCriticalIssues&&(L.hasSensitiveData&&!h.warnSensitive?(P.error("Sensitive data detected. Exiting with code 1."),P.comment(" Use --warn-sensitive to continue without failing, or fix the issues.")):P.error("Critical issues found. Exiting with code 1."),await new Promise(k=>{process.stdout.write("")?k():process.stdout.once("drain",k)}),process.exit(1))}catch(e){let{message:s}=e;P.error(`An error occurred during analysis: ${s||e}`),process.exit(1)}}}});var $c,n$,s$,zie,r$,i$=D(()=>{"use strict";$c=ce(require("node:fs")),n$=ce(require("node:path")),s$="@aws-cdk/core:stackTrace",zie=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[s$]===!0)return{status:"already-set",updated:t};r[s$]=!0;let i={...s,context:r},o=t.endsWith(`
|
|
459
459
|
`)?`
|
|
460
460
|
`:"";return{status:"added",updated:`${JSON.stringify(i,null,2)}${o}`}},r$=t=>{let e=n$.join(t,"cdk.json");if(!$c.existsSync(e))return{status:"missing",cdkJsonPath:e};let s=$c.readFileSync(e,"utf-8"),n=zie(s);return n.status==="invalid-json"?{status:"invalid-json",cdkJsonPath:e}:n.status==="already-set"?{status:"already-set",cdkJsonPath:e}:($c.writeFileSync(e,n.updated,"utf-8"),{status:"added",cdkJsonPath:e})}});var f$=ce(vh()),gh=require("node:child_process"),m$=ce(require("node:path")),h$=require("node:util");nr();var g$=ce(i0());var Vd=require("assert");var HU={right:KU,center:ZU},GU=0,Wd=1,zU=2,jd=3,o0=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(`
|
|
461
461
|
`).map(r=>r.split(" ")),n=0;return s.forEach(r=>{r.length>1&&qs.stringWidth(r[0])>n&&(n=Math.min(Math.floor(this.width*.5),qs.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=qs.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(`
|
|
@@ -579,7 +579,7 @@ ${t.body.join(`
|
|
|
579
579
|
\u2705 Configuration saved successfully!`),console.log(`
|
|
580
580
|
\u{1F4CB} Your current configuration:`),console.log(JSON.stringify(t,null,2))}finally{s.close()}},Jie=()=>{let t=er();console.log("\u{1F4CB} Current Configuration:"),console.log(JSON.stringify(t,null,2))},Xie=t=>{let{key:e,value:s}=t;if(t.help){Xl(e);return}s||(console.log(`
|
|
581
581
|
\u274C No value provided for ${e}`),Xl(e),process.exit(1));let n=er(),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{ae.error(`\u274C Invalid value for ${e}: ${s}`),Xl(e),process.exit(1)}let i=DC[e];i&&(i.type==="boolean"&&typeof r!="boolean"&&(ae.error(`\u274C ${e} must be a boolean (true/false)`),Xl(e),process.exit(1)),i.type==="array"&&!Array.isArray(r)&&(ae.error(`\u274C ${e} must be a comma-separated list`),Xl(e),process.exit(1))),n[e]=r,Pl(n),ae.info(`\u2714\uFE0F ${e} = ${JSON.stringify(r)}`)},Qie=t=>{let{key:e}=t,s=er();if(s[e]===void 0){ae.warn(`\u26A0\uFE0F ${e} not set`);return}delete s[e],Pl(s),ae.info(`\u2714\uFE0F Removed ${e}`)},y$=new Set(["vi","vim","nvim","nano","emacs","code","subl","atom","gedit","kate","notepad","notepad++","micro","helix","pico"]),eoe=t=>{let e=t.split("/").pop()||t;return y$.has(e.toLowerCase())},toe=()=>{let t=Gp.get("EDITOR")||"vi";eoe(t)||(ae.error(`\u274C Unsupported editor: ${t}. Allowed editors: ${Array.from(y$).join(", ")}`),process.exit(1));let e=(0,gh.spawnSync)(t,[Zie],{stdio:"inherit"});e.error&&(ae.error("\u274C Editor error",{error:e.error.message}),process.exit(1)),ae.info("\u2714\uFE0F Config saved")},wC=t=>t.teamId||process.env.CDK_INSIGHTS_TEAM_ID||void 0,AC=()=>{let t=Gp.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}},EC=()=>Gp.get("CDK_INSIGHTS_API_URL")||"https://api.cdkinsights.dev",soe=async t=>{let e=wC(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 It.get(`${EC()}/v1/teams/${e}/configs`,{headers:AC()})).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=Tl(i.configData),c={...er(),...o};Pl(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)}},noe=async t=>{let e=wC(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=er(),n=t.name||"CLI Config",r=t.description||"";console.log(`\u{1F4E4} Pushing local config as "${n}"...`);let o=(await It.post(`${EC()}/v1/teams/${e}/configs`,{configName:n,configDescription:r,configData:s},{headers:AC()})).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)}},roe=async t=>{let e=wC(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...
|
|
582
|
-
`);let n=(await It.get(`${EC()}/v1/teams/${e}/configs`,{headers:AC()})).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)}},ioe=async t=>{let{path:e}=t,s=(0,h$.promisify)(gh.exec),n=e||process.cwd();ae.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&&ae.error(r)}catch(r){ae.error("\u274C Failed to synthesize stacks",{error:r instanceof Error?r.message:String(r)}),process.exit(1)}},ooe=()=>{ae.info("\u{1F5D1}\uFE0F Clearing caches..."),i_(),g_();let t=oy();ae.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ae.info(`\u{1F4CA} Cache status: ${t.cacheFileExists?"Files found":"No persistent cache files"}`)},aoe=()=>{ae.info("\u{1F4CA} Cache Status:");let t=oy();if(ae.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ae.info(`\u{1F4C2} Directory exists: ${t.cacheDirExists?"Yes":"No"}`),ae.info(`\u{1F4C4} Cache file exists: ${t.cacheFileExists?"Yes":"No"}`),t.cacheSize!==void 0){let e=(t.cacheSize/1024).toFixed(2);ae.info(`\u{1F4CF} Cache file size: ${e} KB`)}ae.info(`\u2699\uFE0F Cache enabled: ${o_()?"Yes":"No"}`),ae.info("\u2139\uFE0F Note: Current cache is in-memory and clears on process restart")},coe=()=>{let t=new g$.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 (nova-lite, mistral-14b, haiku-4-5, sonnet-4-6). 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()},uoe={command:"config <action> [key] [value]",describe:"Manage project-level configuration",builder:t=>t.command({command:"list",describe:"Show current configuration",handler:Jie}).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:Xie}).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:Qie}).command({command:"edit",describe:"Open config file in your editor",handler:toe}).command({command:"setup",describe:"Interactive setup to configure CDK Insights",handler:Yie}).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:soe}).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:noe}).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:roe}).demandCommand(1).help(),handler:()=>{}},loe=()=>{GR(m0(process.argv)).scriptName("cdk-insights").version("1.37.
|
|
582
|
+
`);let n=(await It.get(`${EC()}/v1/teams/${e}/configs`,{headers:AC()})).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)}},ioe=async t=>{let{path:e}=t,s=(0,h$.promisify)(gh.exec),n=e||process.cwd();ae.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&&ae.error(r)}catch(r){ae.error("\u274C Failed to synthesize stacks",{error:r instanceof Error?r.message:String(r)}),process.exit(1)}},ooe=()=>{ae.info("\u{1F5D1}\uFE0F Clearing caches..."),i_(),g_();let t=oy();ae.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ae.info(`\u{1F4CA} Cache status: ${t.cacheFileExists?"Files found":"No persistent cache files"}`)},aoe=()=>{ae.info("\u{1F4CA} Cache Status:");let t=oy();if(ae.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ae.info(`\u{1F4C2} Directory exists: ${t.cacheDirExists?"Yes":"No"}`),ae.info(`\u{1F4C4} Cache file exists: ${t.cacheFileExists?"Yes":"No"}`),t.cacheSize!==void 0){let e=(t.cacheSize/1024).toFixed(2);ae.info(`\u{1F4CF} Cache file size: ${e} KB`)}ae.info(`\u2699\uFE0F Cache enabled: ${o_()?"Yes":"No"}`),ae.info("\u2139\uFE0F Note: Current cache is in-memory and clears on process restart")},coe=()=>{let t=new g$.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 (nova-lite, mistral-14b, haiku-4-5, sonnet-4-6). 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()},uoe={command:"config <action> [key] [value]",describe:"Manage project-level configuration",builder:t=>t.command({command:"list",describe:"Show current configuration",handler:Jie}).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:Xie}).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:Qie}).command({command:"edit",describe:"Open config file in your editor",handler:toe}).command({command:"setup",describe:"Interactive setup to configure CDK Insights",handler:Yie}).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:soe}).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:noe}).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:roe}).demandCommand(1).help(),handler:()=>{}},loe=()=>{GR(m0(process.argv)).scriptName("cdk-insights").version("1.37.6").usage("Usage: $0 <command> [options]").command(z5).command(V5).command(e$).command(t$).command(d$).command(p$).command(uoe).command("hook","Install Git pre-commit hook for CDK Insights",()=>{},()=>K5()).command("synth","Run `cdk synth` automatically before analysis",t=>t.option("path",{type:"string",describe:"Path to the CDK project (defaults to current directory)"}),ioe).command("clear-cache","Clear the analysis cache",()=>{},ooe).command("cache-status","Show the current cache status",()=>{},aoe).demandCommand(1,"Please specify a command.").strict().help().wrap(null).epilog(coe()).parse()};loe();
|
|
583
583
|
/*! Bundled license information:
|
|
584
584
|
|
|
585
585
|
mime-db/index.js:
|
package/dist/index.js
CHANGED
|
@@ -77,7 +77,7 @@ ${JSON.stringify(Q)}`}).join(`
|
|
|
77
77
|
`)!=-1,n=this._styles,r=n.length;r--;){var i=Cn[n[r]];t=i.open+t.replace(i.closeRe,i.open)+i.close,s&&(t=t.replace(OL,function(o){return i.close+o+i.open}))}return t}ve.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){ve[s]=function(n){if(typeof e[s]=="object"){var r=n;for(var i in e[s])r=ve[e[s][i]](r);return r}return ve[e[s]](n)}})(t)};function UL(){var e={};return Object.keys(wv).forEach(function(t){e[t]={get:function(){return xv([t])}}}),e}var jL=function(t,s){var n=s.split("");return n=n.map(t),n.join("")};ve.trap=pv();ve.zalgo=mv();ve.maps={};ve.maps.america=gv()(ve);ve.maps.zebra=yv()(ve);ve.maps.rainbow=bv()(ve);ve.maps.random=vv()(ve);for(Cv in ve.maps)(function(e){ve[e]=function(t){return jL(ve.maps[e],t)}})(Cv);var Cv;Av(ve,UL())});var Iv=T((EV,Rv)=>{var $L=Fv();Rv.exports=$L});var Lv=T((FV,ra)=>{var{info:GL,debug:Pv}=sa(),Ft=wl(),Rl=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={};zL.forEach(function(u){Fl(n,r,u,i)}),this.truncate=this.options.truncate||t.truncate;let o=this.options.style=this.options.style||{},a=t.style;Fl(o,a,"padding-left",this),Fl(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=Ft.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(Ft.wordWrap(this.fixedWidth,this.content,i))}return this.wrapLines(this.content.split(`
|
|
78
78
|
`))}wrapLines(t){let s=Ft.colorizeLines(t);return this.href?s.map(n=>Ft.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(Tv,-1),this.height=this.heights.reduce(Tv,-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=Ft.truncate(this.content,10,this.truncate);t||GL(`${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(Ft.repeat(this.chars[this.y==0?"top":"mid"],n))},this):(s.push(this._topLeftChar(0)),s.push(Ft.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=Iv();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 di;)d=this.cells[d.y][d.x-1];d instanceof mi||(i=this.chars.rightMid)}let o=Ft.repeat(" ",this.paddingLeft),a=s?this.chars.right:"",u=Ft.repeat(" ",this.paddingRight),c=this.lines[t],l=this.width-(this.paddingLeft+this.paddingRight);n&&(c+=this.truncate||"\u2026");let p=Ft.truncate(c,l,this.truncate);return p=Ft.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=Ft.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 di;)o=this.cells[o.y][o.x-1];o instanceof mi||(n=this.chars.rightMid)}let r=t?this.chars.right:"",i=Ft.repeat(" ",this.width);return this.stylizeLine(n,i,r)}},di=class{constructor(){}draw(t){return typeof t=="number"&&Pv(`${this.y}-${this.x}: 1x1 ColSpanCell`),""}init(){}mergeTableOptions(){}},mi=class{constructor(t){this.originalCell=t}init(t){let s=this.y,n=this.originalCell.y;this.cellOffset=s-n,this.offset=HL(t.rowHeights,n,this.cellOffset)}draw(t){return t=="top"?this.originalCell.draw(this.offset,this.cellOffset):t=="bottom"?this.originalCell.draw("bottom"):(Pv(`${this.y}-${this.x}: 1x${this.colSpan} RowSpanCell for ${this.originalCell.content}`),this.originalCell.draw(this.offset+1+t))}mergeTableOptions(){}};function kv(...e){return e.filter(t=>t!=null).shift()}function Fl(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]=kv(e[r],e[s],t[r],t[s])):n[s]=kv(e[s],t[s])}function HL(e,t,s){let n=e[t];for(let r=1;r<s;r++)n+=1+e[t+r];return n}function Tv(e,t){return e+t+1}var zL=["top","top-mid","top-left","top-right","bottom","bottom-mid","bottom-left","bottom-right","left","left-mid","mid","mid-mid","right","right-mid","middle"];ra.exports=Rl;ra.exports.ColSpanCell=di;ra.exports.RowSpanCell=mi});var Bv=T((RV,Ov)=>{var{warn:qL,debug:VL}=sa(),Il=Lv(),{ColSpanCell:KL,RowSpanCell:ZL}=Il;(function(){function e(m,f){return m[f]>0?e(m,f+1):f}function t(m){let f={};m.forEach(function(g,h){let y=0;g.forEach(function(b){b.y=h,b.x=h?e(f,y):y;let C=b.rowSpan||1,v=b.colSpan||1;if(C>1)for(let I=0;I<v;I++)f[b.x+I]=C;y=b.x+v}),Object.keys(f).forEach(b=>{f[b]--,f[b]<1&&delete f[b]})})}function s(m){let f=0;return m.forEach(function(g){g.forEach(function(h){f=Math.max(f,h.x+(h.colSpan||1))})}),f}function n(m){return m.length}function r(m,f){let g=m.y,h=m.y-1+(m.rowSpan||1),y=f.y,b=f.y-1+(f.rowSpan||1),C=!(g>b||y>h),v=m.x,I=m.x-1+(m.colSpan||1),N=f.x,B=f.x-1+(f.colSpan||1),F=!(v>B||N>I);return C&&F}function i(m,f,g){let h=Math.min(m.length-1,g),y={x:f,y:g};for(let b=0;b<=h;b++){let C=m[b];for(let v=0;v<C.length;v++)if(r(y,C[v]))return!0}return!1}function o(m,f,g,h){for(let y=g;y<h;y++)if(i(m,y,f))return!1;return!0}function a(m){m.forEach(function(f,g){f.forEach(function(h){for(let y=1;y<h.rowSpan;y++){let b=new ZL(h);b.x=h.x,b.y=h.y+y,b.colSpan=h.colSpan,c(b,m[g+y])}})})}function u(m){for(let f=m.length-1;f>=0;f--){let g=m[f];for(let h=0;h<g.length;h++){let y=g[h];for(let b=1;b<y.colSpan;b++){let C=new KL;C.x=y.x+b,C.y=y.y,g.splice(h+1,0,C)}}}}function c(m,f){let g=0;for(;g<f.length&&f[g].x<m.x;)g++;f.splice(g,0,m)}function l(m){let f=n(m),g=s(m);VL(`Max rows: ${f}; Max cols: ${g}`);for(let h=0;h<f;h++)for(let y=0;y<g;y++)if(!i(m,y,h)){let b={x:y,y:h,colSpan:1,rowSpan:1};for(y++;y<g&&!i(m,y,h);)b.colSpan++,y++;let C=h+1;for(;C<f&&o(m,C,b.x,b.x+b.colSpan);)b.rowSpan++,C++;let v=new Il(b);v.x=b.x,v.y=b.y,qL(`Missing cell at ${v.y}-${v.x}.`),c(v,m[h])}}function p(m){return m.map(function(f){if(!Array.isArray(f)){let g=Object.keys(f)[0];f=f[g],Array.isArray(f)?(f=f.slice(),f.unshift(g)):f=[g,f]}return f.map(function(g){return new Il(g)})})}function d(m){let f=p(m);return t(f),l(f),a(f),u(f),f}Ov.exports={makeTableLayout:d,layoutTable:t,addRowSpanCells:a,maxWidth:s,fillInTable:l,computeWidths:_v("colSpan","desiredWidth","x",1),computeHeights:_v("rowSpan","desiredHeight","y",1)}})();function _v(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 g=1;g<p;g++)m+=1+o[d+g],typeof r[d+g]!="number"&&f++;else m=t==="desiredWidth"?l.desiredWidth-1:1,(!u[d]||u[d]<m)&&(u[d]=m);if(l[t]>m){let g=0;for(;f>0&&l[t]>m;){if(typeof r[d+g]!="number"){let h=Math.round((l[t]-m)/f);m+=h,o[d+g]+=h,f--}g++}}}Object.assign(r,o,u);for(let c=0;c<r.length;c++)r[c]=Math.max(n,r[c]||0)}}});var Nv=T((IV,Mv)=>{var Ss=sa(),YL=wl(),kl=Bv(),ia=class extends Array{constructor(t){super();let s=YL.mergeOptions(t);if(Object.defineProperty(this,"options",{value:s,enumerable:s.debug}),s.debug){switch(typeof s.debug){case"boolean":Ss.setDebugLevel(Ss.WARN);break;case"number":Ss.setDebugLevel(s.debug);break;case"string":Ss.setDebugLevel(parseInt(s.debug,10));break;default:Ss.setDebugLevel(Ss.WARN),Ss.warn(`Debug option is expected to be boolean, number, or string. Received a ${typeof s.debug}`)}Object.defineProperty(this,"messages",{get(){return Ss.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=kl.makeTableLayout(t);n.forEach(function(i){i.forEach(function(o){o.mergeTableOptions(this.options,n)},this)},this),kl.computeWidths(this.options.colWidths,n),kl.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)&&Tl(o,"top",r);for(let u=0;u<a;u++)Tl(o,u,r);i+1==n.length&&Tl(o,"bottom",r)}return r.join(`
|
|
79
79
|
`)}get width(){return this.toString().split(`
|
|
80
|
-
`)[0].length}};ia.reset=()=>Ss.reset();function Tl(e,t,s){let n=[];e.forEach(function(i){n.push(i.draw(t))});let r=n.join("");r.length&&s.push(r)}Mv.exports=ia});var Uv=T((kV,Wv)=>{Wv.exports=Nv()});var Pl=T((PV,e_)=>{e_.exports={name:"cdk-insights",version:"1.37.
|
|
80
|
+
`)[0].length}};ia.reset=()=>Ss.reset();function Tl(e,t,s){let n=[];e.forEach(function(i){n.push(i.draw(t))});let r=n.join("");r.length&&s.push(r)}Mv.exports=ia});var Uv=T((kV,Wv)=>{Wv.exports=Nv()});var Pl=T((PV,e_)=>{e_.exports={name:"cdk-insights",version:"1.37.6",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 lC={};Ci(lC,{STACK_TRACE_CONTEXT_KEY:()=>ga,ensureStackTraceInCdkJson:()=>L_,isStackTraceContextEnabledInCdkJson:()=>__,patchCdkJsonForStackTrace:()=>uC});var Os,ql,ga,uC,L_,__,pC=Ql(()=>{"use strict";Os=K(require("node:fs")),ql=K(require("node:path")),ga="@aws-cdk/core:stackTrace",uC=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[ga]===!0)return{status:"already-set",updated:e};r[ga]=!0;let i={...s,context:r},o=e.endsWith(`
|
|
81
81
|
`)?`
|
|
82
82
|
`:"";return{status:"added",updated:`${JSON.stringify(i,null,2)}${o}`}},L_=e=>{let t=ql.join(e,"cdk.json");if(!Os.existsSync(t))return{status:"missing",cdkJsonPath:t};let s=Os.readFileSync(t,"utf-8"),n=uC(s);return n.status==="invalid-json"?{status:"invalid-json",cdkJsonPath:t}:n.status==="already-set"?{status:"already-set",cdkJsonPath:t}:(Os.writeFileSync(t,n.updated,"utf-8"),{status:"added",cdkJsonPath:t})},__=e=>{try{let t=ql.join(e,"cdk.json");if(!Os.existsSync(t))return!1;let s=JSON.parse(Os.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[ga]===!0}catch{return!1}}});var xO={};Ci(xO,{CDK_INSIGHTS_ANNOTATION_PREFIX:()=>va,CDK_INSIGHTS_METADATA_VERSION:()=>Yl,CDK_INSIGHTS_NAG_FINDING_PREFIX:()=>ya,CdkInsightsAspect:()=>Da,CdkInsightsPolicyValidationPlugin:()=>bi,ExtremelyHelpfulConsoleLogger:()=>Si,SCAN_REPORT_SCHEMA_VERSION:()=>CC,clearCaches:()=>DC,createCdkInsightsAspect:()=>bC,createCdkInsightsLogger:()=>yC,createCdkInsightsPolicyValidationPlugin:()=>LC,createExtremelyHelpfulConsoleLogger:()=>SC,getCacheStats:()=>vC,isCdkDebugEnabled:()=>Jl,runAnalysis:()=>AO});module.exports=Ra(xO);var MC=K(require("node:fs"));function Sr(e,t){return function(){return e.apply(t,arguments)}}var{toString:HC}=Object.prototype,{getPrototypeOf:xi}=Object,{iterator:wi,toStringTag:np}=Symbol,Ei=(e=>t=>{let s=HC.call(t);return e[s]||(e[s]=s.slice(8,-1).toLowerCase())})(Object.create(null)),$t=e=>(e=e.toLowerCase(),t=>Ei(t)===e),Fi=e=>t=>typeof t===e,{isArray:wn}=Array,xn=Fi("undefined");function br(e){return e!==null&&!xn(e)&&e.constructor!==null&&!xn(e.constructor)&&ft(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var rp=$t("ArrayBuffer");function zC(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&rp(e.buffer),t}var qC=Fi("string"),ft=Fi("function"),ip=Fi("number"),Dr=e=>e!==null&&typeof e=="object",VC=e=>e===!0||e===!1,Ai=e=>{if(Ei(e)!=="object")return!1;let t=xi(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(np in e)&&!(wi in e)},KC=e=>{if(!Dr(e)||br(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},ZC=$t("Date"),YC=$t("File"),JC=e=>!!(e&&typeof e.uri<"u"),XC=e=>e&&typeof e.getParts<"u",QC=$t("Blob"),eA=$t("FileList"),tA=e=>Dr(e)&&ft(e.pipe);function sA(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var tp=sA(),sp=typeof tp.FormData<"u"?tp.FormData:void 0,nA=e=>{if(!e)return!1;if(sp&&e instanceof sp)return!0;let t=xi(e);if(!t||t===Object.prototype||!ft(e.append))return!1;let s=Ei(e);return s==="formdata"||s==="object"&&ft(e.toString)&&e.toString()==="[object FormData]"},rA=$t("URLSearchParams"),[iA,oA,aA,cA]=["ReadableStream","Request","Response","Headers"].map($t),uA=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function vr(e,t,{allOwnKeys:s=!1}={}){if(e===null||typeof e>"u")return;let n,r;if(typeof e!="object"&&(e=[e]),wn(e))for(n=0,r=e.length;n<r;n++)t.call(null,e[n],n,e);else{if(br(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 op(e,t){if(br(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 Ws=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ap=e=>!xn(e)&&e!==Ws;function Ia(...e){let{caseless:t,skipUndefined:s}=ap(this)&&this||{},n={},r=(i,o)=>{if(o==="__proto__"||o==="constructor"||o==="prototype")return;let a=t&&op(n,o)||o,u=ka(n,a)?n[a]:void 0;Ai(u)&&Ai(i)?n[a]=Ia(u,i):Ai(i)?n[a]=Ia({},i):wn(i)?n[a]=i.slice():(!s||!xn(i))&&(n[a]=i)};for(let i=0,o=e.length;i<o;i++)e[i]&&vr(e[i],r);return n}var lA=(e,t,s,{allOwnKeys:n}={})=>(vr(t,(r,i)=>{s&&ft(r)?Object.defineProperty(e,i,{__proto__:null,value:Sr(r,s),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,i,{__proto__:null,value:r,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),e),pA=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),dA=(e,t,s,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),s&&Object.assign(e.prototype,s)},mA=(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&&xi(e)}while(e&&(!s||s(e,t))&&e!==Object.prototype);return t},fA=(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},gA=e=>{if(!e)return null;if(wn(e))return e;let t=e.length;if(!ip(t))return null;let s=new Array(t);for(;t-- >0;)s[t]=e[t];return s},hA=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&xi(Uint8Array)),yA=(e,t)=>{let n=(e&&e[wi]).call(e),r;for(;(r=n.next())&&!r.done;){let i=r.value;t.call(e,i[0],i[1])}},SA=(e,t)=>{let s,n=[];for(;(s=e.exec(t))!==null;)n.push(s);return n},bA=$t("HTMLFormElement"),DA=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(s,n,r){return n.toUpperCase()+r}),ka=(({hasOwnProperty:e})=>(t,s)=>e.call(t,s))(Object.prototype),vA=$t("RegExp"),cp=(e,t)=>{let s=Object.getOwnPropertyDescriptors(e),n={};vr(s,(r,i)=>{let o;(o=t(r,i,e))!==!1&&(n[i]=o||r)}),Object.defineProperties(e,n)},CA=e=>{cp(e,(t,s)=>{if(ft(e)&&["arguments","caller","callee"].includes(s))return!1;let n=e[s];if(ft(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+"'")})}})},AA=(e,t)=>{let s={},n=r=>{r.forEach(i=>{s[i]=!0})};return wn(e)?n(e):n(String(e).split(t)),s},xA=()=>{},wA=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function EA(e){return!!(e&&ft(e.append)&&e[np]==="FormData"&&e[wi])}var FA=e=>{let t=new Array(10),s=(n,r)=>{if(Dr(n)){if(t.indexOf(n)>=0)return;if(br(n))return n;if(!("toJSON"in n)){t[r]=n;let i=wn(n)?[]:{};return vr(n,(o,a)=>{let u=s(o,r+1);!xn(u)&&(i[a]=u)}),t[r]=void 0,i}}return n};return s(e,0)},RA=$t("AsyncFunction"),IA=e=>e&&(Dr(e)||ft(e))&&ft(e.then)&&ft(e.catch),up=((e,t)=>e?setImmediate:t?((s,n)=>(Ws.addEventListener("message",({source:r,data:i})=>{r===Ws&&i===s&&n.length&&n.shift()()},!1),r=>{n.push(r),Ws.postMessage(s,"*")}))(`axios@${Math.random()}`,[]):s=>setTimeout(s))(typeof setImmediate=="function",ft(Ws.postMessage)),kA=typeof queueMicrotask<"u"?queueMicrotask.bind(Ws):typeof process<"u"&&process.nextTick||up,TA=e=>e!=null&&ft(e[wi]),D={isArray:wn,isArrayBuffer:rp,isBuffer:br,isFormData:nA,isArrayBufferView:zC,isString:qC,isNumber:ip,isBoolean:VC,isObject:Dr,isPlainObject:Ai,isEmptyObject:KC,isReadableStream:iA,isRequest:oA,isResponse:aA,isHeaders:cA,isUndefined:xn,isDate:ZC,isFile:YC,isReactNativeBlob:JC,isReactNative:XC,isBlob:QC,isRegExp:vA,isFunction:ft,isStream:tA,isURLSearchParams:rA,isTypedArray:hA,isFileList:eA,forEach:vr,merge:Ia,extend:lA,trim:uA,stripBOM:pA,inherits:dA,toFlatObject:mA,kindOf:Ei,kindOfTest:$t,endsWith:fA,toArray:gA,forEachEntry:yA,matchAll:SA,isHTMLForm:bA,hasOwnProperty:ka,hasOwnProp:ka,reduceDescriptors:cp,freezeMethods:CA,toObjectSet:AA,toCamelCase:DA,noop:xA,toFiniteNumber:wA,findKey:op,global:Ws,isContextDefined:ap,isSpecCompliantForm:EA,toJSONObject:FA,isAsyncFn:RA,isThenable:IA,setImmediate:up,asap:kA,isIterable:TA};var PA=D.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"]),lp=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]&&PA[s])&&(s==="set-cookie"?t[s]?t[s].push(n):t[s]=[n]:t[s]=t[s]?t[s]+", "+n:n)}),t};var pp=Symbol("internals"),LA=/[^\x09\x20-\x7E\x80-\xFF]/g;function _A(e){let t=0,s=e.length;for(;t<s;){let n=e.charCodeAt(t);if(n!==9&&n!==32)break;t+=1}for(;s>t;){let n=e.charCodeAt(s-1);if(n!==9&&n!==32)break;s-=1}return t===0&&s===e.length?e:e.slice(t,s)}function Cr(e){return e&&String(e).trim().toLowerCase()}function OA(e){return _A(e.replace(LA,""))}function Ri(e){return e===!1||e==null?e:D.isArray(e)?e.map(Ri):OA(String(e))}function BA(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 MA=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Ta(e,t,s,n,r){if(D.isFunction(n))return n.call(this,t,s);if(r&&(t=s),!!D.isString(t)){if(D.isString(n))return t.indexOf(n)!==-1;if(D.isRegExp(n))return n.test(t)}}function NA(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,s,n)=>s.toUpperCase()+n)}function WA(e,t){let s=D.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+s,{__proto__:null,value:function(r,i,o){return this[n].call(this,t,r,i,o)},configurable:!0})})}var En=class{constructor(t){t&&this.set(t)}set(t,s,n){let r=this;function i(a,u,c){let l=Cr(u);if(!l)throw new Error("header name must be a non-empty string");let p=D.findKey(r,l);(!p||r[p]===void 0||c===!0||c===void 0&&r[p]!==!1)&&(r[p||u]=Ri(a))}let o=(a,u)=>D.forEach(a,(c,l)=>i(c,l,u));if(D.isPlainObject(t)||t instanceof this.constructor)o(t,s);else if(D.isString(t)&&(t=t.trim())&&!MA(t))o(lp(t),s);else if(D.isObject(t)&&D.isIterable(t)){let a={},u,c;for(let l of t){if(!D.isArray(l))throw TypeError("Object iterator must return a key-value pair");a[c=l[0]]=(u=a[c])?D.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=Cr(t),t){let n=D.findKey(this,t);if(n){let r=this[n];if(!s)return r;if(s===!0)return BA(r);if(D.isFunction(s))return s.call(this,r,n);if(D.isRegExp(s))return s.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,s){if(t=Cr(t),t){let n=D.findKey(this,t);return!!(n&&this[n]!==void 0&&(!s||Ta(this,this[n],n,s)))}return!1}delete(t,s){let n=this,r=!1;function i(o){if(o=Cr(o),o){let a=D.findKey(n,o);a&&(!s||Ta(n,n[a],a,s))&&(delete n[a],r=!0)}}return D.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||Ta(this,this[i],i,t,!0))&&(delete this[i],r=!0)}return r}normalize(t){let s=this,n={};return D.forEach(this,(r,i)=>{let o=D.findKey(n,i);if(o){s[o]=Ri(r),delete s[i];return}let a=t?NA(i):String(i).trim();a!==i&&delete s[i],s[a]=Ri(r),n[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let s=Object.create(null);return D.forEach(this,(n,r)=>{n!=null&&n!==!1&&(s[r]=t&&D.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(`
|
|
@@ -124,7 +124,7 @@ ${q.comment("\u{1F4A1} Next Steps:")}`),U?(e.log(q.error(" \u274C Trial expire
|
|
|
124
124
|
`)},displayQuotaWarning:_=>{let{currentResourcesAnalyzed:W,maxResources:ee,requestedResources:X,isTrial:U}=_;if(!U)return;W+X>ee&&(e.log(`
|
|
125
125
|
${q.warning.bold("\u26A0\uFE0F AI credit allowance exceeded")}`),e.log(q.comment("\u2500".repeat(40))),e.log(q.warning(` You've used ${W}/${ee} AI credits`)),e.log(q.warning(` This analysis would add ${X} more`)),e.log(q.warning(` Total would be ${W+X}/${ee}`)),e.log(`
|
|
126
126
|
${q.info("\u{1F4CB} Falling back to static analysis only")}`),e.log(q.comment("\u{1F4A1} Upgrade to Pro for unlimited AI analysis: https://cdkinsights.dev/pricing")),e.log(`${q.comment("\u2500".repeat(40))}
|
|
127
|
-
`))}}},V=NP();var yD=e=>e&&(e.Name||e.ResourceName||e.FunctionName)||"Unnamed";var pl=null,SD=e=>{pl=e};var dl=()=>{if(pl&&!process.env.CI)try{pl.saveToDisk(),st.info("\u{1F4BE} Cache saved to disk on exit")}catch(e){st.warn("\u26A0\uFE0F Could not save cache on exit",{error:e instanceof Error?e.message:String(e)})}};process.on("exit",dl);process.on("SIGINT",()=>{dl(),process.exit(0)});process.on("SIGTERM",()=>{dl(),process.exit(0)});var WP={maxConcurrent:Xr.DEFAULT_MAX_CONCURRENT,retryAttempts:Xr.DEFAULT_RETRY_ATTEMPTS,retryDelay:Xr.DEFAULT_RETRY_DELAY_MS,timeoutMs:Xr.DEFAULT_TIMEOUT_MS},UP=e=>{if(!(e instanceof Error))return!1;let t=e.message??"";return t.startsWith("Polling timed out")||t==="Analysis timeout"||t.toLowerCase().includes("timeout")},Yo=(e,t)=>{let s=e.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return e;let[,n,r=""]=s;return`${ur(t,n)}${r}`},jP=e=>{let t=Ur({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 UP(s)?{status:"timeout",redactedId:n}:(t.set(i,o+1),o>e.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},$P=({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:g})=>{let h=f.get(d)||[],y=m[d];if(!y)return{status:"skipped",redactedId:d};let C=wu(d,y,i,o,[]),v=Eu(C),I=t[d];if(!I)return{status:"skipped",redactedId:d};let N=I,B=()=>(s[N]||(s[N]={issues:[]}),s[N]),F=u.get(v);if(F){let ye=(F.issues||[]).map(_=>({..._,resource:N,resourceId:N})),oe=B();return oe.issues.push(...bn({existing:oe.issues,incoming:ye})),oe.resourceName=F.resourceName,{status:"success",redactedId:d,resourceKey:N,remappedIssues:ye,resourceName:F.resourceName}}let z=ur(a,I),H=ur("cdk-insights-stack",a),Q=Xi(I,l,c),re={dependencies:Q.dependencies.map(ye=>Yo(ye,a)),dependents:Q.dependents.map(ye=>Yo(ye,a)),usageDescription:Q.usageDescription};for(let ye=1;ye<=r.retryAttempts;ye++)try{let oe=await Promise.race([e(H,z,y,y.Type,i,o,h,g,re,p),new Promise((ee,X)=>setTimeout(()=>X(new Error("Analysis timeout")),r.timeoutMs))]);oe.resourceId=N;let _=(oe.issues||[]).map(ee=>({...ee,resource:N,resourceId:N})),W=B();return W.issues.push(...bn({existing:W.issues,incoming:_})),W.resourceName=oe.resourceName,u.set(v,oe,C),{status:"success",redactedId:d,resourceKey:N,remappedIssues:_,resourceName:oe.resourceName}}catch(oe){if(ye===r.retryAttempts)return n({analysisError:oe,redactedId:d});await new Promise(_=>setTimeout(_,r.retryDelay*2**(ye-1)))}return{status:"fail",redactedId:d,error:new Error("Max retries exceeded")}},GP=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)},HP=10,bD=({analyzeResource:e,analyzeResourcesBatch:t,redactResources:s,config:n=WP})=>async({stackName:r,resources:i,authToken:o,existingFindingsMap:a,pathToLogicalId:u,fingerprint:c,noCache:l=!1,cacheConfig:p,aiModelId:d,aiBatchSize:m})=>{let f={},g=[],h={startTime:Date.now(),processedCount:0,successCount:0,failureCount:0,timeoutCount:0},{redactedResources:y,mapping:b}=s(i),C=ob(a,b,u),v=new Map;for(let U of C){let Y=v.get(U.resourceId);Y?Y.push(U):v.set(U.resourceId,[U])}let I=Object.keys(y),N=I.length,B=Vs(i),F=new Bo({ttl:p?.ttl||6*60*60*1e3,maxSize:p?.maxSize||5e3,disabled:l||!p?.enabled});SD(F);let z=jP(n),H=$P({analyzeResource:e,redactionMapping:b,aggregatedResult:f,errorHandler:z,config:n,authToken:o,fingerprint:c,stackName:r,analysisCache:F,originalResources:i,relationships:B,aiModelId:d}),Q=Ko.createSingleLineProgressTracker(N,"Analyzing resources with AI"),re=Math.min(Math.max(1,Math.floor(m??1)),HP);if(re>1&&!!t&&t){st.debug("Batched analysis enabled",{batchSize:re,totalResources:N});let U=ur("cdk-insights-stack",r),Y=te=>{let de=Xi(te,B,i);return{dependencies:de.dependencies.map(ce=>Yo(ce,r)),dependents:de.dependents.map(ce=>Yo(ce,r)),usageDescription:de.usageDescription}};for(let te=0;te<I.length;te+=re){let de=I.slice(te,te+re),ce=async()=>{for(let xe of de){let O=await H({redactedId:xe,redactedResources:y,findingsByResource:v,progressTracker:Q});switch(h.processedCount++,O.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:xe,resourceData:y[xe],resourceType:y[xe].Type,existingFindings:v.get(xe)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},Ae=new Map,le=[];for(let xe of de){let O=y[xe],P=b[xe];if(!O||!P){h.processedCount++,h.failureCount++;continue}let se=wu(xe,O,o,c,[]),ne=Eu(se),J=F.get(ne);if(J){let Ye=(J.issues||[]).map(lt=>({...lt,resource:P,resourceId:P}));f[P]||(f[P]={issues:[]});let Ce=f[P];Ce.issues.push(...bn({existing:Ce.issues,incoming:Ye})),Ce.resourceName=J.resourceName,h.processedCount++,h.successCount++;continue}let Pe=ur(r,P);Ae.set(Pe,{redactedId:xe,originalResourceId:P,cacheKey:ne,cacheComponents:se}),le.push({stableResourceId:Pe,resourceData:O,resourceType:O.Type,context:Y(P),existingFindings:v.get(xe)||[]})}if(le.length!==0)try{let xe=await Promise.race([t(U,le,o,c,d),new Promise((O,P)=>setTimeout(()=>P(new Error("Analysis timeout")),n.timeoutMs))]);for(let[O,P]of Ae){let se=xe.get(O);if(h.processedCount++,!se){st.warn(`Batched response missing entry for resource ${P.originalResourceId}`,{stableResourceId:O,redactedId:P.redactedId}),h.failureCount++;continue}let ne=(se.issues||[]).map(Pe=>({...Pe,resource:P.originalResourceId,resourceId:P.originalResourceId}));f[P.originalResourceId]||(f[P.originalResourceId]={issues:[]});let J=f[P.originalResourceId];J.issues.push(...bn({existing:J.issues,incoming:ne})),J.resourceName=se.resourceName,F.set(P.cacheKey,{resourceId:P.originalResourceId,issues:se.issues||[],resourceName:se.resourceName},P.cacheComponents),h.successCount++}}catch(xe){st.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:xe instanceof Error?xe.message:String(xe),chunkSize:de.length}),await ce()}}}else await GP(I,n.maxConcurrent,async U=>{st.debug(`Starting analysis for resource ${U}`,{redactedId:U,maxConcurrent:n.maxConcurrent});let Y=await H({redactedId:U,redactedResources:y,findingsByResource:v,progressTracker:Q});switch(h.processedCount++,st.debug(`Resource ${U} analysis result: ${Y.status}`,{redactedId:U,status:Y.status,hasProgressTracker:!!Q}),Y.status){case"success":h.successCount++,st.debug(`Resource ${U} completed successfully`,{redactedId:U,resourceKey:Y.resourceKey});break;case"timeout":h.timeoutCount++,st.warn(`Resource ${U} timed out`,{redactedId:U}),g.push({redactedId:U,resourceData:y[U],resourceType:y[U].Type,existingFindings:v.get(U)||[]});break;case"fail":case"skipped":h.failureCount++,st.warn(`Resource ${U} failed or was skipped`,{redactedId:U,status:Y.status});break}});let oe=Date.now()-h.startTime,_=Q.getStats();if(st.debug("Analysis completed with progress tracker stats",{progressTrackerStats:_,performanceMetrics:h,totalTime:oe,totalResources:N,maxConcurrent:n.maxConcurrent}),V.analysisComplete(oe,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){V.newline(),V.info("\u{1F4CA} Performance Analysis:");let U=h.successCount>0?Math.round(oe/1e3/h.successCount):0;V.comment(` \u23F1\uFE0F Average completion time: ${U}s`),V.comment(` \u{1F4CA} Success rate: ${(h.successCount/N*100).toFixed(1)}%`)}if(g.length>0){V.newline(),V.warning("\u23F0 Timed Out Resources:"),V.comment(` \u{1F4CB} Total timed out: ${g.length}`);for(let U of g){if(V.comment(` \u274C ${U.resourceType}: ${U.redactedId}`),U.resourceData?.Properties){let te=U.resourceData.Properties,de=yD(te);V.comment(` \u{1F4DD} Name: ${de}`)}U.existingFindings.length>0&&V.comment(` \u{1F50D} Existing findings: ${U.existingFindings.length}`),U.resourceData?.Metadata&&V.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(U.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 ${g.length} resource${g.length===1?"":"s"} that need a little more time...`)}let W=new Set(Object.keys(f)),ee=new Set(Object.values(b)),X=Array.from(ee).filter(U=>!W.has(U)||!f[U]?.issues?.length);if(X.length>0){let U=F.getCachedResultsForResources(X),Y=0;for(let[te,de]of Array.from(U.entries())){if(f[te]?.issues?.length>0)continue;let ce=(de.issues||[]).map(Ae=>({...Ae,resource:te,resourceId:te}));ce.length>0&&(f[te]||(f[te]={issues:[]}),f[te].issues.push(...ce),f[te].resourceName=de.resourceName,Y+=ce.length)}Y>0}return f};var ml=require("node:child_process"),nt=K(require("node:fs")),fl=K(require("node:os")),ci=K(require("node:path"));var CD="1.37.5",zP={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/"},DD=e=>e.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),qP=(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},VP=e=>e?e.split(`
|
|
127
|
+
`))}}},V=NP();var yD=e=>e&&(e.Name||e.ResourceName||e.FunctionName)||"Unnamed";var pl=null,SD=e=>{pl=e};var dl=()=>{if(pl&&!process.env.CI)try{pl.saveToDisk(),st.info("\u{1F4BE} Cache saved to disk on exit")}catch(e){st.warn("\u26A0\uFE0F Could not save cache on exit",{error:e instanceof Error?e.message:String(e)})}};process.on("exit",dl);process.on("SIGINT",()=>{dl(),process.exit(0)});process.on("SIGTERM",()=>{dl(),process.exit(0)});var WP={maxConcurrent:Xr.DEFAULT_MAX_CONCURRENT,retryAttempts:Xr.DEFAULT_RETRY_ATTEMPTS,retryDelay:Xr.DEFAULT_RETRY_DELAY_MS,timeoutMs:Xr.DEFAULT_TIMEOUT_MS},UP=e=>{if(!(e instanceof Error))return!1;let t=e.message??"";return t.startsWith("Polling timed out")||t==="Analysis timeout"||t.toLowerCase().includes("timeout")},Yo=(e,t)=>{let s=e.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return e;let[,n,r=""]=s;return`${ur(t,n)}${r}`},jP=e=>{let t=Ur({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 UP(s)?{status:"timeout",redactedId:n}:(t.set(i,o+1),o>e.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},$P=({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:g})=>{let h=f.get(d)||[],y=m[d];if(!y)return{status:"skipped",redactedId:d};let C=wu(d,y,i,o,[]),v=Eu(C),I=t[d];if(!I)return{status:"skipped",redactedId:d};let N=I,B=()=>(s[N]||(s[N]={issues:[]}),s[N]),F=u.get(v);if(F){let ye=(F.issues||[]).map(_=>({..._,resource:N,resourceId:N})),oe=B();return oe.issues.push(...bn({existing:oe.issues,incoming:ye})),oe.resourceName=F.resourceName,{status:"success",redactedId:d,resourceKey:N,remappedIssues:ye,resourceName:F.resourceName}}let z=ur(a,I),H=ur("cdk-insights-stack",a),Q=Xi(I,l,c),re={dependencies:Q.dependencies.map(ye=>Yo(ye,a)),dependents:Q.dependents.map(ye=>Yo(ye,a)),usageDescription:Q.usageDescription};for(let ye=1;ye<=r.retryAttempts;ye++)try{let oe=await Promise.race([e(H,z,y,y.Type,i,o,h,g,re,p),new Promise((ee,X)=>setTimeout(()=>X(new Error("Analysis timeout")),r.timeoutMs))]);oe.resourceId=N;let _=(oe.issues||[]).map(ee=>({...ee,resource:N,resourceId:N})),W=B();return W.issues.push(...bn({existing:W.issues,incoming:_})),W.resourceName=oe.resourceName,u.set(v,oe,C),{status:"success",redactedId:d,resourceKey:N,remappedIssues:_,resourceName:oe.resourceName}}catch(oe){if(ye===r.retryAttempts)return n({analysisError:oe,redactedId:d});await new Promise(_=>setTimeout(_,r.retryDelay*2**(ye-1)))}return{status:"fail",redactedId:d,error:new Error("Max retries exceeded")}},GP=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)},HP=10,bD=({analyzeResource:e,analyzeResourcesBatch:t,redactResources:s,config:n=WP})=>async({stackName:r,resources:i,authToken:o,existingFindingsMap:a,pathToLogicalId:u,fingerprint:c,noCache:l=!1,cacheConfig:p,aiModelId:d,aiBatchSize:m})=>{let f={},g=[],h={startTime:Date.now(),processedCount:0,successCount:0,failureCount:0,timeoutCount:0},{redactedResources:y,mapping:b}=s(i),C=ob(a,b,u),v=new Map;for(let U of C){let Y=v.get(U.resourceId);Y?Y.push(U):v.set(U.resourceId,[U])}let I=Object.keys(y),N=I.length,B=Vs(i),F=new Bo({ttl:p?.ttl||6*60*60*1e3,maxSize:p?.maxSize||5e3,disabled:l||!p?.enabled});SD(F);let z=jP(n),H=$P({analyzeResource:e,redactionMapping:b,aggregatedResult:f,errorHandler:z,config:n,authToken:o,fingerprint:c,stackName:r,analysisCache:F,originalResources:i,relationships:B,aiModelId:d}),Q=Ko.createSingleLineProgressTracker(N,"Analyzing resources with AI"),re=Math.min(Math.max(1,Math.floor(m??1)),HP);if(re>1&&!!t&&t){st.debug("Batched analysis enabled",{batchSize:re,totalResources:N});let U=ur("cdk-insights-stack",r),Y=te=>{let de=Xi(te,B,i);return{dependencies:de.dependencies.map(ce=>Yo(ce,r)),dependents:de.dependents.map(ce=>Yo(ce,r)),usageDescription:de.usageDescription}};for(let te=0;te<I.length;te+=re){let de=I.slice(te,te+re),ce=async()=>{for(let xe of de){let O=await H({redactedId:xe,redactedResources:y,findingsByResource:v,progressTracker:Q});switch(h.processedCount++,O.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:xe,resourceData:y[xe],resourceType:y[xe].Type,existingFindings:v.get(xe)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},Ae=new Map,le=[];for(let xe of de){let O=y[xe],P=b[xe];if(!O||!P){h.processedCount++,h.failureCount++;continue}let se=wu(xe,O,o,c,[]),ne=Eu(se),J=F.get(ne);if(J){let Ye=(J.issues||[]).map(lt=>({...lt,resource:P,resourceId:P}));f[P]||(f[P]={issues:[]});let Ce=f[P];Ce.issues.push(...bn({existing:Ce.issues,incoming:Ye})),Ce.resourceName=J.resourceName,h.processedCount++,h.successCount++;continue}let Pe=ur(r,P);Ae.set(Pe,{redactedId:xe,originalResourceId:P,cacheKey:ne,cacheComponents:se}),le.push({stableResourceId:Pe,resourceData:O,resourceType:O.Type,context:Y(P),existingFindings:v.get(xe)||[]})}if(le.length!==0)try{let xe=await Promise.race([t(U,le,o,c,d),new Promise((O,P)=>setTimeout(()=>P(new Error("Analysis timeout")),n.timeoutMs))]);for(let[O,P]of Ae){let se=xe.get(O);if(h.processedCount++,!se){st.warn(`Batched response missing entry for resource ${P.originalResourceId}`,{stableResourceId:O,redactedId:P.redactedId}),h.failureCount++;continue}let ne=(se.issues||[]).map(Pe=>({...Pe,resource:P.originalResourceId,resourceId:P.originalResourceId}));f[P.originalResourceId]||(f[P.originalResourceId]={issues:[]});let J=f[P.originalResourceId];J.issues.push(...bn({existing:J.issues,incoming:ne})),J.resourceName=se.resourceName,F.set(P.cacheKey,{resourceId:P.originalResourceId,issues:se.issues||[],resourceName:se.resourceName},P.cacheComponents),h.successCount++}}catch(xe){st.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:xe instanceof Error?xe.message:String(xe),chunkSize:de.length}),await ce()}}}else await GP(I,n.maxConcurrent,async U=>{st.debug(`Starting analysis for resource ${U}`,{redactedId:U,maxConcurrent:n.maxConcurrent});let Y=await H({redactedId:U,redactedResources:y,findingsByResource:v,progressTracker:Q});switch(h.processedCount++,st.debug(`Resource ${U} analysis result: ${Y.status}`,{redactedId:U,status:Y.status,hasProgressTracker:!!Q}),Y.status){case"success":h.successCount++,st.debug(`Resource ${U} completed successfully`,{redactedId:U,resourceKey:Y.resourceKey});break;case"timeout":h.timeoutCount++,st.warn(`Resource ${U} timed out`,{redactedId:U}),g.push({redactedId:U,resourceData:y[U],resourceType:y[U].Type,existingFindings:v.get(U)||[]});break;case"fail":case"skipped":h.failureCount++,st.warn(`Resource ${U} failed or was skipped`,{redactedId:U,status:Y.status});break}});let oe=Date.now()-h.startTime,_=Q.getStats();if(st.debug("Analysis completed with progress tracker stats",{progressTrackerStats:_,performanceMetrics:h,totalTime:oe,totalResources:N,maxConcurrent:n.maxConcurrent}),V.analysisComplete(oe,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){V.newline(),V.info("\u{1F4CA} Performance Analysis:");let U=h.successCount>0?Math.round(oe/1e3/h.successCount):0;V.comment(` \u23F1\uFE0F Average completion time: ${U}s`),V.comment(` \u{1F4CA} Success rate: ${(h.successCount/N*100).toFixed(1)}%`)}if(g.length>0){V.newline(),V.warning("\u23F0 Timed Out Resources:"),V.comment(` \u{1F4CB} Total timed out: ${g.length}`);for(let U of g){if(V.comment(` \u274C ${U.resourceType}: ${U.redactedId}`),U.resourceData?.Properties){let te=U.resourceData.Properties,de=yD(te);V.comment(` \u{1F4DD} Name: ${de}`)}U.existingFindings.length>0&&V.comment(` \u{1F50D} Existing findings: ${U.existingFindings.length}`),U.resourceData?.Metadata&&V.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(U.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 ${g.length} resource${g.length===1?"":"s"} that need a little more time...`)}let W=new Set(Object.keys(f)),ee=new Set(Object.values(b)),X=Array.from(ee).filter(U=>!W.has(U)||!f[U]?.issues?.length);if(X.length>0){let U=F.getCachedResultsForResources(X),Y=0;for(let[te,de]of Array.from(U.entries())){if(f[te]?.issues?.length>0)continue;let ce=(de.issues||[]).map(Ae=>({...Ae,resource:te,resourceId:te}));ce.length>0&&(f[te]||(f[te]={issues:[]}),f[te].issues.push(...ce),f[te].resourceName=de.resourceName,Y+=ce.length)}Y>0}return f};var ml=require("node:child_process"),nt=K(require("node:fs")),fl=K(require("node:os")),ci=K(require("node:path"));var CD="1.37.6",zP={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/"},DD=e=>e.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),qP=(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},VP=e=>e?e.split(`
|
|
128
128
|
`).map(t=>t.trim()).filter(Boolean).join(`
|
|
129
129
|
`):"",vD=e=>{let t=`- **Issue:** ${e.issue}`;return e.recommendation&&(t+=`
|
|
130
130
|
- **Recommendation:** ${VP(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.37.
|
|
3
|
+
"version": "1.37.6",
|
|
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",
|